-
-
Notifications
You must be signed in to change notification settings - Fork 235
/
auth.js
80 lines (69 loc) · 2.15 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
var express = require('express');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook');
var db = require('../db');
passport.use(new FacebookStrategy({
clientID: process.env['FACEBOOK_CLIENT_ID'],
clientSecret: process.env['FACEBOOK_CLIENT_SECRET'],
callbackURL: '/oauth2/redirect/facebook',
state: true
}, function verify(accessToken, refreshToken, profile, cb) {
db.get('SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?', [
'https://www.facebook.com',
profile.id
], function(err, row) {
if (err) { return cb(err); }
if (!row) {
db.run('INSERT INTO users (name) VALUES (?)', [
profile.displayName
], function(err) {
if (err) { return cb(err); }
var id = this.lastID;
db.run('INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)', [
id,
'https://www.facebook.com',
profile.id
], function(err) {
if (err) { return cb(err); }
var user = {
id: id,
name: profile.displayName
};
return cb(null, user);
});
});
} else {
db.get('SELECT * FROM users WHERE id = ?', [ row.user_id ], function(err, row) {
if (err) { return cb(err); }
if (!row) { return cb(null, false); }
return cb(null, row);
});
}
});
}));
passport.serializeUser(function(user, cb) {
process.nextTick(function() {
cb(null, { id: user.id, username: user.username, name: user.name });
});
});
passport.deserializeUser(function(user, cb) {
process.nextTick(function() {
return cb(null, user);
});
});
var router = express.Router();
router.get('/login', function(req, res, next) {
res.render('login');
});
router.get('/login/federated/facebook', passport.authenticate('facebook'));
router.get('/oauth2/redirect/facebook', passport.authenticate('facebook', {
successReturnToOrRedirect: '/',
failureRedirect: '/login'
}));
router.post('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
module.exports = router;