fix: gracefully handle jwt token decoding
This commit is contained in:
@@ -60,18 +60,28 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
|
|||||||
|
|
||||||
// Function to check token expiration
|
// Function to check token expiration
|
||||||
const checkTokenExpiration = (token: string) => {
|
const checkTokenExpiration = (token: string) => {
|
||||||
const decodedToken: any = jwtDecode(token);
|
if (!token || typeof token !== 'string') {
|
||||||
const currentTime = Date.now();
|
console.warn("Invalid token provided for decoding");
|
||||||
const tokenExpiryTime = decodedToken.exp * 1000; // Convert to milliseconds
|
logoutUser();
|
||||||
const timeUntilExpiry = tokenExpiryTime - currentTime;
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const decodedToken: any = jwtDecode(token);
|
||||||
|
const currentTime = Date.now();
|
||||||
|
const tokenExpiryTime = decodedToken.exp * 1000; // Convert to milliseconds
|
||||||
|
|
||||||
if (timeUntilExpiry > 0) {
|
if (tokenExpiryTime > currentTime) {
|
||||||
setTimeout(logoutUser, timeUntilExpiry); // Auto-logout when token expires
|
setTimeout(logoutUser, tokenExpiryTime - currentTime); // Auto-logout when token expires
|
||||||
} else {
|
} else {
|
||||||
logoutUser(); // Immediately logout if token is expired
|
logoutUser(); // Immediately logout if token is expired
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding token:", error);
|
||||||
|
logoutUser(); // Logout on error
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const storedUser = window.localStorage.getItem('user');
|
const storedUser = window.localStorage.getItem('user');
|
||||||
if (storedUser) {
|
if (storedUser) {
|
||||||
|
|||||||
Reference in New Issue
Block a user