-
Notifications
You must be signed in to change notification settings - Fork 0
/
signed_cookies.js
executable file
·65 lines (54 loc) · 1.74 KB
/
signed_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
// This approach is vulnerable because we are not destroying user cookies on server upon logout.
// Then any malicious person can steal a user's cookie and he now have access to the account forever.
// So lets destroy this person-cookie association (or SESSIONS) in the server
const express = require('express')
const app = express()
const { createReadStream } = require('fs')
const cookieParser = require('cookie-parser')
var path = require('path');
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: 'password2',
bob: 'pass'
}
const BALANCES = {
alice:500, bob:300
}
app.get('/', (req, res) => {
const username = req.signedCookies.username
console.log(req)
if(username){
res.render('dashboard', {title: 'Welcome', username: username, balance:BALANCES[username]})
} else {
res.redirect('/login')
}
})
app.get('/login', (req, res) => {
if(req.signedCookies.username){
res.redirect('/')
} else {
createReadStream('index.html').pipe(res)
}
})
app.post('/login', (req, res) => {
console.log(req.body)
const username = req.body.username
const password = USERS[username]
if(req.body.password === password){
res.cookie('username', username, {signed: true})
res.redirect('/')
} else {
res.redirect('/login')
}
})
app.get('/logout', (req,res) => {
res.clearCookie('username')
res.redirect('/login')
})
app.listen(4000, () => {
console.log('Listening on port 4000')
})