-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport.config.js
96 lines (88 loc) · 2.42 KB
/
passport.config.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const passport = require("passport");
const createHttpError = require("http-errors");
const { Strategy: JwtStrategy, ExtractJwt } = require("passport-jwt");
const LocalStrategy = require("passport-local").Strategy;
const AuthService = require("../app/services/auth.service");
const { UserModel } = require("../app/models/user.model");
const { extractJwtFromCookies } = require("../utils/cookie.util");
const keys = require("./keys");
const messages = require("./messages");
// Local Strategy
passport.use(
"local",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const user = await UserModel.findOne({ email });
if (!user)
return done(
createHttpError.Unauthorized(messages.errors.auth.userNotFound),
false
);
const isValidPassword = await AuthService.validatePassword(
password,
user.password
);
if (!isValidPassword)
return done(
createHttpError.Unauthorized(messages.errors.auth.invalidPassword),
false
);
return done(null, user);
} catch (err) {
return done(err, false);
}
}
)
);
// Access Token Strategy
const accessOpts = {
jwtFromRequest: ExtractJwt.fromExtractors([
(req) => extractJwtFromCookies(req, "accessToken"),
]),
secretOrKey: keys.jwt.accessSecret,
};
passport.use(
"jwt-access",
new JwtStrategy(accessOpts, async (payload, done) => {
try {
const user = await UserModel.findById(payload._id);
if (!user)
return done(
createHttpError.Unauthorized(messages.errors.auth.userNotFound),
false
);
return done(null, user);
} catch (err) {
return done(err, false);
}
})
);
// Refresh Token Strategy
const refreshOpts = {
jwtFromRequest: ExtractJwt.fromExtractors([
(req) => extractJwtFromCookies(req, "refreshToken"),
]),
secretOrKey: keys.jwt.refreshSecret,
};
passport.use(
"jwt-refresh",
new JwtStrategy(refreshOpts, async (payload, done) => {
try {
const user = await UserModel.findById(payload._id);
if (!user)
return done(
createHttpError.Unauthorized(messages.errors.auth.userNotFound),
false
);
return done(null, user);
} catch (err) {
return done(err, false);
}
})
);
module.exports = passport;