Skip to content

Commit 9b3f6be

Browse files
committed
Fix access without token issue
1 parent c34e6f0 commit 9b3f6be

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

Frontend/src/App.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import './App.css';
22
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
33
import 'bootstrap/dist/css/bootstrap.min.css';
4-
import CreateQn from './components/question/CreateQn';
5-
import EditQn from './components/question/EditQn';
64
import Home from './components/Home';
75
import Login from './components/auth/Login';
86
import SignUp from './components/auth/SignUp';
7+
import ProtectedRoute from './components/routes/ProtectedRoute';
98

109
function App() {
1110
return (
@@ -22,7 +21,7 @@ function App() {
2221
<Route path='/signup' element={<SignUp />} />
2322

2423
{/* Home page route */}
25-
<Route path='/home' element={<Home />} />
24+
<Route path='/home' element={<ProtectedRoute><Home /></ProtectedRoute>} />
2625
</Routes>
2726
</BrowserRouter>
2827
</div>

Frontend/src/components/auth/Login.jsx

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,15 @@ const Login = () => {
2323
.then(result => {
2424
// navigate to home page if successful
2525
console.log(result);
26-
navigate('/home')
26+
const jwt_token = result.data.data.accessToken;
27+
28+
if (jwt_token) {
29+
sessionStorage.setItem('jwt_token', jwt_token);
30+
navigate('/home');
31+
} else {
32+
setError('Token not found, authentication failed.');
33+
}
34+
2735
})
2836
.catch(e => {
2937
// handle errors here
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import React from 'react';
2+
import {Navigate} from 'react-router-dom';
3+
4+
// Authenticate user only if they log in once, token is available until they close the tab/browser for now
5+
const isAuthenticated = () => {
6+
const token = sessionStorage.getItem('jwt_token'); // Get token stored in session storage
7+
if (!token) {
8+
return false;
9+
}
10+
11+
return true;
12+
};
13+
14+
const ProtectedRoute = ({children}) => {
15+
return isAuthenticated() ? children : <Navigate to='/login'/>;
16+
};
17+
18+
export default ProtectedRoute;

0 commit comments

Comments
 (0)