Skip to content

Commit beb79b2

Browse files
committed
feat(useLogoutIfAccessDenied): handle redirect's url and add unit testing
1 parent 5bf9230 commit beb79b2

File tree

2 files changed

+43
-9
lines changed

2 files changed

+43
-9
lines changed

packages/ra-core/src/auth/useLogoutIfAccessDenied.spec.tsx

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,4 +258,36 @@ describe('useLogoutIfAccessDenied', () => {
258258
expect(screen.queryByText('unauthorized')).not.toBeNull();
259259
});
260260
});
261+
262+
it('should stay on same page if error have no redirectTo', async () => {
263+
render(
264+
<TestMemoryRouter>
265+
<AuthContext.Provider
266+
value={{
267+
...authProvider,
268+
checkError: () => {
269+
return Promise.reject({
270+
logoutUser: false,
271+
message: 'Access denied',
272+
});
273+
},
274+
}}
275+
>
276+
<Routes>
277+
<Route path="/" element={<TestComponent />} />
278+
<Route path="/login" element={<div>Login page</div>} />
279+
</Routes>
280+
</AuthContext.Provider>
281+
</TestMemoryRouter>
282+
);
283+
284+
await waitFor(() => {
285+
expect(authProvider.logout).toHaveBeenCalledTimes(0);
286+
expect(notify).toHaveBeenCalledWith('Access denied', {
287+
type: 'error',
288+
});
289+
expect(notify).toHaveBeenCalledTimes(1);
290+
expect(screen.queryByText('Login page')).toBeNull();
291+
});
292+
});
261293
});

packages/ra-core/src/auth/useLogoutIfAccessDenied.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ const useLogoutIfAccessDenied = (): LogoutIfAccessDenied => {
4343
const logout = useLogout();
4444
const notify = useNotify();
4545
const navigate = useNavigate();
46+
47+
const handleRedirect = (url: string) => {
48+
if (url.startsWith('http')) {
49+
window.location.href = url;
50+
} else {
51+
navigate(url);
52+
}
53+
};
54+
4655
const logoutIfAccessDenied = useCallback(
4756
(error?: any) => {
4857
if (!authProvider) {
@@ -102,16 +111,9 @@ const useLogoutIfAccessDenied = (): LogoutIfAccessDenied => {
102111

103112
if (logoutUser) {
104113
logout({}, redirectTo);
105-
} else {
106-
if (redirectTo.startsWith('http')) {
107-
// absolute link (e.g. https://my.oidc.server/login)
108-
window.location.href = redirectTo;
109-
} else {
110-
// internal location
111-
navigate(redirectTo);
112-
}
114+
} else if (redirectTo) {
115+
handleRedirect(redirectTo);
113116
}
114-
115117
return true;
116118
});
117119
},

0 commit comments

Comments
 (0)