-
Notifications
You must be signed in to change notification settings - Fork 11
/
passport-config.js
44 lines (40 loc) · 1.32 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
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require("bcrypt");
const mysql = require('mysql');
function initialize(connection, passport) {
const authenticateUser = async (username, password, done) => {
connection.query('SELECT * FROM accounts WHERE username = ?', [username], async function(error, results, fields) {
if (results.length > 0) {
try {
if (await bcrypt.compare(password, results[0].password)) {
const user = {
id: results[0].id,
username: results[0].username,
password: results[0].password
};
return done(null, user)
} else {
return done(null, false, {
message: "Wrong password"
})
}
} catch (e) {
return done(e);
}
} else {
return done(null, false, {
message: "User not found"
});
}
})
}
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: "password"
}, authenticateUser));
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => connection.query("select * from accounts where id = ?", [id], function(err, results) {
done(err, results[0]);
}));
}
module.exports = initialize;