feat: implement auth flow and app initialization
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { ENV_CONSTANT } from '@/constants/secrect.constant';
|
||||
import { tokenService } from '@/services/token.service';
|
||||
import { useAppStore } from '@/store/app.store';
|
||||
import { useAuthStore } from '@/store/auth.store';
|
||||
import axios from 'axios';
|
||||
import { signOut } from 'next-auth/react';
|
||||
|
||||
const BASE_URL = ENV_CONSTANT.BASE_API_URL;
|
||||
|
||||
@@ -14,8 +14,8 @@ const axiosClient = axios.create({
|
||||
});
|
||||
|
||||
axiosClient.interceptors.request.use(
|
||||
async (config) => {
|
||||
const token = await tokenService.getAccessToken();
|
||||
(config) => {
|
||||
const token = useAuthStore.getState().accessToken;
|
||||
|
||||
if (token && config.headers) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
@@ -31,8 +31,43 @@ axiosClient.interceptors.request.use(
|
||||
axiosClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error?.response?.status === 401 && typeof window !== 'undefined') {
|
||||
await signOut({ callbackUrl: '/login' });
|
||||
const originalRequest = error?.config;
|
||||
const status = error?.response?.status;
|
||||
const requestUrl = originalRequest?.url ?? '';
|
||||
const isAuthRoute =
|
||||
requestUrl.includes('api/auth/login') || requestUrl.includes('api/auth/refresh');
|
||||
|
||||
if (status === 401 && originalRequest && !originalRequest._retry && !isAuthRoute) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
const response = await axiosAuth.post(
|
||||
'api/auth/refresh',
|
||||
{},
|
||||
{
|
||||
withCredentials: true,
|
||||
},
|
||||
);
|
||||
const accessToken = response.data?.access_token;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new Error('Refresh failed: no access token');
|
||||
}
|
||||
|
||||
useAuthStore.getState().setAccessToken(accessToken);
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
||||
|
||||
return axiosClient(originalRequest);
|
||||
} catch (refreshError) {
|
||||
useAuthStore.getState().logout();
|
||||
useAppStore.getState().clear();
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
|
||||
Reference in New Issue
Block a user