forked from mainmatter/ember-simple-auth-component
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-auth-oauth2.js
More file actions
517 lines (451 loc) · 18.9 KB
/
Copy pathsimple-auth-oauth2.js
File metadata and controls
517 lines (451 loc) · 18.9 KB
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
(function(global) {
Ember.libraries.register('Ember Simple Auth OAuth 2.0', '0.6.7');
var define, requireModule;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requireModule = function(name) {
if (seen.hasOwnProperty(name)) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
requireModule.registry = registry;
})();
define("simple-auth-oauth2/authenticators/oauth2",
["simple-auth/authenticators/base","simple-auth/utils/is-secure-url","./../configuration","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Base = __dependency1__["default"];
var isSecureUrl = __dependency2__["default"];
var Configuration = __dependency3__["default"];
/**
Authenticator that conforms to OAuth 2
([RFC 6749](http://tools.ietf.org/html/rfc6749)), specifically the _"Resource
Owner Password Credentials Grant Type"_.
This authenticator supports access token refresh (see
[RFC 6740, section 6](http://tools.ietf.org/html/rfc6749#section-6)).
_The factory for this authenticator is registered as
`'simple-auth-authenticator:oauth2-password-grant'` in Ember's
container._
@class OAuth2
@namespace SimpleAuth.Authenticators
@module simple-auth-oauth2/authenticators/oauth2
@extends Base
*/
__exports__["default"] = Base.extend({
/**
Triggered when the authenticator refreshes the access token (see
[RFC 6740, section 6](http://tools.ietf.org/html/rfc6749#section-6)).
@event updated
@param {Object} data The updated session data
*/
/**
The endpoint on the server the authenticator acquires the access token
from.
This value can be configured via
[`SimpleAuth.Configuration.OAuth2#serverTokenEndpoint`](#SimpleAuth-Configuration-OAuth2-serverTokenEndpoint).
@property serverTokenEndpoint
@type String
@default '/token'
*/
serverTokenEndpoint: '/token',
/**
The endpoint on the server the authenticator uses to revoke tokens. Only
set this if the server actually supports token revokation.
This value can be configured via
[`SimpleAuth.Configuration.OAuth2#serverTokenRevocationEndpoint`](#SimpleAuth-Configuration-OAuth2-serverTokenRevocationEndpoint).
@property serverTokenRevocationEndpoint
@type String
@default null
*/
serverTokenRevocationEndpoint: null,
/**
Sets whether the authenticator automatically refreshes access tokens.
This value can be configured via
[`SimpleAuth.Configuration.OAuth2#refreshAccessTokens`](#SimpleAuth-Configuration-OAuth2-refreshAccessTokens).
@property refreshAccessTokens
@type Boolean
@default true
*/
refreshAccessTokens: true,
/**
@property _refreshTokenTimeout
@private
*/
_refreshTokenTimeout: null,
/**
@method init
@private
*/
init: function() {
this.serverTokenEndpoint = Configuration.serverTokenEndpoint;
this.serverTokenRevocationEndpoint = Configuration.serverTokenRevocationEndpoint;
this.refreshAccessTokens = Configuration.refreshAccessTokens;
},
/**
Restores the session from a set of session properties; __will return a
resolving promise when there's a non-empty `access_token` in the `data`__
and a rejecting promise otherwise.
This method also schedules automatic token refreshing when there are values
for `refresh_token` and `expires_in` in the `data` and automatic token
refreshing is not disabled (see
[`Authenticators.OAuth2#refreshAccessTokens`](#SimpleAuth-Authenticators-OAuth2-refreshAccessTokens)).
@method restore
@param {Object} data The data to restore the session from
@return {Ember.RSVP.Promise} A promise that when it resolves results in the session being authenticated
*/
restore: function(data) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var now = (new Date()).getTime();
if (!Ember.isEmpty(data.expires_at) && data.expires_at < now) {
if (_this.refreshAccessTokens) {
_this.refreshAccessToken(data.expires_in, data.refresh_token).then(function(data) {
resolve(data);
}, reject);
} else {
reject();
}
} else {
if (Ember.isEmpty(data.access_token)) {
reject();
} else {
_this.scheduleAccessTokenRefresh(data.expires_in, data.expires_at, data.refresh_token);
resolve(data);
}
}
});
},
/**
Authenticates the session with the specified `credentials`; the credentials
are send via a _"POST"_ request to the
[`Authenticators.OAuth2#serverTokenEndpoint`](#SimpleAuth-Authenticators-OAuth2-serverTokenEndpoint)
and if they are valid the server returns an access token in response (see
http://tools.ietf.org/html/rfc6749#section-4.3). __If the credentials are
valid and authentication succeeds, a promise that resolves with the
server's response is returned__, otherwise a promise that rejects with the
error is returned.
This method also schedules automatic token refreshing when there are values
for `refresh_token` and `expires_in` in the server response and automatic
token refreshing is not disabled (see
[`Authenticators.OAuth2#refreshAccessTokens`](#SimpleAuth-Authenticators-OAuth2-refreshAccessTokens)).
@method authenticate
@param {Object} credentials The credentials to authenticate the session with
@return {Ember.RSVP.Promise} A promise that resolves when an access token is successfully acquired from the server and rejects otherwise
*/
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = { grant_type: 'password', username: credentials.identification, password: credentials.password };
_this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
Ember.run(function() {
var expiresAt = _this.absolutizeExpirationTime(response.expires_in);
_this.scheduleAccessTokenRefresh(response.expires_in, expiresAt, response.refresh_token);
if (!Ember.isEmpty(expiresAt)) {
response = Ember.merge(response, { expires_at: expiresAt });
}
resolve(response);
});
}, function(xhr, status, error) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
/**
Cancels any outstanding automatic token refreshes and returns a resolving
promise.
@method invalidate
@param {Object} data The data of the session to be invalidated
@return {Ember.RSVP.Promise} A resolving promise
*/
invalidate: function(data) {
var _this = this;
function success(resolve) {
Ember.run.cancel(_this._refreshTokenTimeout);
delete _this._refreshTokenTimeout;
resolve();
}
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(_this.serverTokenRevocationEndpoint)) {
var requests = [];
Ember.A(['access_token', 'refresh_token']).forEach(function(tokenType) {
if (!Ember.isEmpty(data[tokenType])) {
requests.push(_this.makeRequest(_this.serverTokenRevocationEndpoint, {
token_type_hint: tokenType, token: data[tokenType]
}));
}
});
Ember.$.when.apply(Ember.$, requests).always(function(responses) {
success(resolve);
});
} else {
success(resolve);
}
});
},
/**
Sends an `AJAX` request to the `url`. This will always be a _"POST"_
request with content type _"application/x-www-form-urlencoded"_ as
specified in [RFC 6749](http://tools.ietf.org/html/rfc6749).
This method is not meant to be used directly but serves as an extension
point to e.g. add _"Client Credentials"_ (see
[RFC 6749, section 2.3](http://tools.ietf.org/html/rfc6749#section-2.3)).
@method makeRequest
@param {Object} url The url to send the request to
@param {Object} data The data to send with the request, e.g. username and password or the refresh token
@return {Deferred object} A Deferred object (see [the jQuery docs](http://api.jquery.com/category/deferred-object/)) that is compatible to Ember.RSVP.Promise; will resolve if the request succeeds, reject otherwise
@protected
*/
makeRequest: function(url, data) {
if (!isSecureUrl(url)) {
Ember.Logger.warn('Credentials are transmitted via an insecure connection - use HTTPS to keep them secure.');
}
return Ember.$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded'
});
},
/**
@method scheduleAccessTokenRefresh
@private
*/
scheduleAccessTokenRefresh: function(expiresIn, expiresAt, refreshToken) {
var _this = this;
if (this.refreshAccessTokens) {
var now = (new Date()).getTime();
if (Ember.isEmpty(expiresAt) && !Ember.isEmpty(expiresIn)) {
expiresAt = new Date(now + expiresIn * 1000).getTime();
}
var offset = (Math.floor(Math.random() * 5) + 5) * 1000;
if (!Ember.isEmpty(refreshToken) && !Ember.isEmpty(expiresAt) && expiresAt > now - offset) {
Ember.run.cancel(this._refreshTokenTimeout);
delete this._refreshTokenTimeout;
if (!Ember.testing) {
this._refreshTokenTimeout = Ember.run.later(this, this.refreshAccessToken, expiresIn, refreshToken, expiresAt - now - offset);
}
}
}
},
/**
@method refreshAccessToken
@private
*/
refreshAccessToken: function(expiresIn, refreshToken) {
var _this = this;
var data = { grant_type: 'refresh_token', refresh_token: refreshToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
_this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
Ember.run(function() {
expiresIn = response.expires_in || expiresIn;
refreshToken = response.refresh_token || refreshToken;
var expiresAt = _this.absolutizeExpirationTime(expiresIn);
var data = Ember.merge(response, { expires_in: expiresIn, expires_at: expiresAt, refresh_token: refreshToken });
_this.scheduleAccessTokenRefresh(expiresIn, null, refreshToken);
_this.trigger('sessionDataUpdated', data);
resolve(data);
});
}, function(xhr, status, error) {
Ember.Logger.warn('Access token could not be refreshed - server responded with ' + error + '.');
reject();
});
});
},
/**
@method absolutizeExpirationTime
@private
*/
absolutizeExpirationTime: function(expiresIn) {
if (!Ember.isEmpty(expiresIn)) {
return new Date((new Date().getTime()) + expiresIn * 1000).getTime();
}
}
});
});
define("simple-auth-oauth2/authorizers/oauth2",
["simple-auth/authorizers/base","simple-auth/utils/is-secure-url","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var Base = __dependency1__["default"];
var isSecureUrl = __dependency2__["default"];
/**
Authorizer that conforms to OAuth 2
([RFC 6749](http://tools.ietf.org/html/rfc6749)) by sending a bearer token
([RFC 6749](http://tools.ietf.org/html/rfc6750)) in the request's
`Authorization` header.
_The factory for this authorizer is registered as
`'simple-auth-authorizer:oauth2-bearer'` in Ember's container._
@class OAuth2
@namespace SimpleAuth.Authorizers
@module simple-auth-oauth2/authorizers/oauth2
@extends Base
*/
__exports__["default"] = Base.extend({
/**
Authorizes an XHR request by sending the `access_token` property from the
session as a bearer token in the `Authorization` header:
```
Authorization: Bearer <access_token>
```
@method authorize
@param {jqXHR} jqXHR The XHR request to authorize (see http://api.jquery.com/jQuery.ajax/#jqXHR)
@param {Object} requestOptions The options as provided to the `$.ajax` method (see http://api.jquery.com/jQuery.ajaxPrefilter/)
*/
authorize: function(jqXHR, requestOptions) {
var accessToken = this.get('session.access_token');
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
if (!isSecureUrl(requestOptions.url)) {
Ember.Logger.warn('Credentials are transmitted via an insecure connection - use HTTPS to keep them secure.');
}
jqXHR.setRequestHeader('Authorization', 'Bearer ' + accessToken);
}
}
});
});
define("simple-auth-oauth2/configuration",
["simple-auth/utils/load-config","exports"],
function(__dependency1__, __exports__) {
"use strict";
var loadConfig = __dependency1__["default"];
var defaults = {
serverTokenEndpoint: '/token',
serverTokenRevocationEndpoint: null,
refreshAccessTokens: true
};
/**
Ember Simple Auth OAuth2's configuration object.
To change any of these values, define a global environment object for Ember
Simple Auth and define the values there:
```js
window.ENV = window.ENV || {};
window.ENV['simple-auth-oauth2'] = {
serverTokenEndpoint: '/some/custom/endpoint'
}
```
@class OAuth2
@namespace SimpleAuth.Configuration
@module simple-auth/configuration
*/
__exports__["default"] = {
/**
The endpoint on the server the authenticator acquires the access token
from.
@property serverTokenEndpoint
@readOnly
@static
@type String
@default '/token'
*/
serverTokenEndpoint: defaults.serverTokenEndpoint,
/**
The endpoint on the server the authenticator uses to revoke tokens. Only
set this if the server actually supports token revokation.
@property serverTokenRevocationEndpoint
@readOnly
@static
@type String
@default null
*/
serverTokenRevocationEndpoint: defaults.serverTokenRevocationEndpoint,
/**
Sets whether the authenticator automatically refreshes access tokens.
@property refreshAccessTokens
@readOnly
@static
@type Boolean
@default true
*/
refreshAccessTokens: defaults.refreshAccessTokens,
/**
@method load
@private
*/
load: loadConfig(defaults)
};
});
define("simple-auth-oauth2/ember",
["./initializer"],
function(__dependency1__) {
"use strict";
var initializer = __dependency1__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer(initializer);
});
});
define("simple-auth-oauth2/initializer",
["./configuration","simple-auth/utils/get-global-config","simple-auth-oauth2/authenticators/oauth2","simple-auth-oauth2/authorizers/oauth2","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var Configuration = __dependency1__["default"];
var getGlobalConfig = __dependency2__["default"];
var Authenticator = __dependency3__["default"];
var Authorizer = __dependency4__["default"];
__exports__["default"] = {
name: 'simple-auth-oauth2',
before: 'simple-auth',
initialize: function(container, application) {
var config = getGlobalConfig('simple-auth-oauth2');
Configuration.load(container, config);
container.register('simple-auth-authorizer:oauth2-bearer', Authorizer);
container.register('simple-auth-authenticator:oauth2-password-grant', Authenticator);
}
};
});
define('simple-auth/authenticators/base', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Authenticators.Base;
});
define('simple-auth/authorizers/base', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Authorizers.Base;
});
define('simple-auth/utils/is-secure-url', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.isSecureUrl;
});
define('simple-auth/utils/get-global-config', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.getGlobalConfig;
});
define('simple-auth/utils/load-config', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.loadConfig;
});
var initializer = requireModule('simple-auth-oauth2/initializer')['default'];
var Configuration = requireModule('simple-auth-oauth2/configuration')['default'];
var Authenticator = requireModule('simple-auth-oauth2/authenticators/oauth2')['default'];
var Authorizer = requireModule('simple-auth-oauth2/authorizers/oauth2')['default'];
global.SimpleAuth.Configuration.OAuth2 = Configuration;
global.SimpleAuth.Authenticators.OAuth2 = Authenticator;
global.SimpleAuth.Authorizers.OAuth2 = Authorizer;
requireModule('simple-auth-oauth2/ember');
})((typeof global !== 'undefined') ? global : window);