Fix the null issue for refresh and access token

This commit is contained in:
jetli 2024-09-08 16:15:04 -07:00
parent 8632070391
commit 0628ad507f
2 changed files with 12 additions and 7 deletions

View File

@ -57,6 +57,8 @@ export default {
}, },
methods: { methods: {
trySigninWithEmail() { trySigninWithEmail() {
// Prevent the page from refreshing on form submission
event.preventDefault();
this.message = null this.message = null
if (this.email === null || this.email.length < 1) { if (this.email === null || this.email.length < 1) {
this.message = this.$t('Please type in your email') this.message = this.$t('Please type in your email')

View File

@ -32,13 +32,16 @@ function isTokenExpired(token) {
backendAxios.interceptors.request.use( backendAxios.interceptors.request.use(
async (config) => { async (config) => {
let accessToken = localStorage.getItem('access_token') let accessToken = localStorage.getItem('access_token')
const refreshToken = localStorage.getItem('refresh_token') let refreshToken = localStorage.getItem('refresh_token')
// Fix: handle the case where localStorage returns 'null' as a string
if (accessToken === 'null') accessToken = null;
if (refreshToken === 'null') refreshToken = null;
// Check if the access token is expired // Check if the access token is expired
if (!accessToken || isTokenExpired(accessToken)) { if (accessToken == null || refreshToken == null) {
if (!refreshToken) { return config
return config }
} if (isTokenExpired(accessToken)) {
try { try {
// If access token is expired, refresh it using the refresh token // If access token is expired, refresh it using the refresh token
const response = await axios.post('/api/user/signin/refresh-token', {}, { const response = await axios.post('/api/user/signin/refresh-token', {}, {
@ -48,11 +51,11 @@ backendAxios.interceptors.request.use(
} }
}); });
accessToken = response.data.access_token accessToken = response.data.access_token
const new_refreshToken = response.data.refresh_token refreshToken = response.data.refresh_token
// Save the new access token to localStorage // Save the new access token to localStorage
localStorage.setItem('access_token', accessToken) localStorage.setItem('access_token', accessToken)
localStorage.setItem('refresh_token', new_refreshToken) localStorage.setItem('refresh_token', refreshToken)
} catch (error) { } catch (error) {
console.error('Token refresh failed. Redirecting to login.') console.error('Token refresh failed. Redirecting to login.')
// Optionally, handle token refresh failure (e.g., redirect to login) // Optionally, handle token refresh failure (e.g., redirect to login)