-
Notifications
You must be signed in to change notification settings - Fork 8
/
oauth2_api_impl.js
219 lines (203 loc) · 7.51 KB
/
oauth2_api_impl.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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* OAuth2 API flow implementations.
*/
'use strict';
/** @suppress {duplicate} */
var remoting = remoting || {};
/**
* @constructor
* @implements {remoting.OAuth2Api}
*/
remoting.OAuth2ApiImpl = function() {
};
/** @private
* @return {string} OAuth2 token URL.
*/
remoting.OAuth2ApiImpl.prototype.getOAuth2TokenEndpoint_ = function() {
return remoting.settings.OAUTH2_BASE_URL + '/token';
};
/** @private
* @return {string} OAuth2 userinfo API URL.
*/
remoting.OAuth2ApiImpl.prototype.getOAuth2ApiUserInfoEndpoint_ = function() {
return remoting.settings.OAUTH2_API_BASE_URL + '/v1/userinfo';
};
/**
* Interprets HTTP error responses in authentication XMLHttpRequests.
*
* @private
* @param {number} xhrStatus Status (HTTP response code) of the XMLHttpRequest.
* @return {remoting.Error} An error code to be raised.
*/
remoting.OAuth2ApiImpl.prototype.interpretXhrStatus_ =
function(xhrStatus) {
// Return AUTHENTICATION_FAILED by default, so that the user can try to
// recover from an unexpected failure by signing in again.
/** @type {remoting.Error} */
var error = remoting.Error.AUTHENTICATION_FAILED;
if (xhrStatus == 400 || xhrStatus == 401 || xhrStatus == 403) {
error = remoting.Error.AUTHENTICATION_FAILED;
} else if (xhrStatus == 502 || xhrStatus == 503) {
error = remoting.Error.SERVICE_UNAVAILABLE;
} else if (xhrStatus == 0) {
error = remoting.Error.NETWORK_FAILURE;
} else {
console.warn('Unexpected authentication response code: ' + xhrStatus);
}
return error;
};
/**
* Asynchronously retrieves a new access token from the server.
*
* @param {function(string, number): void} onDone Callback to invoke when
* the access token and expiration time are successfully fetched.
* @param {function(remoting.Error):void} onError Callback invoked if an
* error occurs.
* @param {string} clientId OAuth2 client ID.
* @param {string} clientSecret OAuth2 client secret.
* @param {string} refreshToken OAuth2 refresh token to be redeemed.
* @return {void} Nothing.
*/
remoting.OAuth2ApiImpl.prototype.refreshAccessToken = function(
onDone, onError, clientId, clientSecret, refreshToken) {
/** @param {XMLHttpRequest} xhr */
var onResponse = function(xhr) {
if (xhr.status == 200) {
try {
// Don't use base.jsonParseSafe here unless you also include base.js,
// otherwise this won't work from the OAuth trampoline.
// TODO(jamiewalch): Fix this once we're no longer using the trampoline.
var tokens = JSON.parse(xhr.responseText);
onDone(tokens['access_token'], tokens['expires_in']);
} catch (/** @type {Error} */ err) {
console.error('Invalid "token" response from server:', err);
onError(remoting.Error.UNEXPECTED);
}
} else {
console.error('Failed to refresh token. Status: ' + xhr.status +
' response: ' + xhr.responseText);
onError(remoting.Error.fromHttpStatus(xhr.status));
}
};
var parameters = {
'client_id': clientId,
'client_secret': clientSecret,
'refresh_token': refreshToken,
'grant_type': 'refresh_token'
};
remoting.xhr.post(this.getOAuth2TokenEndpoint_(), onResponse, parameters);
};
/**
* Asynchronously exchanges an authorization code for access and refresh tokens.
*
* @param {function(string, string, number): void} onDone Callback to
* invoke when the refresh token, access token and access token expiration
* time are successfully fetched.
* @param {function(remoting.Error):void} onError Callback invoked if an
* error occurs.
* @param {string} clientId OAuth2 client ID.
* @param {string} clientSecret OAuth2 client secret.
* @param {string} code OAuth2 authorization code.
* @param {string} redirectUri Redirect URI used to obtain this code.
* @return {void} Nothing.
*/
remoting.OAuth2ApiImpl.prototype.exchangeCodeForTokens = function(
onDone, onError, clientId, clientSecret, code, redirectUri) {
/** @param {XMLHttpRequest} xhr */
var onResponse = function(xhr) {
if (xhr.status == 200) {
try {
// Don't use base.jsonParseSafe here unless you also include base.js,
// otherwise this won't work from the OAuth trampoline.
// TODO(jamiewalch): Fix this once we're no longer using the trampoline.
var tokens = JSON.parse(xhr.responseText);
onDone(tokens['refresh_token'],
tokens['access_token'], tokens['expires_in']);
} catch (/** @type {Error} */ err) {
console.error('Invalid "token" response from server:', err);
onError(remoting.Error.UNEXPECTED);
}
} else {
console.error('Failed to exchange code for token. Status: ' + xhr.status +
' response: ' + xhr.responseText);
onError(remoting.Error.fromHttpStatus(xhr.status));
}
};
var parameters = {
'client_id': clientId,
'client_secret': clientSecret,
'redirect_uri': redirectUri,
'code': code,
'grant_type': 'authorization_code'
};
remoting.xhr.post(this.getOAuth2TokenEndpoint_(), onResponse, parameters);
};
/**
* Get the user's email address.
*
* @param {function(string):void} onDone Callback invoked when the email
* address is available.
* @param {function(remoting.Error):void} onError Callback invoked if an
* error occurs.
* @param {string} token Access token.
* @return {void} Nothing.
*/
remoting.OAuth2ApiImpl.prototype.getEmail = function(onDone, onError, token) {
/** @param {XMLHttpRequest} xhr */
var onResponse = function(xhr) {
if (xhr.status == 200) {
try {
var result = JSON.parse(xhr.responseText);
onDone(result['email']);
} catch (/** @type {Error} */ err) {
console.error('Invalid "userinfo" response from server:', err);
onError(remoting.Error.UNEXPECTED);
}
} else {
console.error('Failed to get email. Status: ' + xhr.status +
' response: ' + xhr.responseText);
onError(remoting.Error.fromHttpStatus(xhr.status));
}
};
var headers = { 'Authorization': 'OAuth ' + token };
remoting.xhr.get(this.getOAuth2ApiUserInfoEndpoint_(),
onResponse, '', headers);
};
/**
* Get the user's email address and full name.
*
* @param {function(string, string):void} onDone Callback invoked when the email
* address and full name are available.
* @param {function(remoting.Error):void} onError Callback invoked if an
* error occurs.
* @param {string} token Access token.
* @return {void} Nothing.
*/
remoting.OAuth2ApiImpl.prototype.getUserInfo =
function(onDone, onError, token) {
/** @param {XMLHttpRequest} xhr */
var onResponse = function(xhr) {
if (xhr.status == 200) {
try {
var result = JSON.parse(xhr.responseText);
onDone(result['email'], result['name']);
} catch (/** @type {Error} */ err) {
console.error('Invalid "userinfo" response from server:', err);
onError(remoting.Error.UNEXPECTED);
}
} else {
console.error('Failed to get user info. Status: ' + xhr.status +
' response: ' + xhr.responseText);
onError(remoting.Error.fromHttpStatus(xhr.status));
}
};
var headers = { 'Authorization': 'OAuth ' + token };
remoting.xhr.get(this.getOAuth2ApiUserInfoEndpoint_(),
onResponse, '', headers);
};
/** @type {remoting.OAuth2Api} */
remoting.oauth2Api = new remoting.OAuth2ApiImpl();