-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathauth.js
239 lines (219 loc) · 7.56 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
var request = require('request');
var sprintf = require('sprintf').sprintf;
var OAuth2 = require('oauth').OAuth2;
var querystring = require('querystring');
var express = require('express');
var async = require('async');
var fs = require('fs');
function clearPushes(req, base, callback) {
request.post({
uri: sprintf('%s/push?access_token='+req.session.access_token, base),
body: '{}',
headers: {
'Content-Type': 'application/json'
}
}, callback);
};
module.exports = function(app, clientId, clientSecret, hostBaseUrl, hostPort) {
var apiBaseUrl = 'https://api.singly.com';
var sessionSecret = '42';
var usedServices = [
'Facebook',
'foursquare',
'Instagram',
'Tumblr',
'Twitter',
'LinkedIn',
'FitBit',
'Email',
'Withings',
'Zeo'
];
var oa = new OAuth2(clientId, clientSecret, apiBaseUrl);
// A convenience method that takes care of adding the access token to requests
function getProtectedResource(path, access_token, callback) {
oa.getProtectedResource(apiBaseUrl + path, access_token, callback);
}
// Given the name of a service and the array of profiles, return a link to that
// service that's styled appropriately (i.e. show a link or a checkmark).
function getLink(prettyName, profiles, pushes, token, callback) {
var service = prettyName.toLowerCase();
// This flow is documented here: http://dev.singly.com/authorization
var queryString = querystring.stringify({
client_id: clientId,
redirect_uri: sprintf('%s/callback', hostBaseUrl),
service: service
});
// If the user has a profile authorized for this service
if (profiles && profiles[service] !== undefined) {
var ret = sprintf('<li><span class="check">✓</span> <a href="%s/services/%s?access_token=%s">%s</a>', apiBaseUrl, service, token, prettyName);
getProtectedResource('/services/' + service, token, function(err, endpoints) {
try {
endpoints = JSON.parse(endpoints);
} catch(parseErr) {
return callback(ret);
}
ret += "<ul>";
async.forEachSeries(Object.keys(endpoints), function(index, cb) {
var url = apiBaseUrl + '/services/' + service + '/' + index;
ret += '<li>';
if (pushes && pushes[url] !== undefined) {
ret += '<span class="check">✓</span>';
}
ret += sprintf('<a href="/push?service=%s&endpoint=%s">%s</a>',
service,
index,
index);
cb();
}, function (err) {
ret += '</ul>';
return callback(ret);
});
});
}
else {
return callback(sprintf('<li><a href="%s/oauth/authorize?%s">%s</a>',
apiBaseUrl,
queryString,
prettyName));
}
}
// Setup for the express web framework
app.configure(function() {
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: sessionSecret
}));
app.use(app.router);
});
// We want exceptions and stracktraces in development
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
// ... but not in production
app.configure('production', function() {
app.use(express.errorHandler());
});
// Use ejs instead of jade because HTML is easy
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
var i, j;
var services = [];
// For each service in usedServices, get a link to authorize it
async.forEach(usedServices, function(service, callback) {
getLink(service, req.session.profiles, req.session.pushes, req.session.access_token, function (link) {
services.push({
name: service,
link: link
});
callback();
});
}, function(err) {
// Render out views/index.ejs, passing in the array of links and the session
res.render('index', {
services: services,
session: req.session
});
});
});
app.get('/clear', function(req, res) {
clearPushes(req, apiBaseUrl, function(err, resp, body) {
console.log(err);
console.log(body);
req.session.pushes = JSON.parse(body).data;
res.redirect('/');
});
});
app.get('/push', function (req, res) {
var pushes = req.session.pushes;
var pushUrl = apiBaseUrl + '/services/' + req.query.service + '/' + req.query.endpoint;
if (pushes && pushes[pushUrl]) {
delete pushes[pushUrl];
} else pushes[pushUrl] = hostBaseUrl + 'post';
request.post({
uri: sprintf('%s/push?access_token='+req.session.access_token, apiBaseUrl),
body: JSON.stringify(pushes),
headers: {
'Content-Type': 'application/json'
}
}, function (err, resp, body) {
try {
console.log(err);
req.session.pushes = JSON.parse(body).data;
} catch(parseErr) {
return res.send(parseErr, 500);
}
console.log(req.session.pushes);
res.redirect('/');
});
});
app.get('/callback', function(req, res) {
var data = {
client_id: clientId,
client_secret: clientSecret,
code: req.param('code')
};
// Exchange the OAuth2 code for an access_token
request.post({
uri: sprintf('%s/oauth/access_token', apiBaseUrl),
body: querystring.stringify(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, function (err, resp, body) {
try {
body = JSON.parse(body);
} catch(parseErr) {
return res.send(parseErr, 500);
}
// Save the access_token for future API requests
req.session.access_token = body.access_token;
fs.writeFile('./config/access_token.txt', req.session.access_token, 'utf8', function (err) {
if (err) console.log(err);
});
// Fetch the user's service profile and push data
async.parallel([
function(callback) {
getProtectedResource('/profiles', req.session.access_token, function(err, profilesBody) {
try {
profilesBody = JSON.parse(profilesBody);
} catch(parseErr) {
return res.send(parseErr, 500);
}
req.session.profiles = profilesBody;
console.log("getting profiles");
callback();
});
},
function(callback) {
getProtectedResource('/push', req.session.access_token, function(err, pushBody) {
if (err) {
req.session.pushes = {};
return callback();
}
try {
pushBody = JSON.parse(pushBody);
} catch(parseErr) {
console.log('push error');
return res.send(parseErr, 500);
}
req.session.pushes = pushBody.data;
console.log("getting push");
callback();
});
}],
function() {
console.log("done");
res.redirect('/');
});
});
});
app.listen(hostPort);
console.log(sprintf('Listening at %s using API endpoint %s.', hostBaseUrl, apiBaseUrl));
}