github.com/zoomfoo/nomad@v0.8.5-0.20180907175415-f28fd3a1a056/ui/app/services/token.js (about) 1 import Service, { inject as service } from '@ember/service'; 2 import { computed } from '@ember/object'; 3 import { assign } from '@ember/polyfills'; 4 import queryString from 'query-string'; 5 import fetch from 'nomad-ui/utils/fetch'; 6 7 export default Service.extend({ 8 system: service(), 9 10 secret: computed({ 11 get() { 12 return window.localStorage.nomadTokenSecret; 13 }, 14 set(key, value) { 15 if (value == null) { 16 window.localStorage.removeItem('nomadTokenSecret'); 17 } else { 18 window.localStorage.nomadTokenSecret = value; 19 } 20 21 return value; 22 }, 23 }), 24 25 // All non Ember Data requests should go through authorizedRequest. 26 // However, the request that gets regions falls into that category. 27 // This authorizedRawRequest is necessary in order to fetch data 28 // with the guarantee of a token but without the automatic region 29 // param since the region cannot be known at this point. 30 authorizedRawRequest(url, options = { credentials: 'include' }) { 31 const headers = {}; 32 const token = this.get('secret'); 33 34 if (token) { 35 headers['X-Nomad-Token'] = token; 36 } 37 38 return fetch(url, assign(options, { headers })); 39 }, 40 41 authorizedRequest(url, options) { 42 if (this.get('system.shouldIncludeRegion')) { 43 const region = this.get('system.activeRegion'); 44 if (region) { 45 url = addParams(url, { region }); 46 } 47 } 48 49 return this.authorizedRawRequest(url, options); 50 }, 51 }); 52 53 function addParams(url, params) { 54 const paramsStr = queryString.stringify(params); 55 const delimiter = url.includes('?') ? '&' : '?'; 56 return `${url}${delimiter}${paramsStr}`; 57 }