forked from vcipi/blockly_unix
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpassport-config.js
50 lines (44 loc) · 1.36 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
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
// Initialize function to set up LocalStrategy
function initialize(passport, getUserByUsername, getUserById) {
// Local Strategy for login
const authenticateUser = async (username, password, done) => {
getUserByUsername(username, async (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'No user found with that username'
});
}
try {
// Compare the provided password with the stored hashed password
if (await bcrypt.compare(password, user.password)) {
return done(null, user);
} else {
return done(null, false, { message: 'Password incorrect' });
}
} catch (e) {
return done(e);
}
});
};
// Use LocalStrategy for authentication
passport.use(
new LocalStrategy({ usernameField: 'username' }, authenticateUser)
);
// Serialize user into the session
passport.serializeUser((user, done) => {
done(null, user.id); // Use the `id` from the database
});
// Deserialize user from the session
passport.deserializeUser((id, done) => {
getUserById(id, (err, user) => {
if (err) return done(err);
return done(null, user);
});
});
}
module.exports = initialize;