Commit 6ca90fb0 authored by Tharaka it19975696's avatar Tharaka it19975696 🎧

Fixed login page link issue

parent 186b4e79
...@@ -22,14 +22,10 @@ if (!JWT_SECRET) { ...@@ -22,14 +22,10 @@ if (!JWT_SECRET) {
process.exit(1); process.exit(1);
} }
// Helper function to create a JWT token // Utility function to create JWT token
const createToken = (userId, role) => { const createToken = (userId, userType) => {
return jwt.sign( return jwt.sign({ userId, userType }, JWT_SECRET, { expiresIn: '1h' });
{ userId, role }, };
JWT_SECRET,
{ expiresIn: '1h' }
);
};
// Registration endpoint for a student // Registration endpoint for a student
app.post('/register/student', async (req, res) => { app.post('/register/student', async (req, res) => {
...@@ -46,6 +42,7 @@ app.post('/register/student', async (req, res) => { ...@@ -46,6 +42,7 @@ app.post('/register/student', async (req, res) => {
data: { username, password: hashedPassword } data: { username, password: hashedPassword }
}); });
//Token Generation
const token = createToken(student.id, 'student'); const token = createToken(student.id, 'student');
res.status(201).json({ token }); // Send the token in the response res.status(201).json({ token }); // Send the token in the response
} catch (error) { } catch (error) {
...@@ -68,6 +65,7 @@ app.post('/register/student', async (req, res) => { ...@@ -68,6 +65,7 @@ app.post('/register/student', async (req, res) => {
data: { username, password: hashedPassword } data: { username, password: hashedPassword }
}); });
//Token Generation
const token = createToken(teacher.id, 'teacher'); const token = createToken(teacher.id, 'teacher');
res.status(201).json({ token }); // Send the token in the response res.status(201).json({ token }); // Send the token in the response
} catch (error) { } catch (error) {
......
...@@ -19,6 +19,12 @@ function App() { ...@@ -19,6 +19,12 @@ function App() {
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
setIsLoggedIn(!!token); setIsLoggedIn(!!token);
}, []); }, []);
// Function to call when the registration is successful
const onRegistrationSuccess = (token) => {
localStorage.setItem('token', token); // Save the token to localStorage
setIsLoggedIn(true); // Update the login state to true
};
const handleLogout = () => { const handleLogout = () => {
localStorage.removeItem('token'); localStorage.removeItem('token');
...@@ -29,9 +35,11 @@ function App() { ...@@ -29,9 +35,11 @@ function App() {
setIsLoggedIn(true); setIsLoggedIn(true);
}; };
const handleRegistrationSuccess = () => { // const handleRegistrationSuccess = () => {
setIsLoggedIn(true); // setIsLoggedIn(true);
}; // };
return ( return (
<Router> <Router>
...@@ -46,7 +54,7 @@ function App() { ...@@ -46,7 +54,7 @@ function App() {
} /> } />
<Route path="/register" element={ <Route path="/register" element={
!isLoggedIn ? ( !isLoggedIn ? (
<RegisterPage onRegistrationSuccess={handleRegistrationSuccess} /> <RegisterPage onRegistrationSuccess={onRegistrationSuccess} />
) : ( ) : (
<Navigate replace to="/home" /> <Navigate replace to="/home" />
) )
......
...@@ -80,7 +80,7 @@ function LoginPage({ onLoginSuccess }) { ...@@ -80,7 +80,7 @@ function LoginPage({ onLoginSuccess }) {
</button> </button>
<p className="text-center"> <p className="text-center">
Don't have an account yet?{' '} Don't have an account yet?{' '}
<Link to="/" className="text-blue-600 hover:text-blue-800 transition duration-200 ease-in-out"> <Link to="/register" className="text-blue-600 hover:text-blue-800 transition duration-200 ease-in-out">
Register here Register here
</Link> </Link>
</p> </p>
......
...@@ -3,7 +3,7 @@ import React, { useState } from 'react'; ...@@ -3,7 +3,7 @@ import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { registerStudent, registerTeacher } from '../api/api'; // Assuming these are API calls returning promises import { registerStudent, registerTeacher } from '../api/api'; // Assuming these are API calls returning promises
const RegisterPage = () => { const RegisterPage = (onRegistrationSuccess) => {
const [userData, setUserData] = useState({ const [userData, setUserData] = useState({
username: '', username: '',
password: '', password: '',
...@@ -15,31 +15,32 @@ const RegisterPage = () => { ...@@ -15,31 +15,32 @@ const RegisterPage = () => {
setUserData({ ...userData, [e.target.name]: e.target.value }); setUserData({ ...userData, [e.target.name]: e.target.value });
}; };
const handleSubmit = async (e) => { //Token generation in Registration success
e.preventDefault();
try { const handleSubmit = async (e) => {
let token; e.preventDefault();
if (userData.role === 'student') { try {
const response = await registerStudent({ username: userData.username, password: userData.password }); const response = userData.role === 'student' ?
token = response.token; await registerStudent(userData) :
} else { await registerTeacher(userData);
const response = await registerTeacher({ username: userData.username, password: userData.password });
token = response.token; if (response.token) {
} console.log("Token received:", response.token); // Log for debugging
localStorage.setItem('token', response.token); // Store the token
if (token) { if (onRegistrationSuccess) onRegistrationSuccess(response.token); // Update app state
console.log("Token received:", token); // Log for debugging
localStorage.setItem('token', token); // Store the token
navigate('/'); // Redirect to the homepage navigate('/'); // Redirect to the homepage
} else { } else {
console.error("No token received"); // This error message can be refined based on the response structure
alert('Registration successful but no token received'); alert('Registration successful but no token received');
} }
} catch (error) { } catch (error) {
console.error("Registration failed:", error); console.error("Registration failed:", error);
alert(error.message); // This error handling can be refined based on the response structure
} alert('Registration failed: ' + (error.response?.data?.message || error.message));
}; }
};
return ( return (
<div className="flex items-center justify-center h-screen bg-gray-200"> <div className="flex items-center justify-center h-screen bg-gray-200">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment