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(); } };