-
Notifications
You must be signed in to change notification settings - Fork 1
/
passport.js
72 lines (69 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
const passport = require("passport");
const jwtStrategy = require("passport-jwt").Strategy;
const LocalStrategy = require("passport-local").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const { JWTSECRET } = require("./secrets/secrets");
const User = require("./models/User");
/**
* To ensure Jwt Strategy is working properly ensure
* that you have put the token in the header,
* the strategy
*/
passport.use(
new jwtStrategy(
{
jwtFromRequest: ExtractJwt.fromHeader("token"), // header parameter name to retrieve token from
secretOrKey: JWTSECRET, // our secret key
},
async (payload, done) => {
try {
// extract user info from payload
console.log(payload.sub);
console.log(payload);
const user = await User.findById(payload.sub);
// if user doesn't exist handle it
if (!user) {
return done(null, false);
}
//else return user
//stripping password from the headers
minifiedUser = { _id: user._id, email: user.email };
done(null, minifiedUser);
} catch (error) {
done(error, false);
}
}
)
);
/**
* This middleware is used when our users
* login, this is where password validation takes place
*/
passport.use(
new LocalStrategy(
{ usernameField: "email" }, // identifier user enters for login (can also be username)
async (email, password, done) => {
/**
* Here we retrieve our validated parameters
* sent by the request body
* @param {string} email
* @param {string} password
* @return {Promise} done method is called and contains (error, payload)
*/
try {
const user = await User.findOne({ email });
if (!user) {
return done(null, false, { message: "Try again" });
}
const isMatch = await user.passwordValidator(password);
if (!isMatch) {
return done(null, false, { message: "Try again" });
}
const minifiedUser = { _id: user._id, email: user.email }; // removing password from our user model
done(null, minifiedUser); // user is attached to request head (req.user)
} catch (error) {
done(error, false);
}
}
)
);