-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
71 lines (56 loc) · 1.7 KB
/
auth.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
const passport = require("passport")
const User = require("./models/user")
const JWTStrategy = require("passport-jwt").Strategy
const {
fromAuthHeaderAsBearerToken, fromExtractors
} = require("passport-jwt").ExtractJwt
// Cookie extractor function
function fromCookie(req) {
let token = null
if (req.cookies) token = req.cookies["jwt"]
return token
}
passport.use(new JWTStrategy(
{
secretOrKey: process.env.JWT_SECRET,
jwtFromRequest: fromExtractors([
// Check for token in "Auth" header first
fromAuthHeaderAsBearerToken(),
// Check for token in browser cookies
fromCookie
])
},
async (payload, done) => {
// Retrieve the user's id from the payload
let userId = payload.id
if (!userId) {
const err = new Error("UserId is not included in token")
err.status = 400
return done(err)
}
const user = await User.findById(userId).exec()
if (!user) {
const err = new Error("User does not exist (maybe was deleted)")
err.status = 404
return done(err)
}
done(null, {id: userId})
}
))
function authenticate(req, res, next) {
passport.authenticate(
"jwt",
{session: false},
(err, user, info, status) => {
// Return errors from jwt strategy
if (err) return next(err)
// Return other errors
if (info) return next(info)
// Attach the user to the request object
req.user = user
// Continue
next()
}
)(req, res, next)
}
module.exports = authenticate