-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathauth-ajax.html
82 lines (71 loc) · 2.69 KB
/
auth-ajax.html
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-ajax/iron-ajax.html">
<link rel="import" href="../iron-ajax/iron-request.html">
<link rel="import" href="../misbehave/misbehave.html">
<link rel="import" href="auth-store.html">
<!--
The `auth-ajax` element exposes network request functionality using the same API as
`<iron-ajax>` but adds access token and token refresh handling through interaction with
the `auth-store` (via `Polymer.AuthTokenStoreBehavior`).
@demo demo/index.html
-->
<script>
(function() {
'use strict';
/**
* converts iron-ajax into a behavior so we don't have to re-implement everything
*
* @polymerBehavior Polymer.AuthAjaxBehavior
*/
Polymer.AuthAjaxBehavior = {}; // to stop polymer analyzer getting upset
Polymer.AuthAjaxBehavior = document.createElement('iron-ajax').toBehavior();
// monkey patch the iron-request send method so we can hook into it
var ironRequest = Polymer.Base.getNativePrototype('iron-request');
var sendOriginal = ironRequest.send;
ironRequest.send = function(requestOptions) {
if (requestOptions._authHandler) {
// if it's an auth-ajax request, we handle it
requestOptions._authHandler(this, requestOptions);
} else {
// otherwise just handle as normal
sendOriginal.call(this, requestOptions);
}
};
Polymer({
is: 'auth-ajax',
behaviors: [
Polymer.AuthAjaxBehavior,
Polymer.AuthTokenStoreBehavior
],
properties: {
/** Whether an auth token is required to even attempt the request */
authRequired: {
type: Boolean,
value: false
}
},
// override the iron-ajax method to create options
// and add our authHandler function call to them
toRequestOptions: function() {
var requestOptions = Polymer.AuthAjaxBehavior.toRequestOptions.call(this);
requestOptions._authHandler = this._authHandler.bind(this);
return requestOptions;
},
// this is the hook that allows us to wait on our auth
// token promise (which may be a token refresh request)
// before we actually send our API call off
_authHandler: function(request, requestOptions) {
this.getAuthToken().then(function(accessToken) {
requestOptions.headers.Authorization = 'Bearer ' + accessToken;
sendOriginal.call(request, requestOptions);
}.bind(this), function(reason) {
if (this.authRequired) {
handleError(request, new Error(reason));
} else {
sendOriginal.call(request, requestOptions);
}
}.bind(this));
}
});
})();
</script>