const express = require('express'); const bodyParser = require('body-parser'); const jwt = require('jsonwebtoken'); const app = express(); const PORT = process.env.PORT || 3000; const SECRET_KEY = 'your-secret-key'; // Change this to a more secure value in production app.use(bodyParser.json()); // Dummy user data (replace with your own user authentication logic) const users = [ { id: 1, email: 'user@example.com', password: 'password123' } ]; // Login endpoint app.post('/login', (req, res) => { const { email, password } = req.body; // Check if email and password are provided if (!email || !password) { return res.status(400).json({ message: 'Email and password are required' }); } // Dummy user authentication logic const user = users.find(u => u.email === email && u.password === password); if (!user) { return res.status(401).json({ message: 'Invalid email or password' }); } // Generate JWT token const token = jwt.sign({ userId: user.id, email: user.email }, SECRET_KEY, { expiresIn: '1h' }); res.json({ token }); }); // Protected route (example) app.get('/protected', authenticateToken, (req, res) => { res.json({ message: 'You have accessed the protected route' }); }); // Middleware to authenticate JWT token function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).json({ message: 'Token is missing' }); } jwt.verify(token, SECRET_KEY, (err, user) => { if (err) { return res.status(403).json({ message: 'Invalid token' }); } req.user = user; next(); }); } app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });