-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTask1-fixed.js
More file actions
63 lines (53 loc) · 1.59 KB
/
Task1-fixed.js
File metadata and controls
63 lines (53 loc) · 1.59 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const express = require('express');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
require('dotenv').config(); // Load environment variables from .env
const app = express();
app.use(express.json());
// Mock database functions
const db = {
users: [
{ id: 1, role: 'admin' },
{ id: 2, role: 'user' }
],
async getUserById(userId) {
return this.users.find(user => user.id == userId);
},
async deleteProject(projectId) {
console.log(`Project ${projectId} deleted by admin.`);
}
};
async function isAdmin(userId) {
const user = await db.getUserById(userId);
return user && user.role === 'admin';
}
// Middleware to verify JWT and set req.user
const authMiddleware = expressJwt({
secret: process.env.JWT_SECRET,
algorithms: ['HS256'],
requestProperty: 'user'
});
// Login endpoint to generate JWT
app.post('/login', (req, res) => {
const { userId } = req.body;
const user = db.users.find(u => u.id == parseInt(userId));
if (!user) {
return res.status(401).send('User not found');
}
// Generate JWT with user ID
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
// Protected route with JWT authentication
app.post('/project/:id/delete', authMiddleware, async (req, res) => {
const userId = req.user.id;
const projectId = req.params.id;
if (await isAdmin(userId)) {
await db.deleteProject(projectId);
return res.send('Project deleted');
}
return res.status(403).send('Not allowed');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});