-
Notifications
You must be signed in to change notification settings - Fork 2
/
oauth-app.js
269 lines (241 loc) · 9.53 KB
/
oauth-app.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*jshint camelcase: false */
module.exports = function(app, config) {
'use strict';
const oauth2 = require('simple-oauth2').create({
client: {
id: config.clientId,
secret: config.clientSecret
},
auth: {
tokenHost: 'https://api.mendeley.com',
tokenPath: '/oauth/token',
authorizeHost: 'https://api.mendeley.com',
authorizePath: '/oauth/authorize'
}
});
let request = require('request');
let sdk = require('@mendeley/api');
let cookieParser = require('cookie-parser');
let Bluebird = require('bluebird');
let jsonexport = require('jsonexport');
let fs = require('fs');
let appConfig = require('./appConfig');
let accessTokenCookieName = 'accessToken';
let refreshTokenCookieName = 'refreshToken';
let tokenExchangePath = '/oauth/token-exchange';
let documents = [];
let members = [];
let total;
let startTime = new Date().getTime();
let endpoint = '/group';
app.use(cookieParser());
app.use(function(req, res, next) {
res.locals.authFlow = serverAuthCodeFlow(req, res);
next();
});
app.get('/', function(req, res) {
let token = res.locals.authFlow.getToken();
if (!token) {
console.log('No token set - authenticate');
res.locals.authFlow.authenticate();
} else {
console.log('Access token set, redirecting to', endpoint);
res.redirect(endpoint);
}
});
app.get('/group', function(req, res) {
let api = sdk({
authFlow: sdk.Auth.refreshTokenFlow({
refreshToken: req.cookies[refreshTokenCookieName],
clientId: config.clientId,
clientSecret: config.clientSecret
})
});
let options = {
profile_id: appConfig.gbifProfileId,
view: "all",
limit: "100"
};
api.documents.list(options)
.then(function(result) {
console.info('There are ' + result.total + ' documents in total');
total = result.total;
documents = documents.concat(result.items);
return resultsPager(result, documents, total);
})
.then(function(documents){
fs.writeFile(appConfig.targetDocumentPath + '/documents.json', JSON.stringify(documents), (err) => {
if (err) throw err;
var endTime = new Date().getTime();
var timeLapsed = (endTime - startTime) / 1000;
var message = 'Documents retrieved and saved. Time lapsed: ' + timeLapsed + ' seconds.';
console.info(message);
res.json({message: message});
process.exit(0);
});
})
.catch(function(reason) {
res.status(reason.status).send();
})
});
app.get('/members', function(req, res) {
let api = sdk({
authFlow: sdk.Auth.refreshTokenFlow({
refreshToken: req.cookies[refreshTokenCookieName],
clientId: config.clientId,
clientSecret: config.clientSecret
})
});
let options = {
profile_id: appConfig.gbifPublicGroupId,
view: "all",
limit: "100"
};
api.groups.members(appConfig.gbifPublicGroupId, options)
.then(function(result) {
console.info('There are ' + result.total + ' members in total');
total = result.total;
members = members.concat(result.items);
return resultsPager(result, members, total);
})
.then(function(members){
if (members.length > 0) {
const promises = members.map(member => api.profiles.retrieve(member.profile_id));
return Promise.all(promises);
}
})
.then(function(membersDetail){
if (membersDetail.length > 0) {
// strip out unnecessary objects.
/*
membersDetail.map(function(member){
let redundent = ['discipline', 'desciplines', 'photo', 'photos'];
redundent.map(function(property){
if (member.hasOwnProperty(property)) {
delete(member[property]);
}
});
});
let exportOptions = {
rowDelimiter: "\t"
};
jsonexport(membersDetail, function(err, csv){
if (err) return new Error(err.message);
});
*/
return fs.writeFile('/tmp/members.json', JSON.stringify(membersDetail), (err) => {
if (err) throw err;
var endTime = new Date().getTime();
var timeLapsed = (endTime - startTime) / 1000;
var message = 'Members retrieved and saved. Time lapsed: ' + timeLapsed + ' seconds.';
console.info(message);
res.json({message: message});
process.exit(0);
});
}
})
.catch(function(reason) {
res.status(reason.status).send();
});
});
app.get(tokenExchangePath, function (req, res, next) {
console.log('Starting token exchange');
let code = req.query.code;
oauth2.authorizationCode.getToken({
redirect_uri: config.redirectUri,
code: code,
}, function(error, result) {
if (error) {
console.log('Error exchanging token', error);
res.redirect('/logout');
} else {
setCookies(res, result);
res.redirect(endpoint);
}
});
});
app.get('/login', function(req, res) {
console.log('Logging in, clearing any existing cookies');
res.clearCookie(accessTokenCookieName);
res.clearCookie(refreshTokenCookieName);
res.locals.authFlow.authenticate();
});
app.get('/oauth/refresh', function(req, res, next) {
res.set('Content-Type', 'application/json');
res.locals.authFlow.refreshToken().then(function() {
return {
json: '{ message: "Refresh token succeeded" }',
status: 200
};
}).catch(function() {
return {
status: 401,
json: '{ message: "Refresh token invalid" }'
};
}).then(function(result) {
res.status(result.status).send(result.json);
});
});
function resultsPager(result, container, total) {
return new Bluebird(function(resolve, reject){
if (typeof result.next === 'function') {
result.next()
.then(function(result){
container = container.concat(result.items);
console.info('Retrieved ' + container.length + ' items.');
resolve(resultsPager(result, container, total));
})
.catch(function(err){
reject(err);
});
}
else if (container.length === total) {
resolve(container);
}
});
}
function setCookies(res, token) {
res.cookie(accessTokenCookieName, token.access_token, { maxAge: token.expires_in * 1000 });
res.cookie(refreshTokenCookieName, token.refresh_token, { httpOnly: true });
}
function serverAuthCodeFlow(req, res) {
let accessToken = req.cookies[accessTokenCookieName];
let refreshToken = req.cookies[refreshTokenCookieName];
return {
authenticate: function() {
const authorizationUri = oauth2.authorizationCode.authorizeURL({
redirect_uri: config.redirectUri,
scope: 'all',
state: '213653957730.97845'
});
console.log('No cookie defined, redirecting to', authorizationUri);
res.redirect(authorizationUri);
},
getToken: function() {
return accessToken;
},
refreshToken: function() {
if (!refreshToken) {
return Bluebird.reject(new Error('No refresh token'));
} else {
return new Bluebird(function(resolve, reject) {
oauth2.accessToken.create({
access_token: accessToken,
refresh_token: refreshToken
}).refresh(function(error, result) {
if (error) {
console.log('Error while refreshing token', error);
reject(error);
} else {
accessToken = result.token.access_token;
refreshToken = result.token.refresh_token;
setCookies(res, result.token);
resolve();
}
});
});
}
}
};
}
};