Skip to content

Commit

Permalink
store token in local storage to keep session always logged in
Browse files Browse the repository at this point in the history
  • Loading branch information
Bahugunajii committed Apr 6, 2024
1 parent a645a33 commit 25e6c7c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
2 changes: 2 additions & 0 deletions components/TopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ const TopBar = () => {
const handleLogout = () => {
deleteCookie("access_token", { path: '/', domain: '.avantifellows.org' });
deleteCookie("refresh_token", { path: '/', domain: '.avantifellows.org' });
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
window.location.reload();
MixpanelTracking.getInstance().trackEvent(MIXPANEL_EVENT.LOGOUT);
};
Expand Down
28 changes: 20 additions & 8 deletions services/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ import { getCookie, setCookie } from 'cookies-next';
import { api } from './url';
import getFetchConfig from '@/api/fetchConfig';

export async function verifyToken() {
const accessToken = getCookie('access_token');
const refreshToken = getCookie('refresh_token');
const url = `${api.portal.backend.baseUrl}${api.portal.backend.verify}`;
const refreshUrl = `${api.portal.backend.baseUrl}${api.portal.backend.refreshToken}`;

if (!accessToken) {
return { isValid: false, message: 'Access token not found' };
async function getToken(key: string): Promise<string | null> {
let token: string | null = localStorage.getItem(key);
if (!token) {
token = getCookie(key) as string | null;
if (token) {
localStorage.setItem(key, token);
}
}
return token;
}

export async function verifyToken() {
try {
const accessToken = await getToken('access_token');
const refreshToken = await getToken('refresh_token');
const url = api.portal.backend.baseUrl + api.portal.backend.verify;
const refreshUrl = api.portal.backend.baseUrl + api.portal.backend.refreshToken;

if (!accessToken) {
return { isValid: false, message: 'Access token not found' };
}

const response = await fetch(url, getFetchConfig(accessToken));
const data = await response.json();

Expand All @@ -29,6 +40,7 @@ export async function verifyToken() {

const refreshData = await refreshResponse.json();
setCookie('access_token', refreshData.access_token, { path: '/', domain: '.avantifellows.org' });
localStorage.setItem('access_token', refreshData.access_token);
window.location.reload();
return { isValid: true };
}
Expand Down

0 comments on commit 25e6c7c

Please sign in to comment.