-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasswork13-secure.js
More file actions
57 lines (44 loc) · 1.57 KB
/
Copy pathclasswork13-secure.js
File metadata and controls
57 lines (44 loc) · 1.57 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
// ==========================================
// DEFENSE TUTORIAL CODE
// FILE: classwork13-secure.js
// ==========================================
// SECURE VERSION - Cookie Tampering Defense
const express = require('express');
const router = express.Router();
const cookieParser = require('cookie-parser');
// Use signed cookies with a secret
const COOKIE_SECRET = 'your-secure-secret-key';
const app = express();
app.use(cookieParser(COOKIE_SECRET));
router.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'alice' && password === 'pass123') {
// SECURE: Use signed cookies
res.cookie('user_data', JSON.stringify({
username: 'alice',
role: 'user'
}), {
httpOnly: true, // SECURE: Not accessible to JavaScript
secure: true, // SECURE: Only over HTTPS
signed: true, // SECURE: Cryptographically signed
sameSite: 'Strict' // SECURE: CSRF protection
});
res.json({ success: true });
}
});
router.get('/premium-content', (req, res) => {
// SECURE: Use signed cookies and verify on server
const userDataCookie = req.signedCookies.user_data;
if (!userDataCookie) {
return res.status(401).json({ error: 'Unauthorized' });
}
const userData = JSON.parse(userDataCookie);
// SECURE: Verify role against database, not cookie
const dbUser = database.getUserByUsername(userData.username);
if (dbUser.role === 'premium') {
res.json({ premiumContent: 'SECRET' });
} else {
res.status(403).json({ error: 'Premium required' });
}
});
module.exports = router;