forked from mcrownover7/vt-legal-aid-hca-capstone
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpassport-config.js
50 lines (45 loc) · 1.74 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')
function initialize (passport, getUserByEmail, getUserById) {
//makes sure user info is correct
const authenticateUser = async (email, password, done) => {
const user = await getUserByEmail(email) //returns user by email or null if no email
if (user == null) {
//if no user found(null) you get an error message
return done(null, false, {
message: 'No user with that email, try again.'
})
} //check password if user IS found
try {
if (await bcrypt.compare(password, user.Password)) {
//user pw is found
return done(null, user)
} else {
//user not found (first parameter is done)
return done(null, false, {
message: 'Password is incorrect, try again'
})
}
} catch (error) {
return done(error)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
/*Serializing a user determines which data of the user object should be stored in the session, usually the user id . The serializeUser() function sets
an id as the cookie in the user's browser, and the deserializeUser() function uses the id to look up the user in the database and retrieve the user object with data.*/
passport.serializeUser((user, done) => {
done(null, user.Email)
})
passport.deserializeUser(async (email, done) => {
try {
const user = await getUserByEmail(email) //returns user by email or null if no email
if (!user) {
return done(new Error('user not found'));
}
done(null, user);
} catch (e) {
done(e);
}
}) //serialize user as single id so must then de-serialize
}
module.exports = initialize