-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathauth.js
56 lines (41 loc) · 1.31 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
/*
* Module dependencies
*/
var passport = require('passport')
, keys = require('./keys.json')
, mongoose = require('mongoose')
var User = mongoose.model('User');
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
done(err, user);
});
});
module.exports = function(app) {
app.set('providers', Object.keys(keys));
for(var strategy in keys) {
(function(provider){
app.get('/auth/' + provider, passport.authenticate(provider));
app.get('/auth/' + provider + '/callback', passport.authenticate(provider, { failureRedirect: '/' }), function(req, res){ res.redirect('/'); });
var Strategy = require('passport-' + provider).Strategy;
passport.use(new Strategy(keys[provider],
function(token, tokenSecret, profile, done) {
User.findOne({provider_id: profile.id, provider: provider}, function(err, user){
if(!user) {
var user = new User();
user.provider = provider;
user.provider_id = profile.id;
user.username = profile.username || profile.displayName;
user.save(function(err, user){
done(null, user);
});
} else {
done(null, user);
}
});
}));
})(strategy);
}
};