-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport.js
62 lines (56 loc) · 1.66 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
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const Models = require("./models.js");
const passportJWT = require("passport-jwt");
const Users = Models.User;
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
passport.use(
new LocalStrategy(
{
usernameField: "Username",
passwordField: "Password",
},
async (username, password, callback) => {
console.log("LocalStrategy executing for username:", username);
try {
const user = await Users.findOne({ Username: username });
if (!user) {
console.log("User not found:", username);
return callback(null, false, {
message: "Incorrect username or password.",
});
}
if (!user.validatePassword(password)) {
console.log("Incorrect password for user:", username);
return callback(null, false, { message: "Incorrect password." });
}
console.log("User authenticated successfully:", username);
return callback(null, user);
} catch (error) {
console.error("Error in LocalStrategy:", error);
return callback(error);
}
}
)
);
passport.use(
new JWTStrategy(
{
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
},
async (jwtPayload, callback) => {
try {
const user = await Users.findById(jwtPayload.id);
if (user) {
return callback(null, user);
} else {
return callback(null, false);
}
} catch (error) {
return callback(error);
}
}
)
);