-
Notifications
You must be signed in to change notification settings - Fork 2k
/
token.js
57 lines (48 loc) · 1.6 KB
/
token.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
import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { assign } from '@ember/polyfills';
import queryString from 'query-string';
import fetch from 'nomad-ui/utils/fetch';
export default Service.extend({
system: service(),
secret: computed({
get() {
return window.localStorage.nomadTokenSecret;
},
set(key, value) {
if (value == null) {
window.localStorage.removeItem('nomadTokenSecret');
} else {
window.localStorage.nomadTokenSecret = value;
}
return value;
},
}),
// All non Ember Data requests should go through authorizedRequest.
// However, the request that gets regions falls into that category.
// This authorizedRawRequest is necessary in order to fetch data
// with the guarantee of a token but without the automatic region
// param since the region cannot be known at this point.
authorizedRawRequest(url, options = { credentials: 'include' }) {
const headers = {};
const token = this.secret;
if (token) {
headers['X-Nomad-Token'] = token;
}
return fetch(url, assign(options, { headers }));
},
authorizedRequest(url, options) {
if (this.get('system.shouldIncludeRegion')) {
const region = this.get('system.activeRegion');
if (region) {
url = addParams(url, { region });
}
}
return this.authorizedRawRequest(url, options);
},
});
function addParams(url, params) {
const paramsStr = queryString.stringify(params);
const delimiter = url.includes('?') ? '&' : '?';
return `${url}${delimiter}${paramsStr}`;
}