UNPKG

@kinde-oss/kinde-auth-react

Version:

Kinde React SDK for authentication

370 lines (369 loc) 9.91 kB
import { K as B } from "./useKindeAuth-BArWbaqf.js"; import { u as Le } from "./useKindeAuth-BArWbaqf.js"; import { jsx as x, Fragment as K } from "react/jsx-runtime"; import { E as Q, I as Y, a as Z, j as ee, c as J, S as L, b as j, T as N, d as F, G as T, H as z, i as f, x as G, _ as re, e as te, F as se, o as ne, z as oe, L as U, R as ae, f as H, W as ie, M as ce, y as b, g as ue, C as ge } from "./index-7XdJNziI.js"; import le, { useState as de, useRef as me, useEffect as C, useCallback as w, useMemo as fe } from "react"; var a = /* @__PURE__ */ ((n) => (n.domain = "domain", n.clientId = "client_id", n.audience = "audience", n.redirectUri = "redirect_uri", n.logoutUri = "logout_uri", n.performingLogout = "performing_logout", n))(a || {}); const g = new Y(), E = new Q(); Z(g); ee(E); const I = (n) => n || window.location.origin, we = "5.6.0", he = { version: we }; J.keyPrefix = ""; const Se = () => { window.history.replaceState({}, document.title, window.location.pathname); }, Re = { onSuccess: Se }, Pe = ({ audience: n, scope: M, clientId: u, children: V, domain: l, useInsecureForRefreshToken: $ = !1, redirectUri: d, callbacks: W = {}, logoutUri: S, forceChildrenRender: X = !1, popupOptions: R = {} }) => { const s = { ...Re, ...W }; L.framework = "react", L.frameworkVersion = le.version, L.sdkVersion = he.version, J.useInsecureForRefreshToken = $; const [y, h] = de({ user: void 0, isAuthenticated: !1, isLoading: !0 }), _ = me(!1); C(() => { g.setItems({ [a.domain]: l, [a.clientId]: u, [a.audience]: n, [a.redirectUri]: d, [a.logoutUri]: S }); }, [n, M, u, l, d, S]); const k = w( async (e = {}) => { const o = e.state || {}; e.state = void 0; const r = { audience: n, clientId: u, ...e, supportsReauth: !0, state: j( JSON.stringify({ kinde: { event: "login" /* login */ }, ...o }) ), redirectURL: I(e.redirectURL || d) }, t = await g.getSessionItem( a.domain ), i = await N( t, F.login, r ); try { T({ url: i.url.toString(), popupOptions: R, handleResult: P }); } catch (m) { s.onError?.( { error: "ERR_POPUP", errorDescription: m.message }, {}, {} ); } }, [n, u, d, R, s] ), A = w( async (e = {}) => { const o = e.state || {}; e.state = void 0; const r = { ...e, state: j( JSON.stringify({ kinde: { event: "register" /* register */ }, ...o }) ), supportsReauth: !0, audience: await g.getSessionItem( a.audience ), clientId: await g.getSessionItem( a.clientId ), redirectURL: I(e?.redirectURL || d), prompt: z.create }; try { const t = await g.getSessionItem( a.domain ), i = await N( t, F.register, r ); try { T({ url: i.url.toString(), popupOptions: R, handleResult: P }); } catch (m) { s.onError?.( { error: "ERR_POPUP", errorDescription: m.message }, {}, {} ); } } catch (t) { console.error("Register error:", t), s.onError?.( { error: "ERR_REGISTER", errorDescription: String(t) }, {}, c ); } }, [d, R, s] ), O = w(async (e) => { try { const o = await g.getSessionItem( a.domain ), r = new URLSearchParams(); e ? e && typeof e == "string" ? r.append("redirect", e) : typeof e == "object" && ((e.redirectUrl || S) && r.append("redirect", e.redirectUrl || S || ""), e.allSessions && r.append("all_sessions", String(e.allSessions))) : r.append("redirect", S || ""), h((t) => ({ ...t, user: void 0, isAuthenticated: !1 })), await Promise.all([ g.removeSessionItem(f.idToken), g.removeSessionItem(f.accessToken), g.removeSessionItem(f.refreshToken), E.removeSessionItem(f.refreshToken) ]), await E.setSessionItem( a.performingLogout, "true" ); try { await T({ url: `${o}/logout?${r.toString()}`, popupOptions: R }); } catch (t) { s.onError?.( { error: "ERR_POPUP", errorDescription: t.message }, {}, {} ); } } catch (o) { console.error("Logout error:", o), s.onError?.( { error: "ERR_LOGOUT", errorDescription: String(o) }, {}, c ); } }, []), c = fe(() => ({ // Internal Methods login: k, logout: O, register: A, getIdToken: async () => await b()?.getSessionItem(f.idToken), getAccessToken: async () => await b()?.getSessionItem( f.accessToken ), /** @deprecated use `getAccessToken` instead */ getToken: async () => await b()?.getSessionItem( f.accessToken ), getClaim: async (e, o) => ce(e, o), getClaims: async (...e) => ie(...e), /** @deprecated use `getCurrentOrganization` instead */ getOrganization: async () => await H(), getCurrentOrganization: async () => await H(), getFlag: async (e) => await ae(e), getUserProfile: async () => U(), getPermission: async (e) => await oe(e), getPermissions: async () => ne(), getUserOrganizations: async () => await se(), getRoles: async () => await te(), generatePortalUrl: async (e) => await re({ domain: l, returnUrl: e.returnUrl || window.location.href, subNav: e.subNav }), refreshToken: async (...e) => await G(...e), ...y }), [y, k, O, A]), v = w( (e) => { s.onEvent && s.onEvent("tokenRefreshed", e, c); }, [s, c] ), P = w( async (e) => { const o = atob(e.get("state") || ""); let r, t; try { r = JSON.parse(o), t = Object.assign( r.kinde || { event: z.login } ); } catch (i) { console.error("Error parsing state:", i), s.onError?.( { error: "ERR_STATE_PARSE", errorDescription: String(i) }, {}, c ), r = {}, t = { event: "login" /* login */ }; } try { const i = await ue({ urlParams: e, domain: l, clientId: u, redirectURL: I(d), autoRefresh: !0, onRefresh: v }); if (i.success) { const m = await U(); m && (h((q) => ({ ...q, user: m, isAuthenticated: !0 })), s.onSuccess?.( m, { ...r, kinde: void 0 }, c ), s.onEvent && s.onEvent( t.event, { ...r, kinde: void 0 }, c )); } else s.onError?.( { error: "ERR_CODE_EXCHANGE", errorDescription: i.error }, r, c ); } catch (i) { s.onError?.( { error: "ERR_POPUP_AUTH", errorDescription: String(i) }, r, c ); } finally { h((i) => ({ ...i, isLoading: !1 })); } }, [l, u, d, v, s, c] ), p = w(() => { document.visibilityState === "visible" && y.isAuthenticated && G({ domain: l, clientId: u, onRefresh: v }).catch((e) => { console.error("Error refreshing token:", e); }); }, [y.isAuthenticated, l, u, v]); C(() => (document.removeEventListener("visibilitychange", p), document.addEventListener("visibilitychange", p), () => { document.removeEventListener("visibilitychange", p); }), [p]); const D = w(async () => { if (_.current) return; await ge({ domain: l, clientId: u }), _.current = !0; const e = new URLSearchParams(window.location.search); if (e.has("error")) { if (e.get("error")?.toLowerCase() === "login_link_expired") { const t = e.get("reauth_state"); t && k({ reauthState: t }); return; } h((t) => ({ ...t, isLoading: !1 })); return; } if (await E.getSessionItem( a.performingLogout ) === "true" && (await E.removeSessionItem( a.performingLogout ), window.close()), !e.has("code")) { try { const r = await U(); r && h((t) => ({ ...t, user: r, isAuthenticated: !0 })); } catch (r) { console.warn("Error getting user profile", r); } finally { h((r) => ({ ...r, isLoading: !1 })); } return; } if (window.opener) { const r = new URLSearchParams(window.location.search); window.opener.postMessage( { type: "KINDE_AUTH_RESULT", result: Object.fromEntries(r.entries()) }, window.location.origin ), window.close(); } await P(new URLSearchParams(window.location.search)); }, [ u, l, d, s, c, v, k, P ]); return C(() => { const e = { current: !0 }; return e.current && D(), () => { e.current = !1; }; }, [D]), X || _.current ? /* @__PURE__ */ x(B.Provider, { value: c, children: V }) : /* @__PURE__ */ x(K, {}); }; export { B as KindeContext, Pe as KindeProvider, Le as useKindeAuth };