Revize 8370b6c1
Přidáno uživatelem Václav Honzík před téměř 3 roky(ů)
frontend/src/api/api.ts | ||
---|---|---|
3 | 3 |
import config from '../config/conf' |
4 | 4 |
import { AppStore } from '../features/redux/store' |
5 | 5 |
|
6 |
let store: AppStore // this will get injected later
|
|
6 |
let store: AppStore // this will get injected in index.tsx
|
|
7 | 7 |
|
8 | 8 |
export const injectStore = (_store: Store) => { |
9 | 9 |
store = _store |
... | ... | |
23 | 23 |
(config) => { |
24 | 24 |
const accessToken = store.getState().user.accessToken // get the access token from the store |
25 | 25 |
if (accessToken) { |
26 |
// @ts-ignore |
|
27 |
// this will always be defined, axios developers are just lazy to provide better Typescript types |
|
26 |
// @ts-ignore (axios typescript types are a crime and this will always be defined) |
|
28 | 27 |
config.headers['Authorization'] = accessToken as string |
29 | 28 |
} |
30 | 29 |
|
... | ... | |
38 | 37 |
axiosInstance.interceptors.response.use( |
39 | 38 |
(res) => res, |
40 | 39 |
async (err) => { |
41 |
|
|
42 | 40 |
const originalConfig = err.config |
43 | 41 |
|
44 | 42 |
// Original URL might be login in which case we don't want to refresh the access token |
... | ... | |
53 | 51 |
// If there is no refresh token we simply log the user out |
54 | 52 |
if (!oldRefreshToken) { |
55 | 53 |
store.dispatch({ type: 'user/logout' }) |
56 |
return Promise.reject(err) |
|
57 | 54 |
} |
58 | 55 |
|
59 |
// Set this to retry the request that failed |
|
60 |
originalConfig.retry = true |
|
61 |
|
|
62 | 56 |
// Try refreshing the JWT |
63 | 57 |
try { |
64 |
const refreshConfig = createBaseInstance()
|
|
58 |
const refreshInstance = createBaseInstance()
|
|
65 | 59 |
// @ts-ignore |
66 |
refreshConfig.headers['Authorization'] = oldRefreshToken as string
|
|
60 |
refreshInstance.headers['Authorization'] = oldRefreshToken as string
|
|
67 | 61 |
|
68 |
// Send the request
|
|
69 |
const { data } = await axiosInstance.get('/refreshToken')
|
|
62 |
// Set this to retry the request that failed
|
|
63 |
originalConfig.retry = true
|
|
70 | 64 |
|
65 |
// Send the request |
|
66 |
const { data } = await axiosInstance.get('/users/refreshToken') |
|
71 | 67 |
const { accessToken, refreshToken } = data |
72 | 68 |
|
73 | 69 |
// Set the new tokens |
... | ... | |
76 | 72 |
payload: { accessToken, refreshToken }, |
77 | 73 |
}) |
78 | 74 |
|
75 |
// Return the failed instance so it can retry |
|
79 | 76 |
return axiosInstance(originalConfig) |
80 | 77 |
} catch (err: any) { |
81 | 78 |
// If the refresh token fails we log the user out |
82 | 79 |
store.dispatch({ type: 'user/logout' }) |
83 |
return Promise.reject(err) |
|
80 |
originalConfig.retry = false // do not retry we are logged out |
|
81 |
return originalConfig |
|
84 | 82 |
} |
85 | 83 |
} |
86 | 84 |
) |
Také k dispozici: Unified diff
login simple form impl + slice for user state