Merge branch 'robot-duplication' of https://github.com/getmaxun/maxun into robot-duplication
This commit is contained in:
@@ -1,7 +1,6 @@
|
|||||||
import { useReducer, createContext, useEffect } from 'react';
|
import { useReducer, createContext, useEffect } from 'react';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { jwtDecode } from 'jwt-decode';
|
|
||||||
import { apiUrl } from "../apiConfig";
|
import { apiUrl } from "../apiConfig";
|
||||||
|
|
||||||
interface AuthProviderProps {
|
interface AuthProviderProps {
|
||||||
@@ -51,74 +50,28 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
axios.defaults.withCredentials = true;
|
axios.defaults.withCredentials = true;
|
||||||
|
|
||||||
const logoutUser = () => {
|
|
||||||
dispatch({ type: 'LOGOUT' });
|
|
||||||
window.localStorage.removeItem('user');
|
|
||||||
window.localStorage.removeItem('logoutTimeout');
|
|
||||||
navigate('/login');
|
|
||||||
};
|
|
||||||
|
|
||||||
const checkTokenExpiration = (token: string) => {
|
|
||||||
if (!token) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const decodedToken: any = jwtDecode(token);
|
|
||||||
const currentTime = Date.now();
|
|
||||||
const tokenExpiryTime = decodedToken.exp * 1000;
|
|
||||||
|
|
||||||
if (tokenExpiryTime > currentTime) {
|
|
||||||
// Calculate remaining time until token expires
|
|
||||||
const remainingTime = tokenExpiryTime - currentTime;
|
|
||||||
|
|
||||||
// Check if a logout timeout already exists in local storage
|
|
||||||
const existingTimeout = window.localStorage.getItem('logoutTimeout');
|
|
||||||
|
|
||||||
if (!existingTimeout) {
|
|
||||||
// Set a timeout for auto-logout
|
|
||||||
const timeoutId = setTimeout(logoutUser, remainingTime);
|
|
||||||
window.localStorage.setItem('logoutTimeout', JSON.stringify(timeoutId));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logoutUser(); // Immediately logout if token is expired
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error decoding token:", error);
|
|
||||||
logoutUser();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const storedUser = window.localStorage.getItem('user');
|
const storedUser = window.localStorage.getItem('user');
|
||||||
if (storedUser) {
|
if (storedUser) {
|
||||||
const userData = JSON.parse(storedUser);
|
dispatch({ type: 'LOGIN', payload: JSON.parse(storedUser) });
|
||||||
dispatch({ type: 'LOGIN', payload: userData });
|
|
||||||
|
|
||||||
// Run expiration check only if a token exists
|
|
||||||
if (userData.token) {
|
|
||||||
checkTokenExpiration(userData.token);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Clean up timeout on component unmount
|
}, []);
|
||||||
return () => {
|
|
||||||
const timeoutId = window.localStorage.getItem('logoutTimeout');
|
|
||||||
if (timeoutId) {
|
|
||||||
clearTimeout(JSON.parse(timeoutId));
|
|
||||||
window.localStorage.removeItem('logoutTimeout');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []); // Only run this effect once on mount
|
|
||||||
|
|
||||||
axios.interceptors.response.use(
|
axios.interceptors.response.use(
|
||||||
(response) => response,
|
function (response) {
|
||||||
(error) => {
|
return response;
|
||||||
|
},
|
||||||
|
function (error) {
|
||||||
const res = error.response;
|
const res = error.response;
|
||||||
if (res?.status === 401 && !res.config.__isRetryRequest) {
|
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
axios
|
axios
|
||||||
.get(`${apiUrl}/auth/logout`)
|
.get(`${apiUrl}/auth/logout`)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
console.log('/401 error > logout');
|
console.log('/401 error > logout');
|
||||||
logoutUser();
|
dispatch({ type: 'LOGOUT' });
|
||||||
|
window.localStorage.removeItem('user');
|
||||||
|
navigate('/login');
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error('AXIOS INTERCEPTORS ERROR:', err);
|
console.error('AXIOS INTERCEPTORS ERROR:', err);
|
||||||
@@ -129,7 +82,7 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
|
|||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ state, dispatch }}>
|
<AuthContext.Provider value={{ state, dispatch }}>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
Reference in New Issue
Block a user