59 lines
1.6 KiB
JavaScript
Raw Normal View History

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-26 20:49:15 +01:00
pathname: loginPathname || "/wifi/",
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.
*/
export function authorizedFetch(url, params) {
const accessToken = localStorage.getItem(ACCESS_TOKEN);
if (accessToken) {
2019-05-14 22:47:04 +01:00
params = params || {};
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.
*/
export function redirectingAuthorizedFetch(url, params) {
2019-05-14 22:47:04 +01:00
return new Promise(function (resolve, reject) {
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);
});
});
}