From ea76efb3f13a7d5fa0624932d9887624c653f867 Mon Sep 17 00:00:00 2001 From: Alexander Borg Date: Mon, 18 Aug 2025 05:47:56 +0200 Subject: [PATCH] Fix jwt-token --- client/src/components/Layout.jsx | 6 +++--- client/src/contexts/AuthContext.jsx | 13 ++++++++++++- client/src/services/api.js | 14 +++++++++----- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx index 68d65eb..f54c2a6 100644 --- a/client/src/components/Layout.jsx +++ b/client/src/components/Layout.jsx @@ -31,7 +31,7 @@ const Layout = () => { const location = useLocation(); return ( -
+
{/* Mobile sidebar */}
{
{/* Main content */} -
+
{/* Page content */} -
+
diff --git a/client/src/contexts/AuthContext.jsx b/client/src/contexts/AuthContext.jsx index c6d4a27..49059ce 100644 --- a/client/src/contexts/AuthContext.jsx +++ b/client/src/contexts/AuthContext.jsx @@ -68,17 +68,28 @@ export const AuthProvider = ({ children }) => { const checkAuthStatus = async () => { try { + dispatch({ type: 'SET_LOADING', payload: true }); + const token = localStorage.getItem('token'); + + if (!token) { + dispatch({ type: 'SET_LOADING', payload: false }); + return; + } + const response = await api.get('/users/profile'); dispatch({ type: 'LOGIN_SUCCESS', payload: { user: response.data.data, - token: localStorage.getItem('token') + token: token } }); } catch (error) { + console.log('Token validation failed:', error.response?.status); localStorage.removeItem('token'); dispatch({ type: 'LOGOUT' }); + } finally { + dispatch({ type: 'SET_LOADING', payload: false }); } }; diff --git a/client/src/services/api.js b/client/src/services/api.js index dc5f846..078009c 100644 --- a/client/src/services/api.js +++ b/client/src/services/api.js @@ -1,8 +1,9 @@ import axios from 'axios'; -const API_BASE_URL = process.env.NODE_ENV === 'production' - ? '/drones/api' - : 'http://localhost:3001/api'; +const API_BASE_URL = import.meta.env.VITE_API_URL || + (process.env.NODE_ENV === 'production' + ? '/drones/api' + : 'http://localhost:3002/api'); const api = axios.create({ baseURL: API_BASE_URL, @@ -30,9 +31,12 @@ api.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { - // Token expired or invalid + // Token expired or invalid - let AuthContext handle this localStorage.removeItem('token'); - window.location.href = '/login'; + // Only redirect if not already on login page + if (window.location.pathname !== '/login') { + window.location.href = '/login'; + } } return Promise.reject(error); }