Farmbot-Web-App/frontend/refresh_token.ts

22 lines
802 B
TypeScript
Raw Normal View History

2018-03-09 22:17:16 -07:00
import axios, { AxiosResponse } from "axios";
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
/** What to do when the Token refresh request completes. */
2018-03-09 22:17:16 -07:00
const ok = (x: AxiosResponse<AuthState>) => {
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. */
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));
};