From 6bd36a8bf98e7baaccb9de34e8b85f48a1d272e8 Mon Sep 17 00:00:00 2001 From: Aarni Halinen Date: Thu, 21 Jul 2022 21:26:49 +0300 Subject: [PATCH] Fix unnecessary auth check after logout --- src/api/auth.ts | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/api/auth.ts b/src/api/auth.ts index c24cc61..bda066c 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -30,18 +30,22 @@ async function generateToken(username: string, password: string): Promise { - try { - const refresh = getRefreshTokenCookie(); - if (refresh) { - const { access } = await postBackendAPI({ path: APIPath.AUTH_TOKEN_REFRESH }, { refresh }); - setAccessTokenCookie(access); - return true; - } - return false; - } catch (err) { + // Get refresh token if exists + const refresh = getRefreshTokenCookie(); + if (!refresh) { deleteTokenCookies(); return false; } + + try { + // Renew access token + const { access } = await postBackendAPI({ path: APIPath.AUTH_TOKEN_REFRESH }, { refresh }); + setAccessTokenCookie(access); + } catch (err) { + // If we get HTTP500 or something form backend, do not clear cookies + return false; + } + return true; } export const login = async (username: string, password: string): Promise => { @@ -51,11 +55,19 @@ export const login = async (username: string, password: string): Promise = }; export const authenticate = async (): Promise => { + // Find access token + const token = getAccessTokenCookie(); + if (!token) { + // Unnecessary, but might be good idea to clear old refresh tokens etc. + deleteTokenCookies(); + return false; + } + try { - const token = getAccessTokenCookie(); await postBackendAPI({ path: APIPath.AUTH_TOKEN_VERIFY }, { token }); return true; } catch (err) { + // Handle refresh automatically return refreshToken(); } };