-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport.js
51 lines (48 loc) · 1.42 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
/* eslint-disable no-console */
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const passportJWT = require('passport-jwt');
const models = require('./models.js');
require('dotenv').config();
const users = models.user;
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
passport.use(
new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password',
},
(usernamePassport, passwordPassport, callback) => {
users.findOne(
{ username: usernamePassport },
(err, user) => {
if (err) {
console.error(err);
return callback(err);
}
if (!user) {
return callback(null, false, { message: 'Oops! Incorrect username. Please try again.' });
}
if (!user.validatePassword(passwordPassport)) {
return callback(null, false, { message: 'Oops! Incorrect password. Please try again.' });
}
return callback(null, user);
},
);
},
),
);
passport.use(
new JWTStrategy(
{
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
},
(jwtPayload, callback) => users
// eslint-disable-next-line no-underscore-dangle
.findById(jwtPayload._id)
.then((user) => callback(null, user))
.catch((err) => callback(err)),
),
);