Skip to content

Commit 3e1288a

Browse files
author
Eric Koleda
committed
Add the ability to set additional HTTP request headers to be sent when retrieving / refreshing the access token. Required by the Fitbit API's OAuth2 implementation.
1 parent 19b06af commit 3e1288a

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

Service.gs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ var Service_ = function(serviceName) {
2828
this.serviceName_ = serviceName;
2929
this.params_ = {};
3030
this.tokenFormat_ = TOKEN_FORMAT.JSON;
31+
this.tokenHeaders_ = null;
3132
};
3233

3334
/**
@@ -69,6 +70,17 @@ Service_.prototype.setTokenFormat = function(tokenFormat) {
6970
return this;
7071
};
7172

73+
/**
74+
* Sets the additional HTTP headers that should be sent when retrieving or
75+
* refreshing the access token.
76+
* @param Object.<string,string> tokenHeaders A map of header names to values.
77+
* @return {Service_} This service, for chaining.
78+
*/
79+
Service_.prototype.setTokenHeaders = function(tokenHeaders) {
80+
this.tokenHeaders_ = tokenHeaders;
81+
return this;
82+
};
83+
7284
/**
7385
* Sets the project key of the script that contains the authorization callback function (required).
7486
* The project key can be found in the Script Editor UI under "File > Project properties".
@@ -224,11 +236,15 @@ Service_.prototype.handleCallback = function(callbackRequest) {
224236
'Token URL': this.tokenUrl_
225237
});
226238
var redirectUri = getRedirectUri(this.projectKey_);
239+
var headers = {
240+
'Accept': this.tokenFormat_
241+
};
242+
if (this.tokenHeaders_) {
243+
headers = _.extend(headers, this.tokenHeaders_);
244+
}
227245
var response = UrlFetchApp.fetch(this.tokenUrl_, {
228246
method: 'post',
229-
headers: {
230-
'Accept': this.tokenFormat_
231-
},
247+
headers: headers,
232248
payload: {
233249
code: code,
234250
client_id: this.clientId_,
@@ -338,11 +354,15 @@ Service_.prototype.refresh = function() {
338354
if (!token.refresh_token) {
339355
throw 'Offline access is required.';
340356
}
357+
var headers = {
358+
'Accept': this.tokenFormat_
359+
};
360+
if (this.tokenHeaders_) {
361+
headers = _.extend(headers, this.tokenHeaders_);
362+
}
341363
var response = UrlFetchApp.fetch(this.tokenUrl_, {
342364
method: 'post',
343-
headers: {
344-
'Accept': this.tokenFormat_
345-
},
365+
headers: headers,
346366
payload: {
347367
refresh_token: token.refresh_token,
348368
client_id: this.clientId_,

0 commit comments

Comments
 (0)