Build a secure REST API for user registration, login, and JWT-based authentication
Create a robust authentication API that handles user registration, login, password reset, and JWT token management with proper security practices.
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
async function register(req, res) {
const { email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
// Save user to database
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET);
res.json({ token });
}
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}