feat: auth & admin
This commit is contained in:
+41
-20
@@ -1,4 +1,9 @@
|
||||
import { fetchBaseQuery, type BaseQueryFn, type FetchArgs, type FetchBaseQueryError } from '@reduxjs/toolkit/query/react';
|
||||
import {
|
||||
fetchBaseQuery,
|
||||
type BaseQueryFn,
|
||||
type FetchArgs,
|
||||
type FetchBaseQueryError,
|
||||
} from '@reduxjs/toolkit/query/react';
|
||||
import type { RootState } from '../store';
|
||||
import { getApiBaseUrl } from '../config/runtime-config';
|
||||
import { logout, setTokens } from '../store/slices/auth';
|
||||
@@ -13,33 +18,49 @@ const rawBaseQuery = () =>
|
||||
},
|
||||
});
|
||||
|
||||
export const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> =
|
||||
async (args, api, extraOptions) => {
|
||||
let result = await rawBaseQuery()(args, api, extraOptions);
|
||||
export const baseQueryWithReauth: BaseQueryFn<
|
||||
string | FetchArgs,
|
||||
unknown,
|
||||
FetchBaseQueryError
|
||||
> = async (args, api, extraOptions) => {
|
||||
let result = await rawBaseQuery()(args, api, extraOptions);
|
||||
|
||||
if (result.error?.status === 401) {
|
||||
const state = api.getState() as RootState;
|
||||
const refreshToken = state.auth.refreshToken;
|
||||
if (result.error?.status === 401) {
|
||||
const state = api.getState() as RootState;
|
||||
const refreshToken = state.auth.refreshToken;
|
||||
|
||||
if (refreshToken) {
|
||||
const refreshResult = await rawBaseQuery()({
|
||||
if (refreshToken) {
|
||||
const refreshResult = await rawBaseQuery()(
|
||||
{
|
||||
url: '/auth/refresh',
|
||||
method: 'POST',
|
||||
body: { refreshToken },
|
||||
}, api, extraOptions);
|
||||
},
|
||||
api,
|
||||
extraOptions,
|
||||
);
|
||||
|
||||
if (refreshResult.data) {
|
||||
const { accessToken, refreshToken: newRefresh, expiresIn } =
|
||||
(refreshResult.data as { accessToken: string; refreshToken: string; expiresIn: number });
|
||||
api.dispatch(setTokens({ accessToken, refreshToken: newRefresh, expiresIn }));
|
||||
result = await rawBaseQuery()(args, api, extraOptions);
|
||||
} else {
|
||||
api.dispatch(logout());
|
||||
}
|
||||
if (refreshResult.data) {
|
||||
const {
|
||||
accessToken,
|
||||
refreshToken: newRefresh,
|
||||
expiresIn,
|
||||
} = refreshResult.data as {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresIn: number;
|
||||
};
|
||||
api.dispatch(
|
||||
setTokens({ accessToken, refreshToken: newRefresh, expiresIn }),
|
||||
);
|
||||
result = await rawBaseQuery()(args, api, extraOptions);
|
||||
} else {
|
||||
api.dispatch(logout());
|
||||
}
|
||||
} else {
|
||||
api.dispatch(logout());
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user