I’m working on a chat app where the user logs in through redirection from another portal. The authentication works fine, and the payload looks like this:
{
“fullName”: “Test Agent”,
“username”: “Test Agent”,
“email”: “[email protected]”,
“role_id”: 1,
“role”: “SuperAdmin”,
“handshakeToken”: “xxxxx.”
}
Login works on Postman, but when I try to fetch users for the sidebar using the getUsersForSidebar API, it returns all users, and the role hierarchy filtering is not applied. I realized that the role_id is not being forwarded properly.
Here’s the login controller:
export const login = async (req, res) => {
try {
const { fullName, username, email, role_id, role, handshakeToken } = req.body;
if (!fullName || !username || !email || !handshakeToken || !role_id || !role) {
return res.status(400).json({ error: "Invalid payload. Ensure all required fields are provided." });
}
const expectedHandshakeToken = process.env.HANDSHAKE_TOKEN;
if (handshakeToken !== expectedHandshakeToken) {
return res.status(401).json({ error: "Invalid handshake token." });
}
const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.cookie("jwt", token, { httpOnly: true, secure: process.env.NODE_ENV === 'production' });
return res.status(200).json({ message: "Login successful", token });
} catch (error) {
console.error("Error during login:", error);
return res.status(500).json({ error: "Internal Server Error. Please check server logs for details." });
}
};
The getUsersForSidebar controller looks like this:
export const getUsersForSidebar = async (req, res) => {
try {
const currentUserEmail = req.user.email;
const currentUser = await User.findOne({ email: currentUserEmail });
const currentUserRoleId = currentUser.role_id;
console.log("Current User Role ID:", currentUserRoleId); // This logs `undefined`
const allUsers = await someApiCall();
const filteredUsers = allUsers.filter(user => canInitiateChat(currentUserRoleId, user.role_id));
res.status(200).json(filteredUsers);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
};
When I log currentUserRoleId, it shows undefined. However, if I manually set the role_id in the sidebar, the filtering works as expected. How can I ensure that the role_id from login is forwarded to the getUsersForSidebar API and used in filtering?