2019-05-14 22:47:04 +01:00
|
|
|
import history from '../history';
|
|
|
|
|
|
|
|
export const ACCESS_TOKEN = 'access_token';
|
|
|
|
export const LOGIN_PATHNAME = 'loginPathname';
|
|
|
|
export const LOGIN_SEARCH = 'loginSearch';
|
|
|
|
|
|
|
|
export function storeLoginRedirect(location) {
|
|
|
|
if (location) {
|
|
|
|
localStorage.setItem(LOGIN_PATHNAME, location.pathname);
|
|
|
|
localStorage.setItem(LOGIN_SEARCH, location.search);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function clearLoginRedirect() {
|
|
|
|
localStorage.removeItem(LOGIN_PATHNAME);
|
|
|
|
localStorage.removeItem(LOGIN_SEARCH);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function fetchLoginRedirect() {
|
|
|
|
const loginPathname = localStorage.getItem(LOGIN_PATHNAME);
|
|
|
|
const loginSearch = localStorage.getItem(LOGIN_SEARCH);
|
|
|
|
clearLoginRedirect();
|
|
|
|
return {
|
2019-05-19 21:22:01 +01:00
|
|
|
pathname: loginPathname || "/wifi-configuration",
|
2019-05-14 22:47:04 +01:00
|
|
|
search: (loginPathname && loginSearch) || undefined
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wraps the normal fetch routene with one with provides the access token if present.
|
|
|
|
*/
|
2019-05-19 17:51:57 +01:00
|
|
|
export function authorizedFetch(url, params) {
|
|
|
|
const accessToken = localStorage.getItem(ACCESS_TOKEN);
|
|
|
|
if (accessToken) {
|
2019-05-14 22:47:04 +01:00
|
|
|
params = params || {};
|
2019-05-19 17:51:57 +01:00
|
|
|
params.credentials = 'include';
|
|
|
|
params.headers = params.headers || {};
|
|
|
|
params.headers.Authorization = 'Bearer ' + accessToken;
|
2019-05-14 22:47:04 +01:00
|
|
|
}
|
|
|
|
return fetch(url, params);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wraps the normal fetch routene which redirects on 401 response.
|
|
|
|
*/
|
2019-05-19 17:51:57 +01:00
|
|
|
export function redirectingAuthorizedFetch(url, params) {
|
2019-05-14 22:47:04 +01:00
|
|
|
return new Promise(function (resolve, reject) {
|
2019-05-19 17:51:57 +01:00
|
|
|
authorizedFetch(url, params).then(response => {
|
2019-05-14 22:47:04 +01:00
|
|
|
if (response.status === 401) {
|
|
|
|
history.go("/");
|
|
|
|
} else {
|
|
|
|
resolve(response);
|
|
|
|
}
|
|
|
|
}).catch(error => {
|
|
|
|
reject(error);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|