UNPKG

@trimble-oss/trimble-id-react

Version:

> **Important Notice:** > > As of version 1.0.0, `PersistentOptions` have been removed. By default, the SDK now supports in-memory token storage. > > When you upgrade to version 1.x, storage options will no longer be available, resulting in a breaking

636 lines (635 loc) 21.5 kB
var F = Object.defineProperty; var B = (i, e, t) => e in i ? F(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t; var c = (i, e, t) => (B(i, typeof e != "symbol" ? e + "" : e, t), t); import { OpenIdEndpointProvider as $, AuthorizationCodeGrantTokenProvider as R, AnalyticsHttpClient as H, BearerTokenHttpClientProvider as Q } from "@trimble-oss/trimble-id"; import * as w from "es-cookie"; import J from "jwt-decode"; import { createContext as q, useContext as L, useState as z, useReducer as X, useRef as Y, useMemo as M, useEffect as D, useCallback as y } from "react"; import { jsx as K, Fragment as Z } from "react/jsx-runtime"; class j { constructor() { /** * This function generate a encapsulation function to store * the user and token information in a secure way disabled the * access from the outside * @see {https://medium.com/javascript-scene/encapsulation-in-javascript-26be60e325b4} Encapsulation * @return {CacheStorage} Key for the token */ c(this, "generateCache", function() { const e = { token: void 0, user: void 0 }; return { /** * Get token store in cache * @return {Promise<TIDAuthToken | undefined>} Token store in memory */ async getToken() { return e.token; }, /** * Get user store in cache * @return {Promise<TIDUser | undefined>} User store in memory */ async getUser() { return e.user; }, /** * Store token in cache * @param {TIDAuthToken} token - Token that you want to store in cache * @return {Promise<void>} Empty promise */ async storeToken(t) { e.token = t; }, /** * Store user in cache * @param {TIDUser} user - User that you want to store in cache * @return {Promise<void>} Empty promise */ async storeUser(t) { e.user = t; }, /** * The clear the cache from the storage * @return {Promise<void>} Empty promise */ clear() { return e.token = void 0, e.user = void 0, Promise.resolve(void 0); } }; }()); } } class ee { constructor() { /** * Cache option selected * @type {CacheStorage} */ c(this, "cacheStorage"); this.cacheStorage = new j().generateCache; } /** * Store token in cache * @param {TIDAuthToken} token - Token that you want to store in cache * @return {Promise<void>} Empty promise */ async setToken(e) { await this.cacheStorage.storeToken(e); } /** * Store user in cache * @param {TIDUser} user - User that you want to store in cache * @return {Promise<void>} Empty promise */ async setUser(e) { await this.cacheStorage.storeUser(e); } /** * Get user store in cache * @return {Promise<TIDUser | undefined>} Key for the user */ async getUser() { return this.cacheStorage.getUser(); } /** * Get token store in cache * @return {Promise<TIDAuthToken | undefined>} Key for the user */ async getToken() { return this.cacheStorage.getToken(); } /** * The clear the cache from the storage * @return {Promise<void>} Empty promise */ async clear() { await this.cacheStorage.clear(); } } const x = 5 * 6e4, te = ["code", "state"], A = (i) => i.split("?")[0], ie = (i) => i.split("?")[1], b = (i) => { let e = i; if (!i.startsWith("?")) try { e = new URL(i).search; } catch { } return new URLSearchParams(e); }, ne = (i = window.location.href, e) => { if (e != null) { const n = A(e), r = A(i ?? ""); if (n !== r) return !1; } const t = b(i); for (const n of te) if (!t.has(n)) return !1; return !0; }, re = (i) => ({ id: i.sub, name: `${i.given_name} ${i.family_name}`, given_name: i.given_name, family_name: i.family_name, picture: i.picture, email: i.email, email_verified: i.email_verified }), se = "@TID_COOKIE"; class oe { /** * Retrieve a cookie from the browser * @param {string} key - Key to retrieve the cookies */ get(e) { const t = w.get(e); if (t == null) throw new Error("Cookie not found"); return JSON.parse(t); } /** * Store cookies in the browser * @param {string} key - Key to save and retrieve the cookies * @param {any} value - Information you want to store in cookies * @param {CookiesOptions} options - Additional options you want to add to the cookies. * @example Save cookies with one day of expiration * cookiesStorage.set('key',{data:{...}},{expires:1}) * @example Save cookies with a custom domain * cookiesStorage.set('key',{data:{...}},{domain:'https://example.com/subpath'}) */ set(e, t, n) { let r = {}; window.location.protocol === "https:" && (r = { secure: !0, sameSite: "none" }), n != null && n.expires && (r.expires = n.expires), n != null && n.domain && (r.domain = n.domain), w.set(e, JSON.stringify(t), r); } /** * Remove a cookie from the browser * @param {string} key - Key to remove the cookies from the browser * @param {CookiesOptions} options - Additional options used when the cookie was declared * @example Remove cookies without additional information * cookiesStorage.remove('key') * @example Remove cookies with custom domain * cookiesStorage.remove('key',{domain:'https://example.com/subpath'}) */ remove(e, t) { const n = {}; t != null && t.domain && (n.domain = t.domain), w.remove(e, n); } } class ae { /** * Create a cookies manager to extract or save cookies in the browser * @param {CookiesManagerOptions} options - Configuration for the managing the cookies */ constructor(e) { /** * Cookie full key to store and retrieve the information from cookies * @type {string} */ c(this, "cookieKey"); /** * Cookie storage. This object contain all functions necessary to retrieve and store tokens using cookies * @type {CookiesStorage} */ c(this, "cookiesStorage"); this.cookieKey = `${se}.${e.clientId}`, this.cookiesStorage = new oe(); } /** * Store cookies in the browser * @param {CookieValue} value - information to store */ save(e) { this.cookiesStorage.set(this.cookieKey, e, { expires: 1 }); } /** * Retrieve cookies in the browser * @return {CookieValue | undefined} - Cookies from the browser */ get() { try { return this.cookiesStorage.get(this.cookieKey); } catch { return; } } /** * Clear information about the cookies stored in the browser */ clear() { this.cookiesStorage.remove(this.cookieKey); } } class U extends Error { } class O extends Error { } class ce extends Error { } const d = "@trimble-oss/trimble-id-react", h = "1.0.0", le = { configurationEndpoint: "", clientId: "", redirectUrl: "", logoutRedirectUrl: "", scopes: [] }; class de { /** * Create a TID client to handle manage all user authentication functions and information * @param {CacheManagerOptions} props - TID client configuration */ constructor(e) { /** * Token provider SDK. This object handles all necessary communication with TID * @type {AuthorizationCodeGrantTokenProvider} */ c(this, "tokenProvider"); /** * This object manage all caching, and all configurations necessary * @type {CacheManager} */ c(this, "cacheManager"); /** * This object manage all cookies administration, and all configurations necessary * @type {CookiesManager} */ c(this, "cookiesManager"); /** * Client id of the application created in trimble developer console * @type {string} */ c(this, "clientId"); /** * Callback url to redirect the user after the authentication is successful * @type {string} */ c(this, "redirectUrl"); /** * AnalyticsHttpClient for sending events * @type {AnalyticsHttpClient} */ c(this, "analyticshttpclient"); const { config: t = le } = e; if (this.redirectUrl = t.redirectUrl, t.configurationEndpoint == null || t.configurationEndpoint == "") throw new Error("Configuration endpoint not defined"); if (t.clientId == null || t.clientId == "") throw new Error("Consumer key is not defined"); this.cookiesManager = new ae({ clientId: t.clientId }); const n = this.cookiesManager.get(), r = new $(t.configurationEndpoint); let a = new R( r, t.clientId, t.redirectUrl ).WithScopes(t.scopes); t.logoutRedirectUrl && (a = a.WithLogoutRedirect(t.logoutRedirectUrl)), (n == null ? void 0 : n.code_verifier) != null && (a = a.WithProofKeyForCodeExchange(n.code_verifier)), this.tokenProvider = a, this.cacheManager = new ee(), this.clientId = t.clientId, this.analyticshttpclient = H, this.analyticshttpclient.sendInitEvent("TIDClient", this.clientId, d, h); } /** * Redirect the user to TID using the browser * @param {LoginWithRedirectOptions} options - Custom configuration for the redirection * @return {Promise<void>} Empty promise * @example No configuration * loginWithRedirect() * // Automatically redirects the user to TID with all necessary parameters * @example Custom redirect * loginWithRedirect({onRedirect: (url) => router.navigate(url)}) * // Redirect calls onRedirect with the log-out url for TID * // So it can be handled by the developer */ async loginWithRedirect(e) { this.analyticshttpclient.sendMethodEvent(this.loginWithRedirect.name, this.clientId, d, h); const { onRedirect: t } = e || {}, n = R.GenerateCodeVerifier(); this.cookiesManager.save({ code_verifier: n }), this.tokenProvider = this.tokenProvider.WithProofKeyForCodeExchange(n); const r = await this.tokenProvider.GetOAuthRedirect("state"); t != null ? t(r) : window.location.assign(r); } /** * Authenticated the user using the url callback params * @param {string} url - Custom configuration for the redirection * @return {Promise<AuthState>} Object contain the state returned from TID * @throws {CodeVerifierNotFoundException} Will throw an exception if the session doesn't contain the code verifier * @example No configuration * handleCallback() * // Will automatically take the url from the browser and try to log in the user * @example Custom url * handleCallback('https://example.com?code=code....') * // Will try to log in the user with the url assign by the developer */ async handleCallback(e = window.location.href) { const t = this.cookiesManager.get(); if (t == null || (t == null ? void 0 : t.code_verifier) == null) throw new ce("Code verifier not available"); const n = ie(e), r = b(e), a = r.get("identity_provider") ?? "", g = r.get("state") ?? ""; return await this.tokenProvider.ValidateQuery(n), await this.generateToken(a), { authState: g }; } /** * Function to generate and store the access token * @param {string} identityProvider - Type of identity provider used * @return {Promise<void>} Empty promise */ async generateToken(e) { var s, f; const t = await this.tokenProvider.RetrieveToken(), n = await this.tokenProvider.RetrieveRefreshToken(), r = await this.tokenProvider.RetrieveIdToken(), a = await this.tokenProvider.RetrieveTokenExpiry(), k = new Date(a).getTime(), v = (f = (s = this.tokenProvider) == null ? void 0 : s._scopes) == null ? void 0 : f.join(" "); await this.cacheManager.setToken({ scope: v, state: "", session_state: "", identity_provider: e, token_type: "bearer", access_token: t, refresh_token: n, id_token: r, expires_at: k }); const m = J(r), T = re(m); await this.cacheManager.setUser(T), await this.reloadCodeVerifier(); } async reloadCodeVerifier() { const e = await this.tokenProvider.RetrieveCodeVerifier(); this.cookiesManager.save({ code_verifier: e }), this.tokenProvider = this.tokenProvider.WithProofKeyForCodeExchange(e); } /** * Return the user stored in cache * @return {Promise<TIDUser | undefined>} User in cache */ async getUser() { return this.analyticshttpclient.sendMethodEvent(this.getUser.name, this.clientId, d, h), await this.cacheManager.getUser(); } /** * Gets the access token from cache. If the token already expired, * will try to refresh it using the refresh token * @return {Promise<string>} Access token * @throws {TokenNotFoundException} Will throw an exception if the access token is not in cache * @throws {TokenExpiredException} Will throw an exception if the user token expired */ async getAccessTokenSilently() { this.analyticshttpclient.sendMethodEvent(this.getAccessTokenSilently.name, this.clientId, d, h); let e = await this.cacheManager.getToken(); if (e == null) throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name, "No token available", this.clientId, d, h), new O("No token available"); const t = new Date((/* @__PURE__ */ new Date()).getTime() + x); if ((e == null ? void 0 : e.expires_at) == null || (e == null ? void 0 : e.expires_at) < t.getTime()) { try { await this.tokenProvider.RetrieveToken(); } catch (n) { throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name, n.message, this.clientId, d, h), new U(n.message); } await this.generateToken((e == null ? void 0 : e.identity_provider) ?? ""), e = await this.cacheManager.getToken(); } return (e == null ? void 0 : e.access_token) || ""; } /** * Retrieves token details from the cache, including the access token, ID token, and expiration time. * If the token already expired, will try to refresh it using the refresh token. * @return {Promise<TokenResponse>} Token response * @throws {TokenNotFoundException} Will throw an exception if there are no tokens in cache * @throws {TokenExpiredException} Will throw an exception if the user token expired */ async getTokens() { this.analyticshttpclient.sendMethodEvent(this.getTokens.name, this.clientId, d, h); let e = await this.cacheManager.getToken(); if (e == null) throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name, "No token available", this.clientId, d, h), new O("No token available"); const t = new Date((/* @__PURE__ */ new Date()).getTime() + x); if ((e == null ? void 0 : e.expires_at) == null || (e == null ? void 0 : e.expires_at) < t.getTime()) { try { await this.tokenProvider.RetrieveToken(); } catch (n) { throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name, n.message, this.clientId, d, h), new U(n.message); } await this.generateToken((e == null ? void 0 : e.identity_provider) ?? ""), e = await this.cacheManager.getToken(); } return { access_token: (e == null ? void 0 : e.access_token) || "", expires_at: (e == null ? void 0 : e.expires_at) || 0, id_token: (e == null ? void 0 : e.id_token) || "" }; } /** * Redirect the user to TID using the browser * @param {LogoutOptions} options - Custom configuration for teh redirection * @return {Promise<void>} Empty promise * @example No configuration * logout() * // Automatically redirects the user to TID to log out * @example Custom redirect * logout({onRedirect: (url) => router.navigate(url)}) * // Redirect calls onRedirect with the log-out url for TID * // So it can be handled by the developer */ async logout(e) { this.analyticshttpclient.sendMethodEvent(this.logout.name, this.clientId, d, h); const { onRedirect: t, disabledAutoRedirect: n } = e || {}; this.cacheManager && await this.cacheManager.clear(), this.cookiesManager && this.cookiesManager.clear(); const r = await this.tokenProvider.GetOAuthLogoutRedirect("state"); if (t != null) return t(r); n || window.location.assign(r); } /** * Check if the user still has a valid session * @return {Promise<boolean>} True or false depending on if the user is session is valid or not */ async checkSession() { try { await this.getAccessTokenSilently(); } catch { return !1; } return !0; } /** * Check if the user has a session valid after a refresh * @return {Promise<void>} Empty promise */ async loadUserSession() { await this.loadCacheSessionIntoSDK(), await this.checkSession() || await this.cacheManager.clear(); } /** * Load the user session from cache into the SDK * @return {Promise<void>} Empty promise */ async loadCacheSessionIntoSDK() { const e = await this.cacheManager.getToken(); if (e == null) return; const t = e.access_token, n = e.refresh_token || "", r = e.id_token, a = e.expires_at; this.tokenProvider = this.tokenProvider.WithAccessToken(t, a).WithRefreshToken(n).WithIdToken(r); } /** * Get a http bearer token client to use it for another SDK (Ex: Processing framework) * @return {any} - BearerTokenHttpClientProvider */ getBearerTokenHttpClient(e) { return new Q(this.tokenProvider, e); } /** * Get the redirect url to TID * @return {string} - Callback redirect url */ getRedirectUrl() { return this.redirectUrl; } } const E = q(null), W = () => L(E) ?? {}, he = (i, e) => { switch (e.type) { case "INIT": return { ...i, isLoading: !1, isAuthenticated: e.user != null, user: e.user, error: void 0 }; case "GET_TOKENS_COMPLETE": case "HANDLE_CALLBACK_COMPLETE": case "GET_ACCESS_TOKEN_COMPLETE": return { ...i, isLoading: !1, isAuthenticated: e.user != null, user: e.user, error: void 0 }; case "LOGOUT": return { ...i, isAuthenticated: !1, user: void 0 }; case "ERROR": return { ...i, isLoading: !1, error: e.error }; } }, ue = { isLoading: !0, isAuthenticated: !1 }, ge = (i) => { if (i == null || Object.keys(i).length <= 0) return !0; const e = Object.keys(i); for (const t of e) if (i[t] != null && i[t] !== "") return !1; return !0; }, ke = (i) => !ge(i.config), fe = (i) => { const { children: e, configurationEndpoint: t, clientId: n, redirectUrl: r, logoutRedirectUrl: a, scopes: g, onRedirectCallback: k, checkRedirectUrlMatch: v } = i; if (L(E) != null) throw new Error("TID Provider already defined"); const T = { config: { configurationEndpoint: t ?? "", clientId: n ?? "", redirectUrl: r ?? "", logoutRedirectUrl: a ?? "", scopes: g ?? [""] } }, [s] = z(i.tidClient ?? new de(T)), [f, u] = X(he, ue), p = Y(!1), N = M( () => v ? s.getRedirectUrl() : void 0, [v, s] ); D(() => { p.current || (i.tidClient != null && ke({ config: { configurationEndpoint: t, clientId: n, redirectUrl: r, logoutRedirectUrl: a, scopes: g } }) && console.warn( "When TID client is pass as prop, any client configuration property sent directly to the TID Provider component will be ignored" ), p.current = !0, (async () => { try { let o; if (ne(void 0, N)) { const { authState: l } = await s.handleCallback(); o = await s.getUser(), k != null && k(l); } else await s.loadUserSession(), o = await s.getUser(); u({ type: "INIT", user: o }); } catch (o) { let l = o; typeof o == "string" && (l = new Error(o)), u({ type: "ERROR", error: l }); } })()); }, [s, k]); const _ = y(async () => { const o = await s.getAccessTokenSilently(), l = await s.getUser(); return u({ type: "GET_ACCESS_TOKEN_COMPLETE", user: l }), o; }, [s]), C = y(async () => { const o = await s.getTokens(), l = await s.getUser(); return u({ type: "GET_TOKENS_COMPLETE", user: l }), o; }, [s]), S = y( async (o) => { await s.loginWithRedirect(o); }, [s] ), I = y( async (o) => { await s.logout(o), (o == null ? void 0 : o.disabledAutoRedirect) != null && o.disabledAutoRedirect && u({ type: "LOGOUT" }); }, [s] ), P = y( async (o) => { const { authState: l } = await s.handleCallback(o), V = await s.getUser(); return u({ type: "HANDLE_CALLBACK_COMPLETE", user: V }), { authState: l }; }, [s] ), G = M( () => ({ ...f, getAccessTokenSilently: _, getTokens: C, loginWithRedirect: S, handleCallback: P, logout: I }), [f, _, C, S, P, I] ); return /* @__PURE__ */ K(E.Provider, { value: G, children: e }); }, me = W, pe = fe, _e = ({ renderComponent: i, loader: e }) => { const { isAuthenticated: t, isLoading: n, loginWithRedirect: r } = W(); return D(() => { !n && !t && (async () => await r())(); }, [n, t, r]), t ? i : e || /* @__PURE__ */ K(Z, {}); }; export { _e as AuthenticationGuard, de as TIDClient, E as TIDContext, pe as TIDProvider, me as useAuth };