forked from Greenstand/treetracker-admin-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpClient.js
More file actions
50 lines (43 loc) · 1.14 KB
/
httpClient.js
File metadata and controls
50 lines (43 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import axios from 'axios';
import {
clearAuthState,
ensureFreshToken,
isKeycloakConfigured,
} from '../auth/keycloak';
import { getLegacyToken } from '../auth/util';
export const authAxios = axios.create();
export const publicAxios = axios.create();
let authInterceptorsConfigured = false;
export function setupAuthAxiosInterceptors() {
if (authInterceptorsConfigured) {
return;
}
authInterceptorsConfigured = true;
authAxios.interceptors.request.use(async (config) => {
const headers = config.headers || {};
if (headers.Authorization) {
config.headers = headers;
return config;
}
if (!isKeycloakConfigured()) {
const legacyToken = getLegacyToken();
if (legacyToken) {
headers.Authorization = legacyToken;
}
config.headers = headers;
return config;
}
try {
const token = await ensureFreshToken(30);
if (token) {
headers.Authorization = `Bearer ${token}`;
}
config.headers = headers;
return config;
} catch (error) {
clearAuthState();
window.location.assign('/login');
return Promise.reject(error);
}
});
}