-
Notifications
You must be signed in to change notification settings - Fork 2
/
passport.js
77 lines (66 loc) · 2.22 KB
/
passport.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
'use strict'
exports = module.exports = function (app, passport) {
const LocalStrategy = require('passport-local').Strategy
const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
passport.use(new LocalStrategy(
function (username, password, done) {
const conditions = { isActive: true }
if (username.indexOf('@') === -1) {
conditions.username = username
} else {
conditions.email = username.toLowerCase()
}
app.db.models.User.findOne(conditions, function (err, user) {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, { message: '未知的使用者' })
}
app.db.models.User.validatePassword(password, user.password, function (err, isValid) {
if (err) {
return done(err)
}
if (!isValid) {
return done(null, false, { message: '無效的密碼' })
}
return done(null, user)
})
})
}
))
passport.use(new JwtStrategy(
{ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: app.config.secretkey, passReqToCallback: true },
(request, jwtPayload, done) => {
app.db.models.User.findById(jwtPayload._id).populate('roles.admin').populate('roles.account').exec(function (err, user) {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, { message: 'Unknown user' })
}
const token = request.headers.authorization.replace('Bearer ', '')
if (app.config.expiresIn) {
const now = new Date().getTime()
const tokens = user.jwt.filter(j => j.expiredAt > now)
if (user.jwt.length !== tokens.length) {
user.jwt = tokens
user.save()
}
}
if (user.jwt.filter(j => j.token === token).length === 0) {
done(null, false)
} else {
if (user && user.roles && user.roles.admin) {
user.roles.admin.populate('groups', function (err, admin) {
done(err, user)
})
} else {
done(err, user)
}
}
})
}
))
}