-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport.add.js
76 lines (66 loc) · 2.36 KB
/
passport.add.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
const passport = require("passport");
const { Strategy: LocalStrategy } = require("passport-local");
const { Strategy: JWTStrategy, ExtractJwt } = require("passport-jwt");
const User = require("./api/user/user.model");
const { compareSync } = require("bcryptjs");
passport.config = () => {
passport.use(
"local",
new LocalStrategy(
{
passReqToCallback: true,
usernameField: "email",
passwordField: "password"
},
async (req, email, password, callbackfn) => {
try {
const user = await User.findOne({ email });
if (!user) {
return callbackfn({ status: 401, message: "Invalid email or password" }, null);
}
if (compareSync(password, user.password)) {
await User.populate(user, {
path: "photo",
select: "url"
});
return callbackfn(null, user);
}
return callbackfn({ status: 401, message: "Invalid email or password" }, null);
} catch (err) {
return callbackfn(err, null);
}
}
)
);
const JWTOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_KEY
};
passport.use(
"jwt",
new JWTStrategy(
JWTOptions,
async ({ id }, callbackfn) => {
try {
const user = await User.findById(id);
return user ? callbackfn(null, user) : callbackfn({ status: 401, message: "Token is invalid." }, null);
} catch (err) {
return callbackfn(err, null);
}
}
)
);
passport.serializeUser(async (req, user, callbackfn) => {
return callbackfn(null, user._id);
});
passport.deserializeUser(async (req, id, callbackfn) => {
try {
const user = await User.findById(id);
user.populate("photo", "url");
return callbackfn(null, user);
} catch (err) {
return callbackfn(err, null);
}
});
}
module.exports = passport;