-
Notifications
You must be signed in to change notification settings - Fork 1
/
passport-config.js
70 lines (66 loc) · 2.27 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const LocalStrategy = require('passport-local');
const User = require('./models/user');
const errorMessage = 'Incorrect email or password.';
const initLocalLoginInAndRegisterStrategies = function (passport) {
//Setup login strategy
passport.use('local-login', new LocalStrategy(
{
usernameField: 'email',
},
function(email, password, done) {
if (email) {
email = email.toLowerCase();
}
User.findOne({ 'local.email': email }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: errorMessage });
}
if (!user.validPassword(password)) {
return done(null, false, { message: errorMessage });
}
return done(null, user);
});
}
));
//Setup register strategy
passport.use('local-register', new LocalStrategy(
{
usernameField: 'email',
passReqToCallback : true
},
function(req, email, password, done) {
//Check if email is null
if (!email) {
return done(null, false, { message: 'Email is required' });
}
if (!password) {
return done(null, false, { message: 'Password is required' });
}
if (!req.body.name) {
return done(null, false, { message: 'Name is required' });
}
email = email.toLowerCase();
name = req.body.name.trim();
User.findOne({ 'local.email': email }, function(err, user) {
if (err) { return done(err); }
if (user) {
return done(null, false, { message: 'Email already exist' });
}
//Check if password matches
if (password != req.body.confirmPassword) {
return done(null, false, { message: 'Password must match' });
}
const newUser = new User();
newUser.local.name = name;
newUser.local.email = email;
newUser.local.password = newUser.hashPassword(password);
newUser.save(function(err){
if (err) return done(err);
return done(null, newUser);
});
});
}
));
}
module.exports = { initLocalLoginInAndRegisterStrategies };