-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
50 lines (42 loc) · 1.29 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
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const { validPassword } = require("./utilsFunctions/passwordValidation");
const db = require("./db/connection");
const customFields = {
usernameField: "username",
passwordField: "password",
};
const verifyCallback = async (username, password, done) => {
try {
const result = await db.query("SELECT * FROM users WHERE username = $1", [
username,
]);
if (!result.rows.length) {
return done(null, false, { message: "Incorrect username." });
}
const user = result.rows[0];
console.log(user);
const isValidPassword = await validPassword(password, user.hash, user.salt);
console.log(isValidPassword);
if (!isValidPassword) {
return done(null, false, { message: "Incorrect password." });
}
return done(null, user);
} catch (err) {
return done(err);
}
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const result = await db.query("SELECT * FROM users WHERE id = $1", [id]);
const user = result.rows[0];
done(null, user);
} catch (err) {
return done(err);
}
});