Skip to content

Commit

Permalink
Merge pull request #706 from IkkiOcean/agro-backend-route-1
Browse files Browse the repository at this point in the history
[Fixed] Login State Persistence and User Data Return on Login
  • Loading branch information
manikumarreddyu authored Oct 27, 2024
2 parents 568fc5d + 78182f3 commit 50afb6f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
8 changes: 5 additions & 3 deletions backend/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ exports.signupController = async (req, res) => {


exports.signinController = async (req, res) => {

try {
const { email, password } = req.body;
const { email, password } = req.body; // Log the request body
const user = await User.findOne({ email });

if (!user) {
Expand All @@ -43,9 +44,10 @@ exports.signinController = async (req, res) => {
// Include role in the token
const token = jwt.sign({ userId: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });

res.status(200).json({ message: 'Login successful', token });
const user_id = user._id.toString()
res.status(200).json({ message: 'Login successful', token , user_id});
} catch (error) {
console.error("Login error:", error);
res.status(500).json({ message: 'Login failed' });
}
}
}
2 changes: 1 addition & 1 deletion frontend/src/components/LoginPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const LoginPage = () => {
password,
}
);
login(response.data.token); // Call login method from context
login(response.data.token, response.data.user_id); // Call login method from context
toast.success("Login successful");
} catch (error) {
toast.error(error.response?.data?.message || "Login failed");
Expand Down
30 changes: 26 additions & 4 deletions frontend/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
import { createContext, useContext, useState } from 'react';
import { createContext, useContext, useState, useEffect } from 'react';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userData, setUserData] = useState(null);
// Initialize the logged-in state from localStorage
const [isLoggedIn, setIsLoggedIn] = useState(() => {
const authData = localStorage.getItem('auth');
return authData ? true : false;
});

// Initialize user data from localStorage
const [userData, setUserData] = useState(() => {
const authData = localStorage.getItem('auth');
return authData ? JSON.parse(authData).user : null;
});

const login = (token, user) => {
// Store authentication data in localStorage
localStorage.setItem('auth', JSON.stringify({ token, user }));
setIsLoggedIn(true);
setUserData(user); // Set user data which includes role
setUserData(user);
};

const logout = () => {
// Remove authentication data from localStorage
localStorage.removeItem('auth');
setIsLoggedIn(false);
setUserData(null);
};

// Effect to set user data when the component mounts
useEffect(() => {
const authData = localStorage.getItem('auth');
if (authData) {
const { user } = JSON.parse(authData);
setUserData(user);
setIsLoggedIn(true);
}
}, []);

return (
<AuthContext.Provider value={{ isLoggedIn, login, logout, userData }}>
{children}
Expand All @@ -26,3 +47,4 @@ export const AuthProvider = ({ children }) => {
};

export const useAuth = () => useContext(AuthContext);

0 comments on commit 50afb6f

Please sign in to comment.