-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassport.js
More file actions
40 lines (37 loc) · 1.3 KB
/
passport.js
File metadata and controls
40 lines (37 loc) · 1.3 KB
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
// passport.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const passportJWT = require("passport-jwt");
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, cb) {
//this one is typically a DB call. Assume that the returned user object is pre-formatted and ready for storing in JWT
return UserModel.findOne({email, password})
.then(user => {
if (!user) {
return cb(null, false, {message: 'Incorrect email or password.'});
}
return cb(null, user, {message: 'Logged In Successfully'});
})
.catch(err => cb(err));
}
));
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'your_jwt_secret'
},
function (jwtPayload, cb) {
//find the user in db if needed. This functionality may be omitted if you store everything you'll need in JWT payload.
return UserModel.findOneById(jwtPayload.id)
.then(user => {
return cb(null, user);
})
.catch(err => {
return cb(err);
});
}
));