@axa-fr/react-oidc
Version:
OpenID Connect & OAuth authentication using react
408 lines (407 loc) • 14.5 kB
JavaScript
import { OidcClient as e, OidcClient as t, OidcLocation as n, OidcLocation as r, TokenAutomaticRenewMode as i, TokenRenewMode as a, getFetchDefault as o, getParseQueryStringFromLocation as s, getPath as c } from "@axa-fr/oidc-client";
import l, { useCallback as u, useEffect as d, useRef as f, useState as p } from "react";
import { Fragment as m, jsx as h, jsxs as g } from "react/jsx-runtime";
//#region src/FetchToken.tsx
var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithTokens(e, n)(...r), y = (e = null, t = _, n = !1) => (r) => (i) => {
let { fetch: a } = b(e || i.fetch, t, n);
return /* @__PURE__ */ h(r, {
...i,
fetch: a
});
}, b = (e = null, n = _, r = !1) => {
let i = e || window.fetch, a = t.get;
return { fetch: u((e, t) => v(i, () => a(n), r)(e, t), [
i,
n,
r
]) };
}, x = () => /* @__PURE__ */ h("div", {
className: "oidc-authenticating",
children: /* @__PURE__ */ g("div", {
className: "oidc-authenticating__container",
children: [/* @__PURE__ */ h("h1", {
className: "oidc-authenticating__title",
children: "Error authentication"
}), /* @__PURE__ */ h("p", {
className: "oidc-authenticating__content",
children: "An error occurred during authentication."
})]
})
}), S = () => /* @__PURE__ */ h("div", {
className: "oidc-authenticating",
children: /* @__PURE__ */ g("div", {
className: "oidc-authenticating__container",
children: [/* @__PURE__ */ h("h1", {
className: "oidc-authenticating__title",
children: "Authentication in progress"
}), /* @__PURE__ */ h("p", {
className: "oidc-authenticating__content",
children: "You will be redirected to the login page."
})]
})
}), C = () => Math.random().toString(36).slice(2, 8), w = (e, t) => (n, r) => {
if (typeof e.CustomEvent == "function") return new e.CustomEvent(n, r);
let i = r || {
bubbles: !1,
cancelable: !1,
detail: void 0
}, a = t.createEvent("CustomEvent");
return a.initCustomEvent(n, i.bubbles, i.cancelable, i.detail), a.prototype = e.Event.prototype, a;
}, T = (e, t, n) => ({ replaceState: (r, i) => {
let a = n(), o = i || e.history.state;
e.history.replaceState({
key: a,
state: o
}, null, r), e.dispatchEvent(t("popstate"));
} }), E = () => T(window, w(window, document), C), D = () => /* @__PURE__ */ h("div", {
className: "oidc-callback",
children: /* @__PURE__ */ g("div", {
className: "oidc-callback__container",
children: [/* @__PURE__ */ h("h1", {
className: "oidc-callback__title",
children: "Authentication complete"
}), /* @__PURE__ */ h("p", {
className: "oidc-callback__content",
children: "You will be redirected to your application."
})]
})
}), O = ({ callBackError: e, callBackSuccess: n, configurationName: r, withCustomHistory: i }) => {
let [a, o] = p(!1);
return d(() => {
let e = !0;
return (async () => {
let n = t.get;
try {
let { callbackPath: e } = await n(r).loginCallbackAsync();
(i ? i() : E()).replaceState(e || "/");
} catch (t) {
e && (console.warn(t), o(!0));
}
})(), () => {
e = !1;
};
}, []), h(a ? e || x : n || D, { configurationName: r });
}, k = () => /* @__PURE__ */ h("span", {
className: "oidc-loading",
children: "Loading"
}), A = () => /* @__PURE__ */ h("div", {
className: "oidc-serviceworker",
children: /* @__PURE__ */ g("div", {
className: "oidc-serviceworker__container",
children: [/* @__PURE__ */ h("h1", {
className: "oidc-serviceworker__title",
children: "Unable to authenticate on this browser"
}), /* @__PURE__ */ h("p", {
className: "oidc-serviceworker__content",
children: "Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser."
})]
})
}), j = () => /* @__PURE__ */ h("div", {
className: "oidc-session-lost",
children: /* @__PURE__ */ g("div", {
className: "oidc-session-lost__container",
children: [/* @__PURE__ */ h("h1", {
className: "oidc-session-lost__title",
children: "Session timed out"
}), /* @__PURE__ */ h("p", {
className: "oidc-session-lost__content",
children: "Your session has expired. Please re-authenticate."
})]
})
}), M = ({ configurationName: e }) => (d(() => {
(async () => {
t.get(e).silentLoginCallbackAsync();
})().catch((e) => {
console.error("Error during silent login callback:", e);
});
}, [e]), null), N = ({ configurationName: e }) => {
let n = s(window.location.href), r = t.get, i = r(e), a = null;
for (let [e, t] of Object.entries(n)) e === "state" || e === "scope" || (a === null && (a = {}), a[e] = t);
return d(() => {
i.tokens || i.loginAsync(null, a, !0, n.scope);
}, []), /* @__PURE__ */ h(m, {});
}, P = l.memo(({ callbackErrorComponent: e, callbackSuccessComponent: t, redirect_uri: n, silent_redirect_uri: r, silent_login_uri: i, children: a, configurationName: o, withCustomHistory: s = null }) => {
let [l, u] = p(window ? c(window.location.href) : "");
d(() => {
let e = () => u(c(window.location.href));
return e(), window.addEventListener("popstate", e, !1), () => window.removeEventListener("popstate", e, !1);
}, []);
let f = c(n);
if (r && l === c(r)) return /* @__PURE__ */ h(M, { configurationName: o });
if (i && l === c(i)) return /* @__PURE__ */ h(N, { configurationName: o });
switch (l) {
case f: return /* @__PURE__ */ h(O, {
callBackError: e,
callBackSuccess: t,
configurationName: o,
withCustomHistory: s
});
default: return /* @__PURE__ */ h(m, { children: a });
}
}), F = {
name: "",
data: null
}, I = ({ loadingComponent: e, children: n, configurationName: r }) => {
let [i, a] = p(!0), o = t.get, s = o(r);
return d(() => {
let e = !0;
return s && s.tryKeepExistingSessionAsync().then(() => {
e && a(!1);
}), () => {
e = !1;
};
}, [r]), /* @__PURE__ */ h(m, { children: i ? /* @__PURE__ */ h(e, { configurationName: r }) : /* @__PURE__ */ h(m, { children: n }) });
}, L = ({ isLoading: e, loadingComponent: t, children: n, configurationName: r }) => e ? /* @__PURE__ */ h(t, {
configurationName: r,
children: n
}) : /* @__PURE__ */ h(m, { children: n }), R = ({ children: e, configuration: n, configurationName: i = "default", callbackSuccessComponent: a = D, authenticatingComponent: s = S, loadingComponent: c = k, serviceWorkerNotSupportedComponent: l = A, authenticatingErrorComponent: u = x, sessionLostComponent: f = j, onSessionLost: m = null, onLogoutFromAnotherTab: g = null, onLogoutFromSameTab: _ = null, withCustomHistory: v = null, onEvent: y = null, getFetch: b = null, location: C = null }) => {
if (n && n.redirect_uri && n.silent_redirect_uri && n.redirect_uri === n.silent_redirect_uri) throw Error("redirect_uri and silent_redirect_uri must be different");
let w = (e = "default") => t.getOrCreate(b ?? o, C ?? new r())(n, e), [T, E] = p(F), [O, M] = p(i);
d(() => {
let e = w(i).subscribeEvents((e, t) => {
y && y(i, e, t);
});
return () => {
w(i).removeEventSubscription(e);
};
}, [i, y]), d(() => {
let e = w(i).subscribeEvents((e, r) => {
if (e === t.eventNames.refreshTokensAsync_error || e === t.eventNames.syncTokensAsync_error) {
if (m != null) {
m();
return;
}
E({
name: e,
data: r
});
} else if (e === t.eventNames.logout_from_another_tab) {
if (g != null) {
g();
return;
}
E({
name: e,
data: r
});
} else e === t.eventNames.logout_from_same_tab ? _?.() : (e === t.eventNames.loginAsync_begin || e === t.eventNames.loginCallbackAsync_end || e === t.eventNames.loginAsync_error || e === t.eventNames.loginCallbackAsync_error || e === t.eventNames.service_worker_not_supported_by_browser && n.service_worker_only === !0) && E({
name: e,
data: r
});
});
return queueMicrotask(() => {
M(i);
}), () => {
w(i).removeEventSubscription(e), E(F);
};
}, [n, i]);
let N = f, R = s, z = c, B = l, V = u, H = O !== i, U = w(i);
switch (T.name) {
case t.eventNames.service_worker_not_supported_by_browser: return /* @__PURE__ */ h(L, {
loadingComponent: z,
isLoading: H,
configurationName: i,
children: /* @__PURE__ */ h(B, { configurationName: i })
});
case t.eventNames.loginAsync_begin: return /* @__PURE__ */ h(L, {
loadingComponent: z,
isLoading: H,
configurationName: i,
children: /* @__PURE__ */ h(R, { configurationName: i })
});
case t.eventNames.loginAsync_error:
case t.eventNames.loginCallbackAsync_error: return /* @__PURE__ */ h(L, {
loadingComponent: z,
isLoading: H,
configurationName: i,
children: /* @__PURE__ */ h(V, { configurationName: i })
});
case t.eventNames.refreshTokensAsync_error:
case t.eventNames.syncTokensAsync_error:
case t.eventNames.logout_from_another_tab: return /* @__PURE__ */ h(L, {
loadingComponent: z,
isLoading: H,
configurationName: i,
children: /* @__PURE__ */ h(N, { configurationName: i })
});
default: return /* @__PURE__ */ h(L, {
loadingComponent: z,
isLoading: H,
configurationName: i,
children: /* @__PURE__ */ h(P, {
redirect_uri: U.configuration.redirect_uri,
silent_redirect_uri: U.configuration.silent_redirect_uri,
silent_login_uri: U.configuration.silent_login_uri,
callbackSuccessComponent: a,
callbackErrorComponent: u,
authenticatingComponent: s,
configurationName: i,
withCustomHistory: v,
location: C ?? new r(),
children: /* @__PURE__ */ h(I, {
loadingComponent: z,
configurationName: i,
children: e
})
})
});
}
}, z = ({ children: e, callbackPath: n = null, extras: r = null, configurationName: i = "default" }) => {
let a = t.get, o = a(i);
return d(() => {
o.tokens || o.loginAsync(n, r);
}, [
i,
n,
r
]), o.tokens ? /* @__PURE__ */ h(m, { children: e }) : null;
}, B = (e, t = null, n = null, r = "default") => (i) => /* @__PURE__ */ h(z, {
callbackPath: t,
extras: n,
configurationName: r,
children: /* @__PURE__ */ h(e, { ...i })
}), V = "default", H = (e, t) => {
let n = !1;
return e(t) && (n = e(t).tokens != null), n;
}, U = (e = V) => {
let n = t.get, [r, i] = p(() => H(n, e));
return d(() => {
let r = !0, a = n(e), o = a.subscribeEvents((a, o) => {
(a === t.eventNames.logout_from_another_tab || a === t.eventNames.logout_from_same_tab || a === t.eventNames.token_acquired) && r && i(H(n, e));
});
return () => {
r = !1, a.removeEventSubscription(o);
};
}, [e]), {
login: (t = void 0, r = void 0, i = !1, a = void 0) => n(e).loginAsync(t, r, !1, a, i),
logout: (t = void 0, r = void 0) => n(e).logoutAsync(t, r),
renewTokens: async (t = void 0) => {
let r = await n(e).renewTokensAsync(t);
return {
accessToken: r.accessToken,
accessTokenPayload: r.accessTokenPayload,
idToken: r.idToken,
idTokenPayload: r.idTokenPayload
};
},
isAuthenticated: r
};
}, W = {
accessToken: null,
accessTokenPayload: null
}, G = (e) => {
let n = t.get, r = n(e);
if (r.tokens) {
let e = r.tokens;
return {
accessToken: e.accessToken,
accessTokenPayload: e.accessTokenPayload,
generateDemonstrationOfProofOfPossessionAsync: r.configuration.demonstrating_proof_of_possession ? (t, n) => r.generateDemonstrationOfProofOfPossessionAsync(e.accessToken, t, n) : null
};
}
return W;
};
function K(e, t) {
return e.configuration.demonstrating_proof_of_possession ? (n, r, i = {}) => e.generateDemonstrationOfProofOfPossessionAsync(t.accessToken, n, r, i) : null;
}
var q = (e = V) => {
let n = t.get, [r, i] = p(() => G(e));
return d(() => {
let r = !0, a = n(e), o = a.subscribeEvents((e, n) => {
if ((e === t.eventNames.token_renewed || e === t.eventNames.token_acquired || e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab || e === t.eventNames.refreshTokensAsync_error || e === t.eventNames.syncTokensAsync_error) && r) {
let e = a.tokens;
i(e == null ? W : {
accessToken: e.accessToken,
accessTokenPayload: e.accessTokenPayload,
generateDemonstrationOfProofOfPossessionAsync: K(a, e)
});
}
});
return () => {
r = !1, a.removeEventSubscription(o);
};
}, [e]), r;
}, J = {
idToken: null,
idTokenPayload: null
}, Y = (e) => {
let n = t.get, r = n(e);
if (r.tokens) {
let e = r.tokens;
return {
idToken: e.idToken,
idTokenPayload: e.idTokenPayload
};
}
return J;
}, X = (e = V) => {
let n = t.get, [r, i] = p(() => Y(e));
return d(() => {
let r = !0, a = n(e), o = a.subscribeEvents((e, n) => {
if ((e === t.eventNames.token_renewed || e === t.eventNames.token_acquired || e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab || e === t.eventNames.refreshTokensAsync_error || e === t.eventNames.syncTokensAsync_error) && r) {
let e = a.tokens;
i(e == null ? J : {
idToken: e.idToken,
idTokenPayload: e.idTokenPayload
});
}
});
return () => {
r = !1, a.removeEventSubscription(o);
};
}, [e]), r;
}, Z = /* @__PURE__ */ function(e) {
return e.Unauthenticated = "Unauthenticated", e.Loading = "Loading user", e.Loaded = "User loaded", e.LoadingError = "Error loading user", e;
}({}), Q = (e = "default", n = !1) => {
let r = t.get(e).userInfo(), [i, a] = p({
user: r,
status: r ? "User loaded" : "Unauthenticated"
}), [o, s] = p(+!!r), c = f(+!!r);
return d(() => {
let r = t.get(e), s = !0;
if (r && r.tokens) {
let e = o === c.current;
if (e && r.userInfo()) return;
c.current = o, queueMicrotask(() => {
s && a({
...i,
status: "Loading user"
});
}), r.userInfoAsync(!e, n).then((e) => {
s && a({
user: e,
status: "User loaded"
});
}).catch(() => a({
...i,
status: "Error loading user"
}));
} else queueMicrotask(() => {
s && a({
user: null,
status: "Unauthenticated"
});
});
let l = r.subscribeEvents((e) => {
(e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab) && s && a({
user: null,
status: "Unauthenticated"
});
});
return () => {
s = !1, r.removeEventSubscription(l);
};
}, [
o,
e,
n
]), {
oidcUser: i.user,
oidcUserLoadingState: i.status,
reloadOidcUser: () => {
s(o + 1);
}
};
};
//#endregion
export { e as OidcClient, n as OidcLocation, R as OidcProvider, z as OidcSecure, Z as OidcUserStatus, i as TokenAutomaticRenewMode, a as TokenRenewMode, U as useOidc, q as useOidcAccessToken, b as useOidcFetch, X as useOidcIdToken, Q as useOidcUser, y as withOidcFetch, B as withOidcSecure };