forked from guacsec/trustify-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapiInit.ts
More file actions
86 lines (74 loc) · 1.97 KB
/
apiInit.ts
File metadata and controls
86 lines (74 loc) · 1.97 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import axios from "axios";
import { User, UserManager } from "oidc-client-ts";
import {
OIDC_CLIENT_ID,
OIDC_SERVER_URL,
oidcClientSettings,
oidcSignoutArgs,
} from "@app/oidc";
import { createClient } from "@app/client/client";
import { isAuthRequired } from "@app/Constants";
export const client = createClient({
// set default base url for requests
axios: axios,
throwOnError: true,
});
function getUser() {
const oidcStorage = sessionStorage.getItem(
`oidc.user:${OIDC_SERVER_URL}:${OIDC_CLIENT_ID}`,
);
if (!oidcStorage) {
return null;
}
return User.fromStorageString(oidcStorage);
}
export const initInterceptors = () => {
if (!isAuthRequired) {
return;
}
axios.interceptors.request.use(
(config) => {
const user = getUser();
const token = user?.access_token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
axios.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
if (error.response && error.response.status === 401) {
const userManager = new UserManager(oidcClientSettings);
try {
const refreshedUser = await userManager.signinSilent();
const access_token = refreshedUser?.access_token;
const retryCounter = error.config.retryCounter || 1;
const retryConfig = {
...error.config,
headers: {
...error.config.headers,
Authorization: `Bearer ${access_token}`,
},
};
// Retry limited times
if (retryCounter < 2) {
return axios({
...retryConfig,
retryCounter: retryCounter + 1,
});
}
} catch (_refreshError) {
await userManager.signoutRedirect(oidcSignoutArgs);
}
}
return Promise.reject(error);
},
);
};