From 1e49f729f4c9ff3f089fe74193ac7c8ddede58a9 Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Wed, 17 Jul 2024 01:44:17 +0200 Subject: [PATCH] poc call silentLogin once every 10s if the user isn't logged-in This is a brainstorming. How could we prevent infinite loop after the silent login failed? (disclaimer: I have absolutely not given any attention to the code quality) What about using the local storage? Client set a silent login variable which expires every Xs. --- .../src/features/auth/api/fetchUser.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/frontend/src/features/auth/api/fetchUser.ts b/src/frontend/src/features/auth/api/fetchUser.ts index 512b3d02..1298223c 100644 --- a/src/frontend/src/features/auth/api/fetchUser.ts +++ b/src/frontend/src/features/auth/api/fetchUser.ts @@ -1,6 +1,26 @@ import { ApiError } from '@/api/ApiError' import { fetchApi } from '@/api/fetchApi' import { type ApiUser } from './ApiUser' +import { authUrl } from "@/features/auth"; + +const SILENT_LOGIN_KEY = 'initiateSilentLogin'; +const SILENT_LOGIN_EXPIRY = 10000; + +const shouldInitiateSilentLogin = () => { + const silentLoginStr = localStorage.getItem(SILENT_LOGIN_KEY) + if (!silentLoginStr) { + return true + } + const { expiry } = JSON.parse(silentLoginStr) + const now = new Date() + return now.getTime() > expiry; +}; + +const initiateSilentLogin = () => { + const now = new Date() + localStorage.setItem(SILENT_LOGIN_KEY, JSON.stringify({expiry: now.getTime() + SILENT_LOGIN_EXPIRY})); + window.location.href = authUrl(true) +} /** * fetch the logged-in user from the api. @@ -16,6 +36,9 @@ export const fetchUser = (): Promise => { .catch((error) => { // we assume that a 401 means the user is not logged in if (error instanceof ApiError && error.statusCode === 401) { + if (shouldInitiateSilentLogin()) { + initiateSilentLogin() + } resolve(false) } else { reject(error)