import { a as useRoute, f as useAuthStore, n as navigateTo, e as useToast } from './server.mjs';
import { d as defineNuxtComponent } from './component.800bf414.mjs';
import { ref, h } from 'vue';
import minimatch from 'minimatch';
import { u as useAPI } from './api.820f4308.mjs';
import 'ofetch';
import 'hookable';
import 'unctx';
import 'destr';
import 'ufo';
import 'h3';
import '@unhead/vue';
import '@unhead/dom';
import 'vue-router';
import '@ebec/http';
import 'hapic';
import 'rapiq';
import '@vue-layout/basic';
import 'change-case';
import '@ucast/mongo2js';
import '@hapic/oauth2';
import '@vuelidate/validators';
import 'ilingo';
import 'nanoid';
import '@vue-layout/hyperscript';
import 'smob';
import 'browser-storage-adapter';
import 'cookie-es';
import 'ohash';
import 'vue/server-renderer';
import 'defu';
import './node-server.mjs';
import 'node-fetch-native/polyfill';
import 'http';
import 'https';
import 'unenv/runtime/fetch/index';
import 'scule';
import 'unstorage';
import 'radix3';
import 'node:fs';
import 'node:url';
import 'pathe';
import './composables.d2421f17.mjs';

function isGlobMatch(target, pattern) {
  const patterns = Array.isArray(pattern) ? pattern : [pattern];
  for (let i = 0; i < patterns.length; i++) {
    if (minimatch(target, patterns[i])) {
      return true;
    }
  }
  return false;
}
function extractOAuth2QueryParameters(query) {
  if (typeof query.client_id !== "string" || !query.client_id || query.client_id.length === 0) {
    throw new Error("The client_id is invalid");
  }
  if (typeof query.redirect_uri !== "string" || !query.redirect_uri || query.redirect_uri.length === 0) {
    throw new Error("The redirect_uri is invalid");
  }
  if (typeof query.response_type === "undefined") {
    query.response_type = "code";
  }
  if (typeof query.response_type !== "string" || query.response_type.length === 0) {
    throw new Error("The response_type is invalid");
  }
  if (typeof query.scope === "undefined") {
    query.scope = "";
  }
  if (Array.isArray(query.scope)) {
    query.scope = query.scope.join(" ");
  }
  return {
    client_id: decodeURIComponent(query.client_id),
    response_type: query.response_type,
    redirect_uri: decodeURIComponent(query.redirect_uri),
    scope: decodeURIComponent(query.scope || "")
  };
}
const authorize = defineNuxtComponent({
  async setup() {
    const route = useRoute();
    const authStore = useAuthStore();
    if (!authStore.loggedIn) {
      return navigateTo({
        path: "/login",
        query: {
          ...route.query,
          redirect: route.path
        }
      });
    }
    const renderError = (message) => h("div", { class: "d-flex align-items-center justify-content-center h-100" }, [
      h("div", { class: "oauth2-wrapper panel-card p-3 flex-column" }, [
        h("div", { class: "text-center" }, [
          h("i", { class: "fa-solid fa-exclamation fa-10x text-danger" })
        ]),
        h("div", { class: "text-center fs-6 p-3" }, [
          message
        ])
      ])
    ]);
    const parameters = extractOAuth2QueryParameters(route.query);
    const entity = ref(null);
    try {
      entity.value = await useAPI().client.getOne(parameters.client_id);
    } catch (e) {
      return () => renderError([
        "The",
        h("strong", { class: "ps-1 pe-1" }, "client_id"),
        "is invalid"
      ]);
    }
    const redirectUriPatterns = (entity.value.redirect_uri || "").split(",");
    if (!isGlobMatch(parameters.redirect_uri, redirectUriPatterns)) {
      return () => renderError([
        "The",
        h("strong", { class: "ps-1 pe-1" }, "redirect_uri"),
        "does not match."
      ]);
    }
    let scopeNames = [];
    if (typeof parameters.scope === "string" && parameters.scope.length > 0) {
      scopeNames = parameters.scope.split(" ");
    }
    const clientScopeQuery = {
      filter: {
        client_id: entity.value.id
      },
      relations: ["scope"]
    };
    if (clientScopeQuery.filter && scopeNames.length > 0) {
      clientScopeQuery.filter.scope = {
        name: scopeNames
      };
    }
    const { data: clientScopes } = await useAPI().clientScope.getMany(clientScopeQuery);
    const abort = () => {
      const url = new URL(`${parameters.redirect_uri}`);
      url.searchParams.set("error", "access_denied");
      url.searchParams.set(
        "error_description",
        "The resource owner or authorization server denied the request"
      );
      if (route.query.state && typeof route.query.state === "string") {
        url.searchParams.set("state", route.query.state);
      }
      window.location.href = url.href;
    };
    const authorize2 = async () => {
      try {
        const response = await useAPI().post("authorize", {
          response_type: parameters.response_type,
          client_id: entity.value.id,
          redirect_uri: parameters.redirect_uri,
          ...route.query.state ? { state: route.query.state } : {},
          scope: clientScopes.map((item) => item.scope.name).join(" ")
        });
        const { url } = response.data;
        window.location.href = url;
      } catch (e) {
        if (e instanceof Error) {
          const toast = useToast();
          toast.warning(e.message);
        }
      }
    };
    const render = () => {
      const headerView = h("div", { class: "flex-column d-flex" }, [
        h("div", { class: "text-center text-secondary" }, [
          h("div", "An external application"),
          h("div", { class: "fs-5 fw-bold" }, entity.value.name),
          h("div", "wants to access your account")
        ])
      ]);
      ({
        client_id: entity.value.id
      });
      if (scopeNames.length > 0)
        ;
      const scopeItems = clientScopes.map((clientScope) => h("div", { class: "d-flex flex-row" }, [
        h("div", { style: { width: "15px" }, class: "text-center" }, [
          h("i", { class: "fa-solid fa-check text-success" })
        ]),
        h("div", { class: "ms-1" }, [
          h("small", [
            clientScope.scope.name
          ])
        ])
      ]));
      const scopeView = h("div", { class: "mt-2 mb-2" }, [
        h("div", [
          "This will allow the",
          h("strong", { class: "ps-1 pe-1" }, entity.value.name),
          "developer to:"
        ]),
        h("div", { class: "flex-column" }, [
          scopeItems
        ])
      ]);
      const detailsView = h("div", { class: "mt-auto" }, [
        h("div", { class: "d-flex flex-row" }, [
          h("div", [
            h("i", { class: "fa-solid fa-link" })
          ]),
          h("div", { class: "ms-1" }, [
            h("small", [
              "Once authorized, you will be redirected to:",
              " ",
              parameters.redirect_uri
            ])
          ])
        ]),
        h("div", { class: "d-flex flex-row" }, [
          h("div", [
            h("i", { class: "fa-solid fa-lock" })
          ]),
          h("div", { class: "ms-1" }, [
            h("small", [
              "This application is governed by the",
              h("strong", { class: "ps-1 pe-1" }, entity.value.name),
              "developer's Privacy Policy and Terms of Service."
            ])
          ])
        ]),
        h("div", { class: "d-flex flex-row" }, [
          h("div", [
            h("i", { class: "fa-solid fa-clock" })
          ]),
          h("div", { class: "ms-1" }, [
            h("small", [
              "Active since",
              " ",
              `${entity.value.created_at}`
            ])
          ])
        ])
      ]);
      const footerView = h("div", { class: "d-flex justify-content-evenly mt-auto" }, [
        h("div", [
          h("button", {
            type: "button",
            class: "btn btn-sm btn-secondary",
            onClick: ($event) => {
              $event.preventDefault();
              return abort();
            }
          }, [
            "Abort"
          ])
        ]),
        h("div", [
          h("button", {
            type: "button",
            class: "btn btn-sm btn-primary",
            onClick: ($event) => {
              $event.preventDefault();
              return authorize2();
            }
          }, [
            "Authorize"
          ])
        ])
      ]);
      return h("div", { class: "d-flex align-items-center justify-content-center h-100" }, [
        h("div", { class: "oauth2-wrapper panel-card p-3 flex-column" }, [
          headerView,
          scopeView,
          detailsView,
          footerView
        ])
      ]);
    };
    return () => render();
  }
});

export { authorize as default };
//# sourceMappingURL=authorize.f61e73aa.mjs.map
