/
setup.gs
317 lines (291 loc) · 10.5 KB
/
setup.gs
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This code was orignally developed by Arun Nagarajan https://plus.google.com/+ArunNagarajan/
* and extended by Martin Hawksey https://plus.google.com/+MartinHawksey
*/
var consumer = { consumerKey : getStaticUserProperty_('consumerKey') || null,
consumerSecret : getStaticUserProperty_('consumerSecret') || null,
serviceProvider: { signatureMethod : "HMAC-SHA1",
requestTokenURL : "https://api.twitter.com/oauth/request_token",
userAuthorizationURL: "https://api.twitter.com/oauth/authorize",
accessTokenURL : "https://api.twitter.com/oauth/access_token" },
};
/* Set up the API root URL. */
var HOST = 'https://api.twitter.com/1.1/';
var UPLOAD_HOST = 'https://upload.twitter.com/1.1/';
/* Respons format. */
var FORMAT = 'json';
/* Managed Library Script Id (for user callback) */
var SCRIPT_ID = "MarIlVOhstkJA6QjPgCWAHIq9hSqx7jwh";
var SERVICE_URL = getStaticScriptProperty_("service_url");
var HASH = getStaticScriptProperty_('hash');
var INITIALISED_SIG = "";
var H = 380, W = 600;
/**
* Initialise script variables.
*
* @param {Object} config Override for consumer object. Parameters {consumerKey: "string", consumerSecret: "string"}.
* @return {string} Service url for signing in with Twitter.
*/
function init(config){
consumer.consumerKey = config.consumerKey;
consumer.consumerSecret = config.consumerSecret;
INITIALISED_SIG = oauthlibrary.hex_hmac_sha1(HASH, consumer);
setStaticUserProperty_(INITIALISED_SIG, JSON.stringify(consumer));
SERVICE_URL += "?signature="+INITIALISED_SIG;
return SERVICE_URL;
}
/**
* Script service to handle authentication flow.
*
* @return {HTMLService}
*/
function doGet(e){
var w = HtmlService.createTemplateFromFile('3_auth_pop');
w.parameters = e.parameters;
return w.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setHeight(320).setWidth(600)
.setTitle('Twitter Authorisation');
}
/**
* Gets a static script property, using long term caching.
* @param {string} key The property key.
* @returns {string} The property value.
*/
function getStaticScriptProperty_(key) {
var value = CacheService.getScriptCache().get(key);
if (!value) {
value = PropertiesService.getScriptProperties().getProperty(key);
CacheService.getScriptCache().put(key, value, 21600);
}
return value;
}
/**
* Gets a static user property, using long term caching.
* @param {string} key The property key.
* @returns {string} The property value.
*/
function getStaticUserProperty_(key) {
var value = CacheService.getUserCache().get(key);
if (!value) {
value = PropertiesService.getUserProperties().getProperty(key);
CacheService.getUserCache().put(key, value, 21600);
}
return value;
}
/**
* Sets a static user property, using long term caching.
* @param {string} key The property key.
* @param {string} value The property value.
*/
function setStaticUserProperty_(key, value) {
PropertiesService.getUserProperties().setProperty(key, value)
CacheService.getUserCache().put(key, value, 21600);
}
/**
* Delete a static user property, using long term caching.
* @param {string} key The property key.
* @returns {string} The property value.
*/
function deleteStaticUserProperty_(key) {
CacheService.getUserCache().remove(key);
PropertiesService.getUserProperties().deleteProperty(key)
}
/**
* Generate Twitter authorisation url.
*
* @return {string} authorisation url (link for user to start twitter authentication).
*/
function getTwitterAuthURL_(signature) {
if (signature){
INITIALISED_SIG = signature;
var accessor = JSON.parse(getStaticUserProperty_(signature));
} else {
var accessor = consumer;
}
var message = {
method: "post", action: accessor.serviceProvider.requestTokenURL
, parameters: [["oauth_callback", getCallbackURL_('handleTwitterCallback_')]]
};
var requestBody = oauthlibrary.OAuth.formEncode(message.parameters);
oauthlibrary.OAuth.completeRequest(message, accessor);
var authorizationHeader = oauthlibrary.OAuth.getAuthorizationHeader("", message.parameters);
var tokenOptions = {
"method" : message.method,
"headers" : {"Authorization" : authorizationHeader},
"muteHttpExceptions" : true
};
var requestTokenResponse = UrlFetchApp.fetch(message.action, tokenOptions);
if (requestTokenResponse.getResponseCode() != "200"){
return "<strong>Oops something went wrong</strong>. Twitter says:"+ requestTokenResponse.getContentText();
}
var tokenProperties = requestTokenResponse.getContentText().split('&');
var authorizeURL = 'https://api.twitter.com/oauth/authorize?'+tokenProperties[0];
return "<a href='"+authorizeURL+"' target='_blank' onclick='google.script.host.close();'><img src='https://g.twimg.com/dev/sites/default/files/images_documentation/sign-in-with-twitter-gray.png'/></a>";
}
/**
* Get user callback url with state token.
*
* @param {string} callback Callback method name.
* @return {string} Callback url.
*/
function getCallbackURL_(callback) {
var signature = "";
var state = ScriptApp.newStateToken().withTimeout(3600).withMethod(callback).createToken();
if (INITIALISED_SIG != ""){
signature = "&signature="+oauthlibrary.hex_hmac_sha1(HASH, consumer);
}
var url = getStaticScriptProperty_("service_url");
url = url.slice(0, -4) + 'usercallback?state='; // Change /exec to /usercallback
return url+state+signature;
}
/**
* Test if user has authenticated with Twitter.
*
* @return {boolean} Return true if user is authenticated.
*/
function isUserConnectedToTwitter(){
if (getStaticUserProperty_('screen_name'+INITIALISED_SIG)){
return true;
}
}
/**
* Handle temporary authtication callback from Twitter to get token/secret.
*
* @param {Object} e.
* @return {HTMLService} html window.
*/
function handleTwitterCallback_(e){
var signature = e.parameters.signature;
if (signature){
var accessor = JSON.parse(getStaticUserProperty_(signature));
} else {
var accessor = consumer;
signature = "";
}
var message = {
method: "post", action: accessor.serviceProvider.accessTokenURL
, parameters: [["oauth_verifier", e.parameters.oauth_verifier],["oauth_token", e.parameters.oauth_token]]
};
var requestBody = oauthlibrary.OAuth.formEncode(message.parameters);
oauthlibrary.OAuth.completeRequest(message, accessor);
var authorizationHeader = oauthlibrary.OAuth.getAuthorizationHeader("", message.parameters);
var tokenOptions = {
"method" : message.method,
"payload" : requestBody,
"headers" : {"Authorization" : authorizationHeader}
};
var accessTokenResponse = UrlFetchApp.fetch(message.action, tokenOptions);
var results = accessTokenResponse.getContentText();
var screen_name = oauthlibrary.OAuth.getParameter(results, "screen_name")
var oauth_token = oauthlibrary.OAuth.getParameter(results, "oauth_token")
var oauth_token_secret = oauthlibrary.OAuth.getParameter(results, "oauth_token_secret")
setStaticUserProperty_('screen_name'+signature, screen_name)
setStaticUserProperty_('oauth_token'+signature, oauth_token)
setStaticUserProperty_('oauth_token_secret'+signature, oauth_token_secret)
return HtmlService.createTemplateFromFile('4_auth_success')
.evaluate()
.setTitle('Twitter Authorisation Complete')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
}
/**
* Set library user key/secret
*
* @param {object} formObject Key and secret from credenitals popup
*/
function setUserKeySecret(formObject){
setStaticUserProperty_('consumerKey', formObject.consumerKey.trim());
setStaticUserProperty_('consumerSecret', formObject.consumerSecret.trim());
consumer.consumerKey = formObject.consumerKey;
consumer.consumerSecret = formObject.consumerSecret;
}
/**
* Get library user key.
* @return {string} twitter key
*/
function getUserKey(){
return getStaticUserProperty_('consumerKey');
}
/**
* Get library user secret.
* @return {string} twitter secret
*/
function getUserSecret(){
return getStaticUserProperty_('consumerSecret');
}
/**
* Disconnect user from Twitter.
*
*/
function disconnectTwitter(){
deleteStaticUserProperty_('screen_name'+INITIALISED_SIG);
deleteStaticUserProperty_('oauth_token'+INITIALISED_SIG);
deleteStaticUserProperty_('oauth_token_secret'+INITIALISED_SIG);
deleteStaticUserProperty_('consumerKey'+INITIALISED_SIG);
deleteStaticUserProperty_('consumerSecret'+INITIALISED_SIG);
}
/**
* Show auth window (private).
*
* @param {Object} doctype Instigator service (DocumentApp || SpreadsheetApp etc)
* @param {string} stepTemplate The template file to render
*/
function showDialog_(optDoctype, stepTemplate){
var doctype = optDoctype || false;
try {
var html = HtmlService.createTemplateFromFile(stepTemplate)
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setHeight(H).setWidth(W);
if (!doctype){
return html;
}
doctype.getUi().showModalDialog(html, "Twitter Authorisation");
} catch(e) {
// if Google old Sheet fallback to UiApp
switch(stepTemplate){
case "1_cred_pop":
doctype.getActiveSpreadsheet().show(cred_pop_old_());
break;
}
}
}
/**
* Show the key/secret data entry form.
*
* @param {(DocumentApp|SpreadsheetApp)} doc The Document or Spreadsheet the library is being called from.
*/
function showTwitterKeySecret(doc){
return showDialog_(doc, '1_cred_pop');
}
/**
* Show auth window for a DocumentApp.
*
* @param {(DocumentApp|SpreadsheetApp)} doc The Document or Spreadsheet the library is being called from.
*/
function showTwitterLogin(doc){
return showDialog_(doc, '2_start_auth');
}
/**
* Used as part of setup() to process form data
*/
//function processForm(formObject) {
// setUserKeySecret(formObject);
// //return showTwitterLogin(false);
//}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}