Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 996c2e0

Browse files
committed
Initial version of Angular HTTP Auth Module
1 parent 9c3d2b9 commit 996c2e0

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

src/angular-http-auth.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* @license Angular HTTP Auth Module
3+
* (c) 2012 Witold Szczerba
4+
* License: MIT
5+
*/
6+
angular.module('angular-auth', [])
7+
8+
/**
9+
* Holds all the requests which failed due to 401 response,
10+
* so they can be re-requested in future, once login is completed.
11+
*/
12+
.service('requests401', function() {
13+
14+
var buffer = [];
15+
16+
/**
17+
* Required by HTTP interceptor.
18+
* Function is attached to provider to be invisible for regular users of this service.
19+
*/
20+
this.pushToBuffer = function(config, deferred) {
21+
buffer.push({
22+
config: config,
23+
deferred: deferred
24+
});
25+
}
26+
27+
this.$get = ['$injector', function($injector) {
28+
var $http; //initialized later because of circular dependency problem
29+
function retry(config, deferred) {
30+
$http = $http || $injector.get('$http');
31+
$http(config).then(function(response) {
32+
deferred.resolve(response);
33+
});
34+
}
35+
36+
return {
37+
retryAll: function() {
38+
for (var i = 0; i < buffer.length; ++i) {
39+
retry(buffer[i].config, buffer[i].deferred);
40+
}
41+
buffer = [];
42+
}
43+
}
44+
}]
45+
})
46+
47+
/**
48+
* $http interceptor.
49+
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
50+
*/
51+
.config(function($httpProvider, requests401Provider) {
52+
53+
var interceptor = function($rootScope, $q) {
54+
function success(response) {
55+
return response;
56+
}
57+
58+
function error(response) {
59+
if (response.status === 401) {
60+
var deferred = $q.defer();
61+
requests401Provider.pushToBuffer(response.config, deferred);
62+
$rootScope.$broadcast('event:angular-auth-loginRequired');
63+
return deferred.promise;
64+
}
65+
// otherwise
66+
return $q.reject(response);
67+
}
68+
69+
return function(promise) {
70+
return promise.then(success, error);
71+
}
72+
73+
};
74+
$httpProvider.responseInterceptors.push(interceptor);
75+
});

0 commit comments

Comments
 (0)