Last change
on this file since 468 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
|
Line | |
---|
1 | define([ |
---|
2 | "./session", |
---|
3 | "dojo/Deferred", |
---|
4 | "dojo/on", |
---|
5 | "dojo/request" |
---|
6 | ], function(session, Deferred, on, request) { |
---|
7 | |
---|
8 | var user = session.get(); |
---|
9 | var queue = []; |
---|
10 | |
---|
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 | |
---|
49 | var _request = function(url, options) { |
---|
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); |
---|
60 | } else { |
---|
61 | console.log("Push",url); |
---|
62 | queue.push(item); |
---|
63 | } |
---|
64 | return item.dfd.promise; |
---|
65 | }; |
---|
66 | |
---|
67 | return _request; |
---|
68 | }); |
---|
Note: See
TracBrowser
for help on using the repository browser.