import { executeAsync } from 'unctx';
import { useSSRContext, ref, mergeProps } from 'vue';
import { _ as _export_sfc, d as defineNuxtComponent, f as useRoute, g as useAuthStore, s as storeToRefs, n as navigateTo, c as createError } from '../server.mjs';
import { useToast } from 'bootstrap-vue-next';
import { minimatch } from 'minimatch';
import { u as useAPI } from './api-29ff697c.mjs';
import { ssrRenderAttrs, ssrInterpolate, ssrRenderList, ssrRenderStyle } from 'vue/server-renderer';
import 'ofetch';
import 'hookable';
import 'vue-router';
import 'h3';
import 'ufo';
import '@ebec/http';
import 'hapic';
import '@hapic/oauth2';
import 'rapiq';
import '@hapic/vault';
import '@vue-layout/navigation';
import 'destr';
import 'change-case';
import '@vue-layout/list-controls/core';
import '@vue-layout/form-controls';
import 'smob';
import '@vue-layout/list-controls';
import '@vue-layout/pagination';
import '@ucast/mongo2js';
import '@vuelidate/validators';
import 'ilingo';
import '@vuelidate/core';
import 'nanoid';
import '@unhead/ssr';
import 'unhead';
import '@unhead/shared';
import '@vue-layout/preset-bootstrap-v5';
import '@vue-layout/preset-font-awesome';
import '@vue-layout/countdown';
import '@vue-layout/timeago';
import 'browser-storage-adapter';
import 'cookie-es';
import 'ohash';
import 'defu';
import '../../nitro/node-server.mjs';
import 'node-fetch-native/polyfill';
import 'node:http';
import 'node:https';
import 'unenv/runtime/fetch/index';
import 'scule';
import 'klona';
import 'unstorage';
import 'radix3';
import 'node:fs';
import 'node:url';
import 'pathe';
import 'http-graceful-shutdown';

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 _sfc_main = /* @__PURE__ */ defineNuxtComponent({
  async setup() {
    let __temp, __restore;
    const toast = useToast();
    const route = useRoute();
    const store = useAuthStore();
    const { loggedIn } = storeToRefs(store);
    if (!loggedIn.value) {
      [__temp, __restore] = executeAsync(() => navigateTo({
        path: "/login",
        query: {
          ...route.query,
          redirect: route.path
        }
      })), await __temp, __restore();
      throw createError({});
    }
    const parameters = extractOAuth2QueryParameters(route.query);
    const entity = ref(null);
    try {
      entity.value = ([__temp, __restore] = executeAsync(() => useAPI().client.getOne(parameters.client_id)), __temp = await __temp, __restore(), __temp);
    } catch (e) {
      [__temp, __restore] = executeAsync(() => navigateTo({
        path: "/authorize-error",
        query: {
          message: "The client_id is invalid."
        }
      })), await __temp, __restore();
      throw createError({});
    }
    const redirectUriPatterns = (entity.value.redirect_uri || "").split(",");
    if (!isGlobMatch(parameters.redirect_uri, redirectUriPatterns)) {
      [__temp, __restore] = executeAsync(() => navigateTo({
        path: "/authorize-error",
        query: {
          message: "The redirect_uri does not match."
        }
      })), await __temp, __restore();
      throw createError({});
    }
    let scopeNames = [];
    if (typeof parameters.scope === "string" && parameters.scope.length > 0) {
      scopeNames = parameters.scope.split(" ");
    }
    const clientScopeQuery = {
      filter: {
        client_id: entity.value.id,
        ...scopeNames.length > 0 ? { scope: { name: scopeNames } } : {}
      },
      relations: ["scope"]
    };
    const { data: clientScopes } = ([__temp, __restore] = executeAsync(() => useAPI().clientScope.getMany(clientScopeQuery)), __temp = await __temp, __restore(), __temp);
    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 && toast) {
          toast.warning({ body: e.message });
        }
      }
    };
    return {
      abort,
      authorize: authorize2,
      clientScopes,
      entity,
      parameters
    };
  }
}, "$fbcQxgZ2I5");
function _sfc_ssrRender(_ctx, _push, _parent, _attrs, $props, $setup, $data, $options) {
  _push(`<div${ssrRenderAttrs(mergeProps({ class: "d-flex align-items-center justify-content-center h-100" }, _attrs))}><div class="oauth2-wrapper panel-card p-3 flex-column"><div class="flex-column d-flex"><div class="text-center text-secondary"><div>An external application</div><div class="fs-5 fw-bold">${ssrInterpolate(_ctx.entity.name)}</div></div><div class="mt-2 mb-2"><div> This will allow the <strong class="ps-1 pe-1">${ssrInterpolate(_ctx.entity.name)}</strong> developer to: </div><div class="flex-column"><!--[-->`);
  ssrRenderList(_ctx.clientScopes, (item) => {
    _push(`<div class="d-flex flex-row"><div class="text-center" style="${ssrRenderStyle({ "width": "15px" })}"><i class="fa-solid fa-check text-success"></i></div><div class="ms-1"><small>${ssrInterpolate(item.scope.name)}</small></div></div>`);
  });
  _push(`<!--]--></div></div><div class="mt-auto"><div class="d-flex flex-row"><div><i class="fa-solid fa-link"></i></div><div class="ms-1"><small>Once authorized, you will be redirected to: ${ssrInterpolate(_ctx.parameters.redirect_uri)}</small></div></div><div class="d-flex flex-row"><div><i class="fa fa-solid fa-lock"></i></div><div class="ms-1"><small> This application is governed by the <strong class="ps-1 pe-1">${ssrInterpolate(_ctx.entity.name)}</strong> developer&#39;s Privacy Policy and Terms of Service. </small></div></div><div class="d-flex flex-row"><div><i class="fa fa-solid fa-clock"></i></div><div class="ms-1"><small> Active since ${ssrInterpolate(_ctx.entity.created_at)}</small></div></div></div><div class="d-flex justify-content-evenly mt-auto"><div><button type="button" class="btn btn-sm btn-secondary"> Abort </button></div><div><button type="button" class="btn btn-sm btn-primary"> Authorize </button></div></div></div></div></div>`);
}
const _sfc_setup = _sfc_main.setup;
_sfc_main.setup = (props, ctx) => {
  const ssrContext = useSSRContext();
  (ssrContext.modules || (ssrContext.modules = /* @__PURE__ */ new Set())).add("pages/authorize.vue");
  return _sfc_setup ? _sfc_setup(props, ctx) : void 0;
};
const authorize = /* @__PURE__ */ _export_sfc(_sfc_main, [["ssrRender", _sfc_ssrRender]]);

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