This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 182
/
interceptor.js
85 lines (74 loc) · 2.65 KB
/
interceptor.js
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
angular.module('angular-jwt.interceptor', [])
.provider('jwtInterceptor', function() {
this.urlParam;
this.authHeader;
this.authPrefix;
this.whiteListedDomains;
this.tokenGetter;
var config = this;
this.$get = function($q, $injector, $rootScope, urlUtils, jwtOptions) {
var options = angular.extend({}, jwtOptions.getConfig(), config);
function isSafe (url) {
if (!urlUtils.isSameOrigin(url) && !options.whiteListedDomains.length) {
throw new Error('As of v0.1.0, requests to domains other than the application\'s origin must be white listed. Use jwtOptionsProvider.config({ whiteListedDomains: [<domain>] }); to whitelist.')
}
var hostname = urlUtils.urlResolve(url).hostname.toLowerCase();
for (var i = 0; i < options.whiteListedDomains.length; i++) {
var domain = options.whiteListedDomains[i];
if (domain instanceof RegExp) {
if (hostname.match(domain)) {
return true;
}
} else {
if (hostname === domain.toLowerCase()) {
return true;
}
}
}
if (urlUtils.isSameOrigin(url)) {
return true;
}
return false;
}
return {
request: function (request) {
if (request.skipAuthorization || !isSafe(request.url)) {
return request;
}
if (options.urlParam) {
request.params = request.params || {};
// Already has the token in the url itself
if (request.params[options.urlParam]) {
return request;
}
} else {
request.headers = request.headers || {};
// Already has an Authorization header
if (request.headers[options.authHeader]) {
return request;
}
}
var tokenPromise = $q.when($injector.invoke(options.tokenGetter, this, {
options: request
}));
return tokenPromise.then(function(token) {
if (token) {
if (options.urlParam) {
request.params[options.urlParam] = token;
} else {
request.headers[options.authHeader] = options.authPrefix + token;
}
}
return request;
});
},
responseError: function (response) {
// handle the case where the user is not authenticated
if (response !== undefined && response.status === 401) {
$rootScope.$broadcast('unauthenticated', response);
}
return $q.reject(response);
}
};
}
});