-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
82 lines (73 loc) · 1.95 KB
/
app.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
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// This is how we configure session.
// By default this session is in memory
// We could configure an add on module to store
// them in the DB though.
app.use(session({
secret: 'SSSSHHHHHH',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
sameSite: 'strict'
}
}));
const users = {
testuser: 'password'
}
// Logs a user in
// Normall we would check the DB, but we are just using hardcoded users in this demo
app.post('/login', (req, res, next) => {
const { username, password } = req.body;
console.log(req.body);
if (users[username] && users[username] === password) {
// We set this property in the session
// This proves the user is logged in.
// We normally might store the userid or username or
// other things in here.
req.session.loggedIn = true;
res.send({
loggedIn: true,
message: "Successfully Logged In"
});
} else {
res.status(401).send({
loggedIn: false,
message: "Unauthorized"
});
}
});
// This is an authenticated route.
// We could probably move these checks into an authRequired middleware.
app.get('/authenticated', (req, res,next) => {
if (!req.session.loggedIn) {
res.status(401).send({
loggedIn: false,
message: "Unauthorized"
});
return;
}
res.send({
loggedIn: true,
message: "Congrats you can see this"
});
});
// This logs the user out by destroying their session
app.get('/logout', (req, res, next) => {
req.session.destroy();
res.send({
loggedIn: false,
message: 'Logged Out'
});
});
module.exports = app;