-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (52 loc) · 1.39 KB
/
index.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
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const rateLimitMiddleware = require('./rateLimitMiddleware');
const { userByUserId, userByUsername } = require('./users');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
(username, password, done) => {
const user = userByUsername(username);
if (!user) {
return done(null, false);
}
return done(null, user);
},
));
passport.serializeUser((user, done) => done(null, user.userId));
passport.deserializeUser((userId, done) => {
const user = userByUserId(userId);
return done(null, user);
});
function ensureAuthenticated(req, res, next) {
if (!req.isAuthenticated()) {
return res.sendStatus(401);
}
return next();
}
app.post('/login',
passport.authenticate('local'),
(req, res) => {
res.json(req.user);
});
app.get('/protected',
passport.authenticate('session'),
ensureAuthenticated,
rateLimitMiddleware,
(req, res) => {
res.json({
protected: 'resource',
});
});
module.exports = app;