Last active
November 25, 2021 17:54
-
-
Save RacketyWater7/3be9146d9e8796abdc4f85ec52b4d143 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
import Cookies from "js-cookie"; | |
import jwt_decode from "jwt-decode"; | |
import moment from "moment"; | |
import { history } from "../index"; | |
const TokenValidate = async () => { | |
let access_token = Cookies.get("access"); | |
let refresh_token = localStorage.getItem("refresh_token"); | |
if (!refresh_token) return history.push("/logout"); | |
let accessTokenExpireTime; | |
try { | |
//extracting the token's expiry time with jwt_decode | |
accessTokenExpireTime = jwt_decode(access_token).exp; | |
} catch (error) { | |
return history.push("/logout"); | |
} | |
if (moment.unix(accessTokenExpireTime) - moment(Date.now()) < 10000) { | |
//generating new accessToken | |
let refreshTokenExpireTime; | |
try { | |
refreshTokenExpireTime = jwt_decode(refresh_token).exp; | |
} catch (error) { | |
return history.push("/logout"); | |
} | |
if (moment.unix(refreshTokenExpireTime) - moment(Date.now()) > 10000) { | |
return new Promise((resolve, reject) => { | |
axios | |
.post("/refreshToken", { refresh_token: refresh_token }) | |
.then((res) => { | |
if (!res?.data?.access_token) { | |
//the execution will never reach in this block, and if it did, it could be some backend issue. | |
console.log("refresh token is gone"); | |
return history.push("/logout"); | |
} else { | |
//refreshed the access token | |
const { access_token } = res?.data; | |
Cookies.set("access", access_token); | |
resolve(access_token); | |
} | |
}); | |
}); | |
} else { | |
//refreshToken expired | |
Cookies.remove("access"); | |
localStorage.removeItem("refresh_token"); | |
history.push("/logout"); | |
alert("Your session has expired, please login again."); | |
} | |
return access_token; | |
} | |
return access_token; | |
}; | |
export default TokenValidate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment