-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathauth.js
106 lines (86 loc) · 2.57 KB
/
auth.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const bcrypt = require('bcrypt');
const db = require('./db/index');
// ==== Local Login ====
// https://www.passportjs.org/concepts/authentication/password/
// https://www.passportjs.org/tutorials/password/
// https://www.passportjs.org/howtos/password/
// https://medium.com/@prashantramnyc/node-js-with-passport-authentication-simplified-76ca65ee91e5
async function hashPassword(password) {
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
return hashedPassword;
}
async function localVerify(username, password, done) {
const email_address = username;
try {
const user = await db.getUserByEmail(email_address, 'local');
if (!user) {
return done(null, false,
{ message: `An account with the email address '${email_address}' does not exist.` }
);
}
const matchedPassword = await bcrypt.compare(password, user.hashed_pw);
if (!matchedPassword) {
return done(null, false, { message: 'Incorrect email address or password.' });
}
return done(null, {
id: user.id,
email_address: user.email_address,
auth_method: user.auth_method
});
} catch(err) {
return done(err);
}
}
// ==== Google Login ====
// https://www.passportjs.org/concepts/authentication/google/
// https://www.passportjs.org/tutorials/google/
// https://www.passportjs.org/reference/normalized-profile/
// https://console.cloud.google.com/apis/dashboard
const googleConfig = {
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/redirect',
scope: ['email']
}
async function googleVerify(issuer, profile, done) {
const email_address = profile.emails[0].value;
try {
let user = await db.getUserByEmail(email_address, 'google');
if (!user) {
user = await db.addGoogleUser(email_address);
}
return done(null, {
id: user.id,
email_address: user.email_address,
auth_method: 'google'
});
} catch(err) {
return done(null, null);
}
}
// ==== Serialization and Deserialization ====
// https://www.passportjs.org/concepts/authentication/sessions/
// https://www.passportjs.org/howtos/session/
function serialize(user, done) {
process.nextTick(function() {
return done(null, {
id: user.id,
email_address: user.email_address,
auth_method: user.auth_method
});
});
}
function deserialize(user, done) {
process.nextTick(function() {
return done(null, user);
});
}
module.exports = {
hashPassword,
localVerify,
googleConfig,
googleVerify,
serialize,
deserialize
};