-
Notifications
You must be signed in to change notification settings - Fork 0
/
secure_cookies.js
executable file
·74 lines (63 loc) · 2.16 KB
/
secure_cookies.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Associate a random string to each user session and revoking this string after their logout.
// Same user can have multiple sessions from different devices
const express = require('express')
const app = express()
const { createReadStream } = require('fs')
const cookieParser = require('cookie-parser')
var path = require('path');
const { cookie } = require('express-validator');
const { randomBytes } = require('crypto');
const { POINT_CONVERSION_COMPRESSED } = require('constants');
const SECRET_TOKEN = 'sdfqiwuhjeilfudhqwme' //anything random
app.use(express.urlencoded({ extended: false })); //gives the ability to use req.body
app.use(cookieParser(SECRET_TOKEN)) //gives us the ability to use req.cookies
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, ''));
const USERS = {
alice: 'password',
bob: 'pass'
}
const BALANCES = {
alice: 500, bob: 300
}
let SESSIONS = {} // sessionId --> username
app.get('/', (req, res) => {
const sessionId= req.cookies.sessionId
const username = SESSIONS[sessionId]
console.log(req.cookies)
if (username) {
res.render('dashboard', { title: 'Welcome', username: username, balance: BALANCES[username] })
} else {
res.redirect('/login')
}
})
app.get('/login', (req, res) => {
if (SESSIONS[req.cookies.sessionId]) {
res.redirect('/')
} else {
createReadStream('index.html').pipe(res)
}
})
app.post('/login', (req, res) => {
const username = req.body.username
const password = USERS[username]
if (req.body.password === password) {
randomId = randomBytes(16).toString('base64')
res.cookie('sessionId', randomId, {maxAge: 86409000})
//Remember to use expiry date otherwise the browser will remember the cookie only for a browsing session.
SESSIONS[randomId] = username
res.redirect('/')
} else {
res.redirect('/login')
}
console.log(SESSIONS)
})
app.get('/logout', (req, res) => {
res.clearCookie('sessionId')
delete SESSIONS[req.cookies.sessionId]
res.redirect('/login')
console.log(SESSIONS)
})
app.listen(4000, () => {
console.log('Listening on port 4000')
})