From 5be94a84be884ef577db7ee9c8913dc4a30892e7 Mon Sep 17 00:00:00 2001 From: Giuseppe Date: Wed, 16 Apr 2025 11:04:35 +0200 Subject: [PATCH] feat: add logInSilent method to AuthContext and update IAuthContext interface --- src/AuthContext.tsx | 35 +++++++++++++++++++++++++++++++++++ src/types.ts | 2 ++ 2 files changed, 37 insertions(+) diff --git a/src/AuthContext.tsx b/src/AuthContext.tsx index c7bb113..69d9f1b 100644 --- a/src/AuthContext.tsx +++ b/src/AuthContext.tsx @@ -20,6 +20,7 @@ export const AuthContext = createContext({ token: '', login: () => null, logIn: () => null, + logInSilent: () => null, logOut: () => null, error: null, loginInProgress: false, @@ -106,6 +107,39 @@ export const AuthProvider = ({ authConfig, children }: IAuthProvider) => { }) } + function logInSilent(initial: boolean = false) { + setToken('') + setTokenExpire(epochAtSecondsFromNow(FALLBACK_EXPIRE_TIME)) + setIdToken(undefined) + setLoginInProgress(true) + if (refreshToken) { + fetchWithRefreshToken({ config, refreshToken }) + .then((result: TTokenResponse) => handleTokenResponse(result)) + .catch((error: unknown) => { + if (error instanceof FetchError) { + // If the fetch failed with status 400, assume expired refresh token + if (error.status === 400) { + handleExpiredRefreshToken(initial) + return + } + // Unknown error. Set error, and log in if first page load + console.error(error) + setError(error.message) + if (initial) logIn(undefined, undefined, config.loginMethod) + } + // Unknown error. Set error, and log in if first page load + else if (error instanceof Error) { + console.error(error) + setError(error.message) + if (initial) logIn(undefined, undefined, config.loginMethod) + } + }) + .finally(() => { + setLoginInProgress(false) + }) + } + } + function handleTokenResponse(response: TTokenResponse) { setToken(response.access_token) if (response.id_token) { @@ -269,6 +303,7 @@ export const AuthProvider = ({ authConfig, children }: IAuthProvider) => { login: logIn, logIn, logOut, + logInSilent, error, loginInProgress, }} diff --git a/src/types.ts b/src/types.ts index 087cb97..077040e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -53,12 +53,14 @@ export interface IAuthProvider { } type TLogInFunction = (state?: string, additionalParameters?: TPrimitiveRecord, method?: TLoginMethod) => void +type TLogInSilentFunction = (initial?: boolean) => void export interface IAuthContext { token: string logIn: TLogInFunction logOut: (state?: string, logoutHint?: string, additionalParameters?: TPrimitiveRecord) => void /** @deprecated Use `logIn` instead */ login: TLogInFunction + logInSilent: TLogInSilentFunction error: string | null tokenData?: TTokenData idToken?: string