-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle.js
280 lines (270 loc) · 10.6 KB
/
google.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
270
271
272
273
274
275
276
277
278
279
280
/*******************************************************************************
* Copyright (C) 2018 Orange.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Rombit - initial API and implementation
******************************************************************************/
module.exports = function(RED) {
"use strict";
var request = require('request');
var crypto = require("crypto");
var url = require('url');
function GoogleNode(n) {
RED.nodes.createNode(this,n);
this.displayName = n.displayName;
}
RED.nodes.registerType("google-credentials",GoogleNode,{
credentials: {
displayName: {type:"text"},
clientId: {type:"text"},
clientSecret: {type:"password"},
accessToken: {type:"password"},
refreshToken: {type:"password"},
expireTime: {type:"password"}
}
});
GoogleNode.prototype.refreshToken = function(cb) {
var credentials = this.credentials;
var node = this;
//console.log("refreshing token: " + credentials.refreshToken);
if (!credentials.refreshToken) {
node.error(RED._("google.error.no-refresh-token"));
return cb(RED._("google.error.no-refresh-token"));
}
request.post({
url: 'https://accounts.google.com/o/oauth2/token',
json: true,
form: {
grant_type: 'refresh_token',
client_id: credentials.clientId,
client_secret: credentials.clientSecret,
refresh_token: credentials.refreshToken,
},
}, function(err, result, data) {
if (err) {
node.error(RED._("google.error.token-request-error", {err: err}));
return;
}
if (data.error) {
node.error(RED._("google.error.refresh-token-error", {message: data.error.message}));
return;
}
// console.log("refreshed: " + require('util').inspect(data));
credentials.accessToken = data.access_token;
if (data.refresh_token) {
credentials.refreshToken = data.refresh_token;
}
credentials.expiresIn = data.expires_in;
credentials.expireTime =
data.expires_in + (new Date().getTime()/1000);
credentials.tokenType = data.token_type;
RED.nodes.addCredentials(node.id, credentials);
if (typeof cb !== undefined) {
cb();
}
});
};
GoogleNode.prototype.request = function(req, retries, cb) {
var node = this;
if (typeof retries === 'function') {
cb = retries;
retries = 1;
}
// if (typeof req !== 'object') {
// req = { url: req };
// }
// req.method = req.method || 'GET';
// if (!req.hasOwnProperty("json")) {
// req.json = true;
// }
// always set access token to the latest ignoring any already present
req.auth = { bearer: this.credentials.accessToken };
//console.log(require('util').inspect(req));
if (!this.credentials.expireTime ||
this.credentials.expireTime < (new Date().getTime()/1000)) {
if (retries === 0) {
node.error(RED._("google.error.too-many-refresh-attempts"));
cb(RED._("google.error.too-many-refresh-attempts"));
return;
}
node.warn(RED._("google.warn.token-expired"));
node.refreshToken(function (err) {
if (err) {
return;
}
node.request(req, 0, cb);
});
return;
}
request(req, function(err, result, data) {
if (err) {
// handled in callback
} else if (result.statusCode >= 400) {
data = {
error: {
code: result.statusCode,
message: result.body,
},
};
} else if (data.error) {
if (data.error.code === 401 && retries > 0) {
retries--;
node.warn(RED._("google.warn.refreshing-accesstoken"));
node.refreshToken(function (err) {
if (err) {
return cb(err, null);
}
return node.request(req, retries, cb);
});
}
}
cb(err, data);
});
};
RED.httpAdmin.get('/google-credentials/auth', function(req, res){
if (!req.query.clientId || !req.query.clientSecret ||
!req.query.id || !req.query.callback) {
res.send(400);
return;
}
var node_id = req.query.id;
var callback = req.query.callback;
var credentials = {
clientId: req.query.clientId,
clientSecret: req.query.clientSecret
};
var gPlusScopes = 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile';
var driveScopes = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file'
];
var csrfToken = crypto.randomBytes(18).toString('base64').replace(/\//g, '-').replace(/\+/g, '_');
credentials.csrfToken = csrfToken;
credentials.callback = callback;
res.cookie('csrf', csrfToken);
res.redirect(url.format({
protocol: 'https',
hostname: 'accounts.google.com',
pathname: '/o/oauth2/auth',
query: {
response_type: 'code',
client_id: credentials.clientId,
state: node_id + ":" + csrfToken,
access_type: 'offline',
approval_prompt: 'force',
scope : driveScopes.join(' ') + ' ' + gPlusScopes,
// TODO: include_granted_scopes: 'true', ?
redirect_uri: callback
}
}));
RED.nodes.addCredentials(node_id, credentials);
});
RED.httpAdmin.get('/google-credentials/auth/callback', function(req, res) {
if (req.query.error) {
return res.send(RED._("google.error.error", {error: req.query.error, description: req.query.error_description}));
}
var state = req.query.state.split(':');
var node_id = state[0];
var credentials = RED.nodes.getCredentials(node_id);
if (!credentials || !credentials.clientId || !credentials.clientSecret) {
console.log("credentials not present?");
return res.send(RED._("google.error.no-credentials"));
}
if (state[1] !== credentials.csrfToken) {
return res.status(401).send(
RED._("google.error.token-mismatch")
);
}
request.post({
url: 'https://accounts.google.com/o/oauth2/token',
json: true,
form: {
grant_type: 'authorization_code',
code: req.query.code,
client_id: credentials.clientId,
client_secret: credentials.clientSecret,
redirect_uri: credentials.callback
},
}, function(err, result, data) {
if (err) {
console.log("request error:" + err);
return res.send(RED._("google.error.something-broke"));
}
if (data.error) {
console.log("oauth error: " + data.error);
return res.send(RED._("google.error.something-broke"));
}
credentials.accessToken = data.access_token;
credentials.refreshToken = data.refresh_token;
credentials.expiresIn = data.expires_in;
credentials.expireTime =
data.expires_in + (new Date().getTime()/1000);
credentials.tokenType = data.token_type;
delete credentials.csrfToken;
delete credentials.callback;
RED.nodes.addCredentials(node_id, credentials);
request.get({
url: 'https://www.googleapis.com/plus/v1/people/me',
json: true,
auth: { bearer: credentials.accessToken },
}, function(err, result, data) {
if (err) {
console.log('fetching google profile failed: ' + err);
return res.send("auth worked but profile fetching failed");
}
if (data.error) {
console.log('fetching google profile failed: ' +
data.error.message);
return res.send(RED._("google.error.profile-fetch-failed"));
}
credentials.displayName = data.displayName;
RED.nodes.addCredentials(node_id, credentials);
res.send(RED._("google.message.authorized"));
});
});
});
function GoogleAPINode(n) {
RED.nodes.createNode(this,n);
}
RED.nodes.registerType("google-api-config",GoogleAPINode,{
credentials: {
key: { type:"password" }
}
});
GoogleAPINode.prototype.request = function(req, cb) {
if (typeof req !== 'object') {
req = { url: req };
}
req.method = req.method || 'GET';
if (!req.hasOwnProperty("json")) {
req.json = true;
}
if (!req.qs) {
req.qs = {};
}
req.qs.key = this.credentials.key;
return request(req, function(err, result, data) {
if (err) {
return cb(err.toString(), null);
}
if (result.statusCode >= 400) {
return cb(RED._("google.error.httperror", {statusCode: result.statusCode}), data);
}
if (data && data.status !== 'OK') {
var error = RED._("google.error.apierror", {status: data.status});
if (data.error_message) {
error += ": " + data.error_message;
}
return cb(error, data);
}
return cb(null, data);
});
};
};