Skip to content

Commit

Permalink
🐛 logout automatically when refresh token fails
Browse files Browse the repository at this point in the history
  • Loading branch information
pouyio committed May 12, 2024
1 parent fb6c523 commit af3ece8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
21 changes: 17 additions & 4 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { createContext, useEffect, useState } from 'react';
import React, { createContext, useContext, useEffect, useState } from 'react';
import { refreshApi } from 'utils/api';

export interface Session {
Expand All @@ -12,11 +12,13 @@ export interface Session {

interface AuthContextProps {
session: Session | null;
logout: () => void;
setSession: (session: Session) => void;
}

export const AuthContext = createContext<AuthContextProps>({
session: null,
logout: () => null,
setSession: () => null,
});

Expand All @@ -27,6 +29,11 @@ export const AuthProvider: React.FC<React.PropsWithChildren<{}>> = ({
JSON.parse(localStorage.getItem('session') || 'null')
);

const logout = () => {
localStorage.removeItem('session');
window.location.reload();
};

useEffect(() => {
const session = JSON.parse(localStorage.getItem('session') || 'null');

Expand All @@ -35,9 +42,14 @@ export const AuthProvider: React.FC<React.PropsWithChildren<{}>> = ({
if (
new Date() > new Date((+session.created_at + session.expires_in) * 1000)
) {
refreshApi(session.refresh_token).then(({ data }) => {
setSession(data);
});
refreshApi(session.refresh_token)
.then(({ data }) => {
setSession(data);
})
.catch((e) => {
console.warn('Auth error, trying login out', e);
logout();
});
}
}
}, []);
Expand All @@ -52,6 +64,7 @@ export const AuthProvider: React.FC<React.PropsWithChildren<{}>> = ({
<AuthContext.Provider
value={{
session,
logout,
setSession: localSetSession,
}}
>
Expand Down
7 changes: 1 addition & 6 deletions src/pages/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function Profile() {
const { theme, setTheme } = useContext(ThemeContext);
const [stats, setStats] = useState<UserStats>();
const [dev, setDev] = useState(false);
const { session } = useContext(AuthContext);
const { session, logout } = useContext(AuthContext);
const isLogged = !!session;
const dispatch = useAppDispatch();
const language = useAppSelector((state) => state.config.language);
Expand All @@ -31,11 +31,6 @@ export default function Profile() {
}
}, [isLogged]);

const logout = () => {
localStorage.removeItem('session');
window.location.reload();
};

const convertMinutes = (minutes: number = 0) => {
const d = Math.floor(minutes / 1440);
const h = Math.floor((minutes - d * 1440) / 60);
Expand Down

0 comments on commit af3ece8

Please sign in to comment.