-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport-config.js
45 lines (39 loc) · 1.24 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
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");
const User = require("./models/User");
function initializeStrategy(passport) {
console.log("local strategy initialized");
const authenticateUser = async (username, password, done) => {
const user = await User.getUserByUsername(username);
if (user) {
bcrypt.compare(password, user.password, (err, matched) => {
if (err) throw err;
if (matched) {
console.log("pw matched");
return done(null, user);
} else {
console.log("pw not matched");
return done(null, false, { message: "Incorrect password" });
}
});
} else {
return done(null, false, {
message: "Username is not registered",
});
}
};
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
authenticateUser
)
);
// stores a cookie with user.id inside browser
passport.serializeUser((user, done) => done(null, user.id));
// decrypt cookie to get userId
passport.deserializeUser(async (id, done) => {
const user = await User.getUserById(id);
return done(null, user);
});
}
module.exports = initializeStrategy;