-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-1.js
58 lines (47 loc) · 1.25 KB
/
server-1.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
'use strict';
/**
* Step 0
* Protect aj endpoint with Gatekeep - a custom middleware
*/
const express = require('express');
const { PORT } = require('./config');
const app = express();
app.use(express.static('public'));
app.use(express.json());
// ===== Public endpoint =====
app.get('/api/welcome', function (req, res) {
res.json({message: 'Hello!'});
});
// ===== Gatekeeper example =====
function gateKeeper(req, res, next) {
const { username, password } = req.body;
try {
if (!username && !password) {
console.log('Bad Request');
return res.sendStatus(400);
}
if (username !== 'bobuser') {
console.log('Incorrect username');
return res.sendStatus(401);
}
if (password !== 'baseball') {
console.log('Incorrect password');
return res.sendStatus(401);
}
req.user = { username, password };
next();
} catch (err) {
next(err);
}
}
// ===== Protected endpoint =====
app.post('/api/login', gateKeeper, (req, res, next) => {
console.log(`${req.user.username} ${req.user.password} successfully logged in.`);
res.json({
message: 'Rosebud',
username: req.user.username
});
});
app.listen(PORT, function () {
console.log(`app listening on port ${this.address().port}`);
});