Last change
on this file since 474 was
468,
checked in by hendrikvanantwerpen, 12 years ago
|
Improved authentication
- Authentication cannot be cancelled, removing a lot of weird race
conditions.
- We offer a request provider that has automatic retry in case of
authentication failures.
- Reduced dependency on LoginDialog? by having it act independent
based on events. Other modules can just depend on 'session'.
|
File size:
1.7 KB
|
Rev | Line | |
---|
[463] | 1 | define([ |
---|
[468] | 2 | "./session", |
---|
[463] | 3 | "dojo/Deferred", |
---|
[468] | 4 | "dojo/on", |
---|
[463] | 5 | "dojo/request" |
---|
[468] | 6 | ], function(session, Deferred, on, request) { |
---|
[463] | 7 | |
---|
[468] | 8 | var user = session.get(); |
---|
[463] | 9 | var queue = []; |
---|
| 10 | |
---|
[468] | 11 | on(session, 'change', function(newUser) { |
---|
| 12 | user = newUser; |
---|
| 13 | if ( user ) { |
---|
| 14 | retry(); |
---|
| 15 | } |
---|
| 16 | }); |
---|
| 17 | |
---|
| 18 | function retry() { |
---|
| 19 | if (queue.length > 0) { |
---|
| 20 | var item = queue.shift(); |
---|
| 21 | console.log("Retry",item.url); |
---|
| 22 | real_request(item); |
---|
| 23 | } |
---|
| 24 | } |
---|
| 25 | |
---|
| 26 | function real_request(item) { |
---|
| 27 | var req = request(item.url,item.options); |
---|
| 28 | |
---|
| 29 | // forward successfull response |
---|
| 30 | req.then(function(body){ |
---|
| 31 | item.dfd.resolve(body); |
---|
| 32 | }); |
---|
| 33 | |
---|
| 34 | // handle unauthenticated and queued requests |
---|
| 35 | req.response.then(function(response){ |
---|
| 36 | retry(); |
---|
| 37 | }, function(error) { |
---|
| 38 | if ( error.response.status === 401 ) { |
---|
| 39 | queue.unshift(item); |
---|
| 40 | session.restore(); |
---|
| 41 | } else { |
---|
| 42 | item.dfd.reject(error); // this should be error body |
---|
| 43 | // not, the request? |
---|
| 44 | retry(); |
---|
| 45 | } |
---|
| 46 | }); |
---|
| 47 | } |
---|
| 48 | |
---|
[463] | 49 | var _request = function(url, options) { |
---|
[468] | 50 | var item = { |
---|
| 51 | url: url, |
---|
| 52 | options: options, |
---|
| 53 | dfd: new Deferred() |
---|
| 54 | }; |
---|
| 55 | // only do the request directly if we are authenticated and |
---|
| 56 | // there are no earlier requests queued. |
---|
| 57 | if ( user && queue.length === 0 ) { |
---|
| 58 | console.log("Request",url); |
---|
| 59 | real_request(item); |
---|
[463] | 60 | } else { |
---|
[468] | 61 | console.log("Push",url); |
---|
| 62 | queue.push(item); |
---|
[463] | 63 | } |
---|
[468] | 64 | return item.dfd.promise; |
---|
[463] | 65 | }; |
---|
[468] | 66 | |
---|
[463] | 67 | return _request; |
---|
| 68 | }); |
---|
Note: See
TracBrowser
for help on using the repository browser.