Here's a simplified version of my authentication code:
Code: Select all
// auth.js
const jwt = require('jsonwebtoken');
const secretKey = 'mysecretkey';
// ... (other imports and middleware setup)
router.post('/login', async (req, res) => {
const { email, password } = req.body;
// Check if email and password are valid
// If valid, generate a JWT token
const user = await User.findOne({ email });
if (!user || user.password !== password) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user._id }, secretKey);
return res.json({ token });
});
// ... (other routes and middleware)
Could anyone guide me on what I might be overlooking in this implementation? Is there a common pitfall when setting up JWT authentication in a Node.js backend with Express? Any advice or insights would be greatly appreciated. Thank you in advance!