forked from googleworkspace/apps-script-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOAuth2.gs
984 lines (915 loc) · 30.1 KB
/
OAuth2.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
(function (host, expose) {
var module = { exports: {} };
var exports = module.exports;
/****** code begin *********/
// 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.
/**
* @file Contains the methods exposed by the library, and performs
* any required setup.
*/
/**
* The supported formats for the returned OAuth2 token.
* @enum {string}
*/
var TOKEN_FORMAT = {
/** JSON format, for example <code>{"access_token": "..."}</code> **/
JSON: 'application/json',
/** Form URL-encoded, for example <code>access_token=...</code> **/
FORM_URL_ENCODED: 'application/x-www-form-urlencoded'
};
/**
* The supported locations for passing the state parameter.
* @enum {string}
*/
var STATE_PARAMETER_LOCATION = {
/**
* Pass the state parameter in the authorization URL.
* @default
*/
AUTHORIZATION_URL: 'authorization-url',
/**
* Pass the state token in the redirect URL, as a workaround for APIs that
* don't support the state parameter.
*/
REDIRECT_URL: 'redirect-url'
};
/**
* Creates a new OAuth2 service with the name specified. It's usually best to
* create and configure your service once at the start of your script, and then
* reference them during the different phases of the authorization flow.
* @param {string} serviceName The name of the service.
* @return {Service_} The service object.
*/
function createService(serviceName) {
return new Service_(serviceName);
}
/**
* Returns the redirect URI that will be used for a given script. Often this URI
* needs to be entered into a configuration screen of your OAuth provider.
* @param {string} scriptId The script ID of your script, which can be found in
* the Script Editor UI under "File > Project properties".
* @return {string} The redirect URI.
*/
function getRedirectUri(scriptId) {
return Utilities.formatString(
'https://script.google.com/macros/d/%s/usercallback', scriptId);
}
if (typeof module === 'object') {
module.exports = {
createService: createService,
getRedirectUri: getRedirectUri,
TOKEN_FORMAT: TOKEN_FORMAT,
STATE_PARAMETER_LOCATION: STATE_PARAMETER_LOCATION
};
}
// 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.
/**
* @file Contains the Service_ class.
*/
// Disable JSHint warnings for the use of eval(), since it's required to prevent
// scope issues in Apps Script.
// jshint evil:true
/**
* Creates a new OAuth2 service.
* @param {string} serviceName The name of the service.
* @constructor
*/
var Service_ = function(serviceName) {
validate_({
'Service name': serviceName
});
this.serviceName_ = serviceName;
this.params_ = {};
this.tokenFormat_ = TOKEN_FORMAT.JSON;
this.tokenHeaders_ = null;
this.scriptId_ = eval('Script' + 'App').getScriptId();
this.expirationMinutes_ = 60;
};
/**
* The number of seconds before a token actually expires to consider it expired
* and refresh it.
* @type {number}
* @private
*/
Service_.EXPIRATION_BUFFER_SECONDS_ = 60;
/**
* The number of milliseconds that a token should remain in the cache.
* @type {number}
* @private
*/
Service_.LOCK_EXPIRATION_MILLISECONDS_ = 30 * 1000;
/**
* Sets the service's authorization base URL (required). For Google services
* this URL should be
* https://accounts.google.com/o/oauth2/auth.
* @param {string} authorizationBaseUrl The authorization endpoint base URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setAuthorizationBaseUrl = function(authorizationBaseUrl) {
this.authorizationBaseUrl_ = authorizationBaseUrl;
return this;
};
/**
* Sets the service's token URL (required). For Google services this URL should
* be https://accounts.google.com/o/oauth2/token.
* @param {string} tokenUrl The token endpoint URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenUrl = function(tokenUrl) {
this.tokenUrl_ = tokenUrl;
return this;
};
/**
* Sets the service's refresh URL. Some OAuth providers require a different URL
* to be used when generating access tokens from a refresh token.
* @param {string} refreshUrl The refresh endpoint URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setRefreshUrl = function(refreshUrl) {
this.refreshUrl_ = refreshUrl;
return this;
};
/**
* Sets the format of the returned token. Default: OAuth2.TOKEN_FORMAT.JSON.
* @param {OAuth2.TOKEN_FORMAT} tokenFormat The format of the returned token.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenFormat = function(tokenFormat) {
this.tokenFormat_ = tokenFormat;
return this;
};
/**
* Sets the additional HTTP headers that should be sent when retrieving or
* refreshing the access token.
* @param {Object.<string,string>} tokenHeaders A map of header names to values.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenHeaders = function(tokenHeaders) {
this.tokenHeaders_ = tokenHeaders;
return this;
};
/**
* @callback tokenHandler
* @param tokenPayload {Object} A hash of parameters to be sent to the token
* URL.
* @param tokenPayload.code {string} The authorization code.
* @param tokenPayload.client_id {string} The client ID.
* @param tokenPayload.client_secret {string} The client secret.
* @param tokenPayload.redirect_uri {string} The redirect URI.
* @param tokenPayload.grant_type {string} The type of grant requested.
* @returns {Object} A modified hash of parameters to be sent to the token URL.
*/
/**
* Sets an additional function to invoke on the payload of the access token
* request.
* @param {tokenHandler} tokenHandler tokenHandler A function to invoke on the
* payload of the request for an access token.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenPayloadHandler = function(tokenHandler) {
this.tokenPayloadHandler_ = tokenHandler;
return this;
};
/**
* Sets the name of the authorization callback function (required). This is the
* function that will be called when the user completes the authorization flow
* on the service provider's website. The callback accepts a request parameter,
* which should be passed to this service's <code>handleCallback()</code> method
* to complete the process.
* @param {string} callbackFunctionName The name of the callback function.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setCallbackFunction = function(callbackFunctionName) {
this.callbackFunctionName_ = callbackFunctionName;
return this;
};
/**
* Sets the client ID to use for the OAuth flow (required). You can create
* client IDs in the "Credentials" section of a Google Developers Console
* project. Although you can use any project with this library, it may be
* convinient to use the project that was created for your script. These
* projects are not visible if you visit the console directly, but you can
* access it by click on the menu item "Resources > Advanced Google services" in
* the Script Editor, and then click on the link "Google Developers Console" in
* the resulting dialog.
* @param {string} clientId The client ID to use for the OAuth flow.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setClientId = function(clientId) {
this.clientId_ = clientId;
return this;
};
/**
* Sets the client secret to use for the OAuth flow (required). See the
* documentation for <code>setClientId()</code> for more information on how to
* create client IDs and secrets.
* @param {string} clientSecret The client secret to use for the OAuth flow.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setClientSecret = function(clientSecret) {
this.clientSecret_ = clientSecret;
return this;
};
/**
* Sets the property store to use when persisting credentials (required). In
* most cases this should be user properties, but document or script properties
* may be appropriate if you want to share access across users.
* @param {PropertiesService.Properties} propertyStore The property store to use
* when persisting credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/properties/
*/
Service_.prototype.setPropertyStore = function(propertyStore) {
this.propertyStore_ = propertyStore;
return this;
};
/**
* Sets the cache to use when persisting credentials (optional). Using a cache
* will reduce the need to read from the property store and may increase
* performance. In most cases this should be a private cache, but a public cache
* may be appropriate if you want to share access across users.
* @param {CacheService.Cache} cache The cache to use when persisting
* credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/cache/
*/
Service_.prototype.setCache = function(cache) {
this.cache_ = cache;
return this;
};
/**
* Sets the lock to use when checking and refreshing credentials (optional).
* Using a lock will ensure that only one execution will be able to access the
* stored credentials at a time. This can prevent race conditions that arise
* when two executions attempt to refresh an expired token.
* @param {LockService.Lock} lock The lock to use when accessing credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/lock/
*/
Service_.prototype.setLock = function(lock) {
this.lock_ = lock;
return this;
};
/**
* Sets the scope or scopes to request during the authorization flow (optional).
* If the scope value is an array it will be joined using the separator before
* being sent to the server, which is is a space character by default.
* @param {string|Array.<string>} scope The scope or scopes to request.
* @param {string} [optSeparator] The optional separator to use when joining
* multiple scopes. Default: space.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setScope = function(scope, optSeparator) {
var separator = optSeparator || ' ';
this.params_.scope = Array.isArray(scope) ? scope.join(separator) : scope;
return this;
};
/**
* Sets an additional parameter to use when constructing the authorization URL
* (optional). See the documentation for your service provider for information
* on what parameter values they support.
* @param {string} name The parameter name.
* @param {string} value The parameter value.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setParam = function(name, value) {
this.params_[name] = value;
return this;
};
/**
* Sets the private key to use for Service Account authorization.
* @param {string} privateKey The private key.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setPrivateKey = function(privateKey) {
this.privateKey_ = privateKey;
return this;
};
/**
* Sets the issuer (iss) value to use for Service Account authorization.
* If not set the client ID will be used instead.
* @param {string} issuer This issuer value
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setIssuer = function(issuer) {
this.issuer_ = issuer;
return this;
};
/**
* Sets the subject (sub) value to use for Service Account authorization.
* @param {string} subject This subject value
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setSubject = function(subject) {
this.subject_ = subject;
return this;
};
/**
* Sets number of minutes that a token obtained through Service Account
* authorization should be valid. Default: 60 minutes.
* @param {string} expirationMinutes The expiration duration in minutes.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setExpirationMinutes = function(expirationMinutes) {
this.expirationMinutes_ = expirationMinutes;
return this;
};
/**
* Gets the authorization URL. The first step in getting an OAuth2 token is to
* have the user visit this URL and approve the authorization request. The
* user will then be redirected back to your application using callback function
* name specified, so that the flow may continue.
* @return {string} The authorization URL.
*/
Service_.prototype.getAuthorizationUrl = function() {
validate_({
'Client ID': this.clientId_,
'Script ID': this.scriptId_,
'Callback function name': this.callbackFunctionName_,
'Authorization base URL': this.authorizationBaseUrl_
});
var redirectUri = getRedirectUri(this.scriptId_);
var state = eval('Script' + 'App').newStateToken()
.withMethod(this.callbackFunctionName_)
.withArgument('serviceName', this.serviceName_)
.withTimeout(3600)
.createToken();
var params = {
client_id: this.clientId_,
response_type: 'code',
redirect_uri: redirectUri,
state: state
};
params = extend_(params, this.params_);
return buildUrl_(this.authorizationBaseUrl_, params);
};
/**
* Completes the OAuth2 flow using the request data passed in to the callback
* function.
* @param {Object} callbackRequest The request data recieved from the callback
* function.
* @return {boolean} True if authorization was granted, false if it was denied.
*/
Service_.prototype.handleCallback = function(callbackRequest) {
var code = callbackRequest.parameter.code;
var error = callbackRequest.parameter.error;
if (error) {
if (error == 'access_denied') {
return false;
} else {
throw new Error('Error authorizing token: ' + error);
}
}
validate_({
'Client ID': this.clientId_,
'Client Secret': this.clientSecret_,
'Script ID': this.scriptId_,
'Token URL': this.tokenUrl_
});
var redirectUri = getRedirectUri(this.scriptId_);
var headers = {
'Accept': this.tokenFormat_
};
if (this.tokenHeaders_) {
headers = extend_(headers, this.tokenHeaders_);
}
var tokenPayload = {
code: code,
client_id: this.clientId_,
client_secret: this.clientSecret_,
redirect_uri: redirectUri,
grant_type: 'authorization_code'
};
if (this.tokenPayloadHandler_) {
tokenPayload = this.tokenPayloadHandler_(tokenPayload);
}
var response = UrlFetchApp.fetch(this.tokenUrl_, {
method: 'post',
headers: headers,
payload: tokenPayload,
muteHttpExceptions: true
});
var token = this.getTokenFromResponse_(response);
this.saveToken_(token);
return true;
};
/**
* Determines if the service has access (has been authorized and hasn't
* expired). If offline access was granted and the previous token has expired
* this method attempts to generate a new token.
* @return {boolean} true if the user has access to the service, false
* otherwise.
*/
Service_.prototype.hasAccess = function() {
return this.lockable_(function() {
var token = this.getToken();
if (!token || this.isExpired_(token)) {
if (token && token.refresh_token) {
try {
this.refresh();
} catch (e) {
this.lastError_ = e;
return false;
}
} else if (this.privateKey_) {
try {
this.exchangeJwt_();
} catch (e) {
this.lastError_ = e;
return false;
}
} else {
return false;
}
}
return true;
});
};
/**
* Gets an access token for this service. This token can be used in HTTP
* requests to the service's endpoint. This method will throw an error if the
* user's access was not granted or has expired.
* @return {string} An access token.
*/
Service_.prototype.getAccessToken = function() {
if (!this.hasAccess()) {
throw new Error('Access not granted or expired.');
}
var token = this.getToken();
return token.access_token;
};
/**
* Resets the service, removing access and requiring the service to be
* re-authorized.
*/
Service_.prototype.reset = function() {
this.getStorage().removeValue(null);
};
/**
* Gets the last error that occurred this execution when trying to automatically
* refresh or generate an access token.
* @return {Exception} An error, if any.
*/
Service_.prototype.getLastError = function() {
return this.lastError_;
};
/**
* Returns the redirect URI that will be used for this service. Often this URI
* needs to be entered into a configuration screen of your OAuth provider.
* @return {string} The redirect URI.
*/
Service_.prototype.getRedirectUri = function() {
return getRedirectUri(this.scriptId_);
};
/**
* Gets the token from a UrlFetchApp response.
* @param {UrlFetchApp.HTTPResponse} response The response object.
* @return {Object} The parsed token.
* @throws If the token cannot be parsed or the response contained an error.
* @private
*/
Service_.prototype.getTokenFromResponse_ = function(response) {
var token = this.parseToken_(response.getContentText());
var resCode = response.getResponseCode();
if ( resCode < 200 || resCode >= 300 || token.error) {
var reason = [
token.error,
token.message,
token.error_description,
token.error_uri
].filter(Boolean).map(function(part) {
return typeof(part) == 'string' ? part : JSON.stringify(part);
}).join(', ');
if (!reason) {
reason = resCode + ': ' + JSON.stringify(token);
}
throw new Error('Error retrieving token: ' + reason);
}
return token;
};
/**
* Parses the token using the service's token format.
* @param {string} content The serialized token content.
* @return {Object} The parsed token.
* @private
*/
Service_.prototype.parseToken_ = function(content) {
var token;
if (this.tokenFormat_ == TOKEN_FORMAT.JSON) {
try {
token = JSON.parse(content);
} catch (e) {
throw new Error('Token response not valid JSON: ' + e);
}
} else if (this.tokenFormat_ == TOKEN_FORMAT.FORM_URL_ENCODED) {
token = content.split('&').reduce(function(result, pair) {
var parts = pair.split('=');
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
return result;
}, {});
} else {
throw new Error('Unknown token format: ' + this.tokenFormat_);
}
token.granted_time = getTimeInSeconds_(new Date());
return token;
};
/**
* Refreshes a token that has expired. This is only possible if offline access
* was requested when the token was authorized.
*/
Service_.prototype.refresh = function() {
validate_({
'Client ID': this.clientId_,
'Client Secret': this.clientSecret_,
'Token URL': this.tokenUrl_
});
this.lockable_(function() {
var token = this.getToken();
if (!token.refresh_token) {
throw new Error('Offline access is required.');
}
var headers = {
Accept: this.tokenFormat_
};
if (this.tokenHeaders_) {
headers = extend_(headers, this.tokenHeaders_);
}
var tokenPayload = {
refresh_token: token.refresh_token,
client_id: this.clientId_,
client_secret: this.clientSecret_,
grant_type: 'refresh_token'
};
if (this.tokenPayloadHandler_) {
tokenPayload = this.tokenPayloadHandler_(tokenPayload);
}
// Use the refresh URL if specified, otherwise fallback to the token URL.
var url = this.refreshUrl_ || this.tokenUrl_;
var response = UrlFetchApp.fetch(url, {
method: 'post',
headers: headers,
payload: tokenPayload,
muteHttpExceptions: true
});
var newToken = this.getTokenFromResponse_(response);
if (!newToken.refresh_token) {
newToken.refresh_token = token.refresh_token;
}
this.saveToken_(newToken);
});
};
/**
* Gets the storage layer for this service, used to persist tokens.
* Custom values associated with the service can be stored here as well.
* The key <code>null</code> is used to to store the token and should not
* be used.
* @return {Storage} The service's storage.
*/
Service_.prototype.getStorage = function() {
validate_({
'Property store': this.propertyStore_
});
if (!this.storage_) {
var prefix = 'oauth2.' + this.serviceName_;
this.storage_ = new Storage_(prefix, this.propertyStore_, this.cache_);
}
return this.storage_;
};
/**
* Saves a token to the service's property store and cache.
* @param {Object} token The token to save.
* @private
*/
Service_.prototype.saveToken_ = function(token) {
this.getStorage().setValue(null, token);
};
/**
* Gets the token from the service's property store or cache.
* @return {Object} The token, or null if no token was found.
*/
Service_.prototype.getToken = function() {
return this.getStorage().getValue(null);
};
/**
* Determines if a retrieved token is still valid.
* @param {Object} token The token to validate.
* @return {boolean} True if it has expired, false otherwise.
* @private
*/
Service_.prototype.isExpired_ = function(token) {
var expiresIn = token.expires_in || token.expires;
if (!expiresIn) {
return false;
} else {
var expiresTime = token.granted_time + Number(expiresIn);
var now = getTimeInSeconds_(new Date());
return expiresTime - now < Service_.EXPIRATION_BUFFER_SECONDS_;
}
};
/**
* Uses the service account flow to exchange a signed JSON Web Token (JWT) for
* an access token.
* @private
*/
Service_.prototype.exchangeJwt_ = function() {
validate_({
'Token URL': this.tokenUrl_
});
var jwt = this.createJwt_();
var headers = {
'Accept': this.tokenFormat_
};
if (this.tokenHeaders_) {
headers = extend_(headers, this.tokenHeaders_);
}
var response = UrlFetchApp.fetch(this.tokenUrl_, {
method: 'post',
headers: headers,
payload: {
assertion: jwt,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer'
},
muteHttpExceptions: true
});
var token = this.getTokenFromResponse_(response);
this.saveToken_(token);
};
/**
* Creates a signed JSON Web Token (JWT) for use with Service Account
* authorization.
* @return {string} The signed JWT.
* @private
*/
Service_.prototype.createJwt_ = function() {
validate_({
'Private key': this.privateKey_,
'Token URL': this.tokenUrl_,
'Issuer or Client ID': this.issuer_ || this.clientId_
});
var header = {
alg: 'RS256',
typ: 'JWT'
};
var now = new Date();
var expires = new Date(now.getTime());
expires.setMinutes(expires.getMinutes() + this.expirationMinutes_);
var claimSet = {
iss: this.issuer_ || this.clientId_,
aud: this.tokenUrl_,
exp: Math.round(expires.getTime() / 1000),
iat: Math.round(now.getTime() / 1000)
};
if (this.subject_) {
claimSet.sub = this.subject_;
}
if (this.params_.scope) {
claimSet.scope = this.params_.scope;
}
var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' +
Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
var signatureBytes =
Utilities.computeRsaSha256Signature(toSign, this.privateKey_);
var signature = Utilities.base64EncodeWebSafe(signatureBytes);
return toSign + '.' + signature;
};
/**
* Locks access to a block of code if a lock has been set on this service.
* @param {function} func The code to execute.
* @return {*} The result of the code block.
* @private
*/
Service_.prototype.lockable_ = function(func) {
var releaseLock = false;
if (this.lock_ && !this.lock_.hasLock()) {
this.lock_.waitLock(Service_.LOCK_EXPIRATION_MILLISECONDS_);
releaseLock = true;
}
var result = func.apply(this);
if (this.lock_ && releaseLock) {
this.lock_.releaseLock();
}
return result;
};
// Copyright 2017 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.
/**
* @file Contains classes used to persist data and access it.
*/
/**
* Creates a new Storage_ instance, which is used to persist OAuth tokens and
* related information.
* @param {string} prefix The prefix to use for keys in the properties and
* cache.
* @param {PropertiesService.Properties} properties The properties instance to
* use.
* @param {CacheService.Cache} [optCache] The optional cache instance to use.
* @constructor
*/
function Storage_(prefix, properties, optCache) {
this.prefix_ = prefix;
this.properties_ = properties;
this.cache_ = optCache;
this.memory_ = {};
}
/**
* The TTL for cache entries, in seconds.
* @type {number}
* @private
*/
Storage_.CACHE_EXPIRATION_TIME_SECONDS = 21600; // 6 hours.
/**
* Gets a stored value.
* @param {string} key The key.
* @return {*} The stored value.
*/
Storage_.prototype.getValue = function(key) {
// Check memory.
if (this.memory_[key]) {
return this.memory_[key];
}
var prefixedKey = this.getPrefixedKey_(key);
var jsonValue;
var value;
// Check cache.
if (this.cache_ && (jsonValue = this.cache_.get(prefixedKey))) {
value = JSON.parse(jsonValue);
this.memory_[key] = value;
return value;
}
// Check properties.
if (jsonValue = this.properties_.getProperty(prefixedKey)) {
if (this.cache_) {
this.cache_.put(prefixedKey,
jsonValue, Storage_.CACHE_EXPIRATION_TIME_SECONDS);
}
value = JSON.parse(jsonValue);
this.memory_[key] = value;
return value;
}
// Not found.
return null;
};
/**
* Stores a value.
* @param {string} key The key.
* @param {*} value The value.
*/
Storage_.prototype.setValue = function(key, value) {
var prefixedKey = this.getPrefixedKey_(key);
var jsonValue = JSON.stringify(value);
this.properties_.setProperty(prefixedKey, jsonValue);
if (this.cache_) {
this.cache_.put(prefixedKey, jsonValue,
Storage_.CACHE_EXPIRATION_TIME_SECONDS);
}
this.memory_[key] = value;
};
/**
* Removes a stored value.
* @param {string} key The key.
*/
Storage_.prototype.removeValue = function(key) {
var prefixedKey = this.getPrefixedKey_(key);
this.properties_.deleteProperty(prefixedKey);
if (this.cache_) {
this.cache_.remove(prefixedKey);
}
delete this.memory_[key];
};
/**
* Gets a key with the prefix applied.
* @param {string} key The key.
* @return {string} The key with the prefix applied.
* @private
*/
Storage_.prototype.getPrefixedKey_ = function(key) {
if (key) {
return this.prefix_ + '.' + key;
} else {
return this.prefix_;
}
};
// 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.
/**
* @file Contains utility methods used by the library.
*/
/* exported buildUrl_ */
/**
* Builds a complete URL from a base URL and a map of URL parameters.
* @param {string} url The base URL.
* @param {Object.<string, string>} params The URL parameters and values.
* @return {string} The complete URL.
* @private
*/
function buildUrl_(url, params) {
var paramString = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
return url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString;
}
/* exported validate_ */
/**
* Validates that all of the values in the object are non-empty. If an empty
* value is found, and error is thrown using the key as the name.
* @param {Object.<string, string>} params The values to validate.
* @private
*/
function validate_(params) {
Object.keys(params).forEach(function(name) {
var value = params[name];
if (!value) {
throw Utilities.formatString('%s is required.', name);
}
});
}
/* exported getTimeInSeconds_ */
/**
* Gets the time in seconds, rounded down to the nearest second.
* @param {Date} date The Date object to convert.
* @return {Number} The number of seconds since the epoch.
* @private
*/
function getTimeInSeconds_(date) {
return Math.floor(date.getTime() / 1000);
}
/* exported extend_ */
/**
* Copy all of the properties in the source objects over to the
* destination object, and return the destination object.
* @param {Object} destination The combined object.
* @param {Object} source The object who's properties are copied to the
* destination.
* @return {Object} A combined object with the desination and source
* properties.
* @see http://underscorejs.org/#extend
*/
function extend_(destination, source) {
var keys = Object.keys(source);
for (var i = 0; i < keys.length; ++i) {
destination[keys[i]] = source[keys[i]];
}
return destination;
}
/****** code end *********/
;(
function copy(src, target, obj) {
obj[target] = obj[target] || {};
if (src && typeof src === 'object') {
for (var k in src) {
if (src.hasOwnProperty(k)) {
obj[target][k] = src[k];
}
}
} else {
obj[target] = src;
}
}
).call(null, module.exports, expose, host);
}).call(this, this, "OAuth2");