-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbank-05.js
98 lines (81 loc) · 2.12 KB
/
bank-05.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const express = require('express')
const { createReadStream } = require('fs')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const { randomBytes } = require('crypto')
const app = express()
app.use(bodyParser.urlencoded({extended: false}))
app.use(cookieParser())
const USERS = {
alice: '123',
bob: 'eagle'
}
const BALANCES = {
alice: 500,
bob: 100
}
const SESSIONS = {} // sessionId -> username
app.get('/', (req, res) => {
const source = req.query.source
const sessionId = req.cookies.sessionId
const username = SESSIONS[sessionId]
if (username) {
// note: use backquotes `` for ${var} trick
res.send(`Hi ${username}! Your balance is $${BALANCES[username]}
<p>
<form method='POST' action='/transfer'>
Send amount:
<input name='amount' />
To user:
<input name='to' />
<input type='submit' value='send' />
</form>
<p>You can <a href=/logout>logout</a>`)
} else {
res.send(`
<h1>
${source ? `Hi ${source} reader!` : ''}
Login to your bank account:
</h1>
<form method='POST' action='/login'>
Username:
<input name='username' />
Password:
<input name='password' type='password' />
<input type='submit' value='Login' />
</form>
`)
}
})
app.post('/login', (req, res) => {
const username = req.body.username
const password = USERS[username]
if (req.body.password === password) {
const sessionId = randomBytes(16).toString('hex')
SESSIONS[sessionId] = username
res.cookie('sessionId',sessionId)
res.redirect('/')
} else {
res.send('fail!')
}
})
app.post('/transfer', (req,res) => {
const sessionId = req.cookies.sessionId
const username = SESSIONS[sessionId]
if (!username) {
res.send('fail!')
}
const amount = Number(req.body.amount)
const to = req.body.to
// not ACID!!!
BALANCES[username] -= amount
BALANCES[to] += amount
res.redirect('/')
})
app.get('/logout', (req,res) => {
const sessionId = req.cookies.sessionId
delete SESSIONS[sessionId]
res.clearCookie('sessionId')
res.redirect('/')
})
app.listen(4000)