Skip to content

Commit

Permalink
Merge pull request #17 from nhattpn/nhat
Browse files Browse the repository at this point in the history
update token and logout
  • Loading branch information
nhattpn authored Apr 28, 2024
2 parents c41968c + 8e22bd7 commit fc4357f
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 64 deletions.
39 changes: 22 additions & 17 deletions login-frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,32 @@ import Course1 from './pages/coursePage/Course1';
import CourseRegistration from './pages/coursePage/CourseRegistration';
import TeacherDashBoard from './pages/dashboardPage/TeacherDashBoard';
import AdminDashBoard from './pages/dashboardPage/TeacherDashBoard';
import { AuthProvider } from './context/authContext';
import { useRequireAuth } from './hooks/useAuth';
import PrivateRoute from './components/auth/PrivateRoute';

function App() {
return (
<Router>
<Routes>
<Route path='/' element={<FirstPage />} />
<Route path='/teacher/login' element={<AuthPage />} />
<Route path='/student/login' element={<AuthPage />} />
<Route path='/admin/login' element={<AuthPage />} />
<Route path='/teacher/changepassword' element={<AuthPage />} />
<Route path='/student/changepassword' element={<AuthPage />} />
<Route path='/admin/changepassword' element={<AuthPage />} />
<Router>
<Routes>
<Route path='/' element={<FirstPage />} />
<Route path='/teacher/login' element={<AuthPage />} />
<Route path='/student/login' element={<AuthPage />} />
<Route path='/admin/login' element={<AuthPage />} />
<Route path='/teacher/changepassword' element={<AuthPage />} />
<Route path='/student/changepassword' element={<AuthPage />} />
<Route path='/admin/changepassword' element={<AuthPage />} />

<Route path='/teacher/dashboard' element={< TeacherDashBoard/>} />
<Route path='/student/dashboard' element={< StudentDashBoard/>} />
<Route path='/admin/dashboard' element={< AdminDashBoard/>} />
<Route path='/course' element={<Course />} />
<Route path='/course1' element={<Course1 />} />
<Route path='/courseRegistration' element={<CourseRegistration />} />
</Routes>
</Router>
<Route element={< PrivateRoute/>} >
<Route path='/teacher/dashboard' element={< TeacherDashBoard/>} />
<Route path='/student/dashboard' element={< StudentDashBoard/>} />
<Route path='/admin/dashboard' element={< AdminDashBoard/>} />
<Route path='/course' element={<Course />} />
<Route path='/course1' element={<Course1 />} />
<Route path='/courseRegistration' element={<CourseRegistration />} />
</Route>
</Routes>
</Router>
);
}

Expand Down
18 changes: 18 additions & 0 deletions login-frontend/src/components/auth/PrivateRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react';
import { Outlet, Navigate, useNavigate } from 'react-router-dom'

const PrivateRoutes = () => {
const navigate = useNavigate();
const redirectUrl = '/';
const token = sessionStorage.getItem('jwtToken');
useEffect(() => {
if(!token){
navigate(redirectUrl, {replace: true });
}
}, []);
return(
<Outlet/>
)
}

export default PrivateRoutes
36 changes: 18 additions & 18 deletions login-frontend/src/components/auth/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,25 @@ function Login(props) {
const handleLogin = async (event) => {
event.preventDefault();
try {
// Gọi hàm auth.login() và chờ phản hồi
const response = await auth.login(email, password);
console.log("response data: ", response);
if (response.message === "Login successful") {
setErrorMsg(null);
setSuccessMsg("Login successful!");
navigate('/' + path[1] + '/dashboard');
} else if(response.message === "Default password in use. Password change required."){
setErrorMsg(response.message);
setSuccessMsg(null);
navigate('/' + path[1] + '/changepassword');
} else{
setErrorMsg(response.message);
setSuccessMsg(null);
}
// Gọi hàm auth.login() và chờ phản hồi
const response = await auth.login(email, password);
console.log("response data: ", response);
if (response.message === "Login successful") {
setErrorMsg(null);
setSuccessMsg("Login successful!");
navigate('/' + path[1] + '/dashboard');
} else if(response.message === "Default password in use. Password change required."){
setErrorMsg(response.message);
setSuccessMsg(null);
navigate('/' + path[1] + '/changepassword');
} else{
setErrorMsg(response.message);
setSuccessMsg(null);
}
} catch (error) {
// Xử lý các lỗi xảy ra trong quá trình gọi auth.login()
setErrorMsg(error?.message || "Error");
console.error('Login error:', error.message);
// Xử lý các lỗi xảy ra trong quá trình gọi auth.login()
setErrorMsg(error?.message || "Error");
console.error('Login error:', error.message);
}
};

Expand Down
11 changes: 11 additions & 0 deletions login-frontend/src/components/auth/logout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const LogOut = async () => {
try{
sessionStorage.removeItem('jwtToken');
await fetch('/api/logout', { method: 'POST' });
console.log('Logged out successfully (backend)');
} catch (error) {
console.error('Error logging out (backend):', error);
} finally {
window.location.href = '/';
}
};
7 changes: 4 additions & 3 deletions login-frontend/src/context/authContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ export function AuthProvider({ children }) {
const login = async (email, password) => {
try {
const data = await authService.login(email, password);
if (data && data.token) {
sessionStorage.setItem('jwtToken', data.token);
console.log(data);
if (data) {
const token = data.token;
setUser(data);
return data;
return {...data, token};
} else {
console.error('No data or token received on login');
return null;
Expand Down
14 changes: 0 additions & 14 deletions login-frontend/src/hooks/useAuth.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import { useContext } from 'react';
import { AuthContext } from '../context/authContext';
import { useEffect, useNavigate } from 'react';

export function useAuth() {
return useContext(AuthContext);
}
export function useRequireAuth(redirectUrl = '/login') {
const auth = useAuth();
const navigate = useNavigate();

useEffect(() => {
const token = sessionStorage.getItem('jwtToken');
if (!token) {
navigate(redirectUrl);
}
}, [navigate, redirectUrl]);

return auth;
}
1 change: 0 additions & 1 deletion login-frontend/src/pages/FirstPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import axios from 'axios';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import FirstHeader from './../components/header_footer/FirstHeader';
import FirstFooter from './../components/header_footer/FirstFooter';
//import './FirstPage.css';

const slide1 = 'https://i.ibb.co/RbNBFv1/8ktXyJ-n.jpg';

Expand Down
2 changes: 1 addition & 1 deletion login-frontend/src/pages/authPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function App() {
style={{ width: '25%', height: '100vh', backgroundColor: 'rgb(62, 161, 168)' }}
>
<div>
<img className="img-thumbnail no-gutter" id="logo" alt="" src={logo} />
<a href='/'><img className="img-thumbnail no-gutter" id="logo" alt="" src={logo} /></a>
<h1 style={{marginTop: '5vh'}}>Welcome</h1>
{switchToChangePassword()}
</div>
Expand Down
4 changes: 2 additions & 2 deletions login-frontend/src/pages/dashboardPage/AdminDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Training from './../components/DashBoard/studentTraining';
import Footer from './../components/header_footer/Footer';
import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import './StudentDashboard.css';
import {LogOut} from './../../components/auth/logout';

function DataTable() {
const [currentView, setCurrentView] = useState('StudentInfo');
Expand All @@ -24,7 +24,7 @@ function DataTable() {
<li style={{padding: '2vh'}}>
<a className="nav-link" href="#">Nguyen Van A - SVxxxxx</a>
</li>
<li style={{padding: '2vh'}}>
<li style={{padding: '2vh', cursor: 'pointer'}} onClick={LogOut}>
<i className="fa fa-solid fa-bell fa-lg fa-3x"></i>
Logout
</li>
Expand Down
4 changes: 2 additions & 2 deletions login-frontend/src/pages/dashboardPage/StudentDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Training from '../../components/dashboard/studentTraining';
import Footer from '../../components/header_footer/Footer';
import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import {LogOut} from './../../components/auth/logout';
import './Dashboard.css';

function DataTable() {
Expand All @@ -13,7 +14,6 @@ function DataTable() {
setCurrentView(viewName);
};
const [isOpen, setIsOpen] = useState(false);

return (
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
Expand All @@ -24,7 +24,7 @@ function DataTable() {
<li style={{padding: '2vh'}}>
<a className="nav-link" href="#">Nguyen Van A - SVxxxxx</a>
</li>
<li style={{padding: '2vh'}}>
<li style={{padding: '2vh', cursor: 'pointer'}} onClick={LogOut}>
<i className="fa fa-solid fa-bell fa-lg fa-3x"></i>
Logout
</li>
Expand Down
11 changes: 5 additions & 6 deletions login-frontend/src/pages/dashboardPage/TeacherDashBoard.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import TeacherInfo from './../../components/dashboard/teacherInfo';
import Footer from '../../components/header_footer/Footer';
import SubjectSchedule from './../../components/dashboard/subjectSchedule';
import LessonPlan from './../../components/dashboard/lessonPlan';
import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
// import './StudentDashboard.css';

import {LogOut} from './../../components/auth/logout';
function DataTable() {
const [currentView, setCurrentView] = useState('TeacherInfo');

const handleNavigation = (viewName) => {
setCurrentView(viewName);
};
const [isOpen, setIsOpen] = useState(false);


const [isOpen, setIsOpen] = useState(false);
return (
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
Expand All @@ -25,7 +24,7 @@ function DataTable() {
<li style={{padding: '2vh'}}>
<a className="nav-link" href="#">Nguyen Van A - GVxxxxx</a>
</li>
<li style={{padding: '2vh'}}>
<li style={{padding: '2vh', cursor: 'pointer'}} onClick={LogOut}>
<i className="fa fa-solid fa-bell fa-lg fa-3x"></i>
Logout
</li>
Expand Down

0 comments on commit fc4357f

Please sign in to comment.