Skip to content

Commit

Permalink
poc call silentLogin once every 10s if the user isn't logged-in
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lebaudantoine committed Jul 16, 2024
1 parent 9218fe8 commit 1e49f72
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/frontend/src/features/auth/api/fetchUser.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -16,6 +36,9 @@ export const fetchUser = (): Promise<ApiUser | false> => {
.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)
Expand Down

0 comments on commit 1e49f72

Please sign in to comment.