-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (39 loc) · 1.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const bodyParser = require('body-parser');
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
// Middleware for parsing JSON
app.use(express.json());
// Secret key (store securely in production)
const SECRET_KEY = 'hehe';
// Middleware to verify JWT
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Login route - generates JWT
app.post('/login', (req, res) => {
// Validate user credentials (simplified for example)
const username = req.body.username;
const user = {
id: 1,
username: username,
role: 'user'
};
// Generate JWT
const token = jwt.sign(user, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
});
// Protected route
app.get('/protected', authenticateToken, (req, res) => {
res.json({ data: 'Protected data', user: req.user });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});