-
Notifications
You must be signed in to change notification settings - Fork 11
/
passport.js
80 lines (72 loc) · 2.32 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
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
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var config = require('./config');
// Initialize new session, when user logs in
passport.serializeUser(function(user, done) {
done(null, user._id);
})
// Does the user with the ID exist inside the DB?
passport.deserializeUser(function(id, done) {
User.findOne({_id: id}, function(err, user){
done(err, user);
})
});
// The actual authentication process
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(username, password, done) {
User.findOne({ email: username }, function(err, user) {
if(err) return done(err);
// Case 1: Username doesn't exist
if(!user) {
return done(null, false, {
message: 'Username and password wrong or unknown'
});
}
// Case 2: Invalid password
if(!user.validPassword(password)) {
return done(null, false, {
message: 'Username and password wrong or unknown'
});
}
// Case 3: username and password correct
return done(null, user);
})
}
));
passport.use(new FacebookStrategy({
clientID: config.facebook.appID,
clientSecret: config.facebook.appSecret,
callbackURL: config.facebook.callbackURL,
profileFields: ['id', 'displayName', 'email']
},
function(token, refreshToken, profile, done) {
User.findOne({ 'facebookId': profile.id }, function(err, user) {
if (err) return done(err);
if (user) {
return done(null, user);
} else {
debugger;
User.findOne({ email: profile.emails[0].value }, function(err, user) {
if (user) {
user.facebookId = profile.id
return user.save(function(err) {
if (err) return done(null, false, { message: "Can't save. An error has occurred." } );
return done(null, user);
})
}
var user = new User();
user.name = profile.displayName;
user.email = profile.emails[0].value;
user.facebookId = profile.id;
user.save(function(err) {
if (err) return done(null, false, { message: "Can't save. An error has occurred." } );
return done(null, user);
});
});
}
});
}
));