2018-03-09 22:17:16 -07:00
|
|
|
import axios, { AxiosResponse } from "axios";
|
2017-10-05 11:12:08 -06:00
|
|
|
import { API } from "./api/index";
|
2017-10-05 11:39:00 -06:00
|
|
|
import { AuthState } from "./auth/interfaces";
|
2017-10-12 14:28:19 -06:00
|
|
|
import { setToken } from "./auth/actions";
|
2017-10-05 11:39:00 -06:00
|
|
|
|
2017-10-12 14:34:35 -06:00
|
|
|
/** What to do when the Token refresh request completes. */
|
2018-03-09 22:17:16 -07:00
|
|
|
const ok = (x: AxiosResponse<AuthState>) => {
|
2017-10-12 14:34:35 -06:00
|
|
|
setToken(x.data); // Start using new token in HTTP requests.
|
|
|
|
return x.data;
|
|
|
|
};
|
|
|
|
|
2017-10-12 14:28:19 -06:00
|
|
|
/** Grab a new token from the API (won't extend token's exp. date).
|
|
|
|
* Redirect to home page on failure. */
|
2019-12-10 12:53:20 -07:00
|
|
|
export const maybeRefreshToken
|
2017-10-13 14:42:29 -06:00
|
|
|
= (old: AuthState): Promise<AuthState | undefined> => {
|
|
|
|
API.setBaseUrl(old.token.unencoded.iss);
|
|
|
|
setToken(old); // Precaution: The Axios interceptors might not be set yet.
|
|
|
|
return axios
|
2018-03-09 22:17:16 -07:00
|
|
|
.get<AuthState>(API.current.tokensPath)
|
2017-10-13 14:42:29 -06:00
|
|
|
.then(ok, () => Promise.resolve(undefined));
|
|
|
|
};
|