(frontend) try silent login every one hour

This commit is totally work in progress.
@manuhabitela the floor is yours.

If the user is logged-out, try silently log-in her every hour,
to avoid any manual login on her side.

The one hour value has been discussed with @manuhabitela, but there
is no real logic behind it. Could definitely be shorter or longer.

It needs at least to be longer than the average silent login flow
to avoid locking the user-agent in an infinite redirection loop.
This commit is contained in:
lebaudantoine
2024-07-24 23:28:30 +02:00
committed by aleb_the_flash
parent 2a8027deb0
commit 234116163a
3 changed files with 33 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
import { ApiError } from '@/api/ApiError'
import { fetchApi } from '@/api/fetchApi'
import { type ApiUser } from './ApiUser'
import { attemptSilentLogin } from "@/features/auth";
/**
* fetch the logged-in user from the api.
@@ -16,6 +17,7 @@ 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) {
attemptSilentLogin(3600)
resolve(false)
} else {
reject(error)

View File

@@ -2,3 +2,4 @@ export { useUser } from './api/useUser'
export { authUrl } from './utils/authUrl'
export { logoutUrl } from './utils/logoutUrl'
export { RenderIfUserFetched } from './components/RenderIfUserFetched'
export { attemptSilentLogin } from './utils/silentLogin'

View File

@@ -0,0 +1,30 @@
import { authUrl } from "@/features/auth";
const SILENT_LOGIN_RETRY_KEY = 'silent-login-retry'
const isRetryAllowed = () => {
const lastRetryDate = localStorage.getItem(SILENT_LOGIN_RETRY_KEY);
if (!lastRetryDate) {
return true;
}
const now = new Date();
return now.getTime() > Number(lastRetryDate)
}
const setNextRetryTime = (retryIntervalInSeconds: number) => {
const now = new Date()
const nextRetryTime = now.getTime() + (retryIntervalInSeconds * 1000);
localStorage.setItem(SILENT_LOGIN_RETRY_KEY, String(nextRetryTime));
}
const initiateSilentLogin = () => {
window.location.href = authUrl(true)
}
export const attemptSilentLogin = (retryIntervalInSeconds: number) => {
if (!isRetryAllowed()) {
return
}
setNextRetryTime(retryIntervalInSeconds)
initiateSilentLogin()
}