-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
57 lines (55 loc) · 1.67 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
const passport = require("passport");
const bcrypt = require("bcrypt");
const { User } = require("./models");
const LocalStrategy = require("passport-local").Strategy;
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
function (email, password, done) {
//this one is typically a DB call. Assume that the returned user object is pre-formatted and ready for storing in JWT
return User.findOne({ where: { email } })
.then(async (user) => {
if (!user) {
return done(null, undefined, {
message: "No such user",
});
}
const result = await bcrypt.compare(password, user.password);
if (!result) {
return done(null, false, {
message: "Incorrect email or password.",
});
} else {
return done(null, user, { message: "Logged In Successfully" });
}
})
.catch((error) => {
return done(error);
});
}
)
);
const passportJWT = require("passport-jwt");
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
passport.use(
new JWTStrategy(
{
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET || "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 User.findByPk(jwtPayload.id)
.then((user) => {
return cb(null, user);
})
.catch((err) => {
return cb(err);
});
}
)
);