-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
95 lines (81 loc) · 2.54 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
var express = require('express');
var passport = require('passport');
var AppleStrategy = require('@nicokaiser/passport-apple');
var db = require('../db');
//console.log(process.env['APPLE_KEY']);
passport.use(new AppleStrategy({
clientID: process.env['APPLE_CLIENT_ID'],
teamID: process.env['APPLE_TEAM_ID'],
keyID: process.env['APPLE_KEY_ID'],
callbackURL: 'https://todos-express-passport-apple.onrender.com/oauth2/redirect/apple',
key: process.env['APPLE_KEY'],
scope: ['name', 'email'],
state: true
}, function verify(accessToken, refreshToken, profile, cb) {
console.log('VERIFY APPLE!');
console.log(accessToken);
console.log(refreshToken);
console.log(profile);
db.get('SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?', [
'https://appleid.apple.com',
profile.id
], function(err, row) {
if (err) { return cb(err); }
if (!row) {
db.run('INSERT INTO users (name) VALUES (?)', [
profile.name
], function(err) {
if (err) { return cb(err); }
var id = this.lastID;
db.run('INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)', [
id,
'https://appleid.apple.com',
profile.id
], function(err) {
if (err) { return cb(err); }
var user = {
id: id,
name: profile.name
};
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/apple', passport.authenticate('apple'));
router.get('/oauth2/redirect/apple', passport.authenticate('apple', {
successReturnToOrRedirect: '/',
failureRedirect: '/login'
}));
router.post('/oauth2/redirect/apple', passport.authenticate('apple', {
successReturnToOrRedirect: '/',
failureRedirect: '/login'
}));
router.post('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
module.exports = router;