-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsession.js
50 lines (41 loc) · 1.24 KB
/
session.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
'use strict';
const port = 3000;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const urlencoded = bodyParser.urlencoded;
const staticServer = express.static;
const session = require('express-session')
app.use(urlencoded({ extended: true }));
app.use('/', staticServer('./static/'));
app.use(session({secret: 'secret'}));
const users = {
'user1': 'password1',
'user2': 'password2'
}
const data = {
'user1': 'This is the data for user1',
'user2': 'This is the data for user2',
}
app.post('/session', function(req, res) {
const username = req.body.username;
const password = req.body.password;
if (users[username] === password) {
req.session.loggedIn = true;
res.writeHead(302, {
'Location': `data?username=${username}`
});
res.end();
} else {
res.status(401).end('wrong username or password');
}
});
app.get('/data', function(req, res) {
if (!req.session || !req.session.loggedIn) {
res.status(403).end('not logged in');
} else {
const username = req.query.username;
res.end(data[username]);
}
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));