freeleaps_frontend/frontend/src/utils/backend/axios.js
2024-09-09 16:18:11 -07:00

83 lines
2.5 KiB
JavaScript

import axios from 'axios'
import { jwtDecode } from 'jwt-decode'
const backendAxios = axios.create({
baseURL: '',
headers: {
'Content-Type': 'application/json'
}
})
// Function to check if the token has expired
function isTokenExpired(token) {
// Ensure token is a non-empty string
if (!token || typeof token !== 'string') {
console.error('Invalid token: must be a non-empty string')
return true // Treat it as expired
}
try {
const decodedToken = jwtDecode(token)
console.log('this is decoded token', decodedToken)
const now = Math.floor(Date.now() / 1000)
// Buffer as 5 minu = 300 seconds
return decodedToken.exp - 300 < now
} catch (error) {
console.error('Error decoding token:', error)
return true // Treat it as expired if decoding fails
}
}
// Interceptor for handling token expiration and refreshing
backendAxios.interceptors.request.use(
async (config) => {
let accessToken = localStorage.getItem('access_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
if (accessToken == null || refreshToken == null) {
return config
}
if (isTokenExpired(accessToken)) {
try {
// If access token is expired, refresh it using the refresh token
const response = await axios.post(
'/api/user/signin/refresh-token',
{},
{
headers: {
Authorization: `Bearer ${refreshToken}`,
'Content-Type': 'application/json'
}
}
)
accessToken = response.data.access_token
refreshToken = response.data.refresh_token
// Save the new access token to localStorage
localStorage.setItem('access_token', accessToken)
localStorage.setItem('refresh_token', refreshToken)
} catch (error) {
console.error('Token refresh failed. Redirecting to login.')
// Optionally, handle token refresh failure (e.g., redirect to login)
window.location.href = '/front-door'
return Promise.reject(error)
}
}
// Add the (new) access token to the request headers
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
export { backendAxios }