Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to disable notifications of useCheckAuth and useLogoutIfAccessDenied hooks #5255

Merged
merged 5 commits into from
Sep 18, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions packages/ra-core/src/auth/useCheckAuth.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import * as React from 'react';
import { useState, useEffect } from 'react';
import expect from 'expect';
import { render, cleanup, wait } from '@testing-library/react';

import useCheckAuth from './useCheckAuth';
import AuthContext from './AuthContext';
import useLogout from './useLogout';
import useNotify from '../sideEffect/useNotify';
import { AuthProvider } from '../types';
import { defaultAuthParams } from './useAuthProvider';

jest.mock('./useLogout');
jest.mock('../sideEffect/useNotify');

const logout = jest.fn();
useLogout.mockImplementation(() => logout);
const notify = jest.fn();
useNotify.mockImplementation(() => notify);

const defaultParams = {};

const TestComponent = ({
params = defaultParams,
logoutOnFailure = true,
redirectTo = defaultAuthParams.loginUrl,
disableNotification = false,
}: {
params?: any;
logoutOnFailure?: boolean;
redirectTo?: string;
disableNotification?: boolean;
}) => {
const [authenticated, setAuthenticated] = useState(true);
const checkAuth = useCheckAuth();
useEffect(() => {
checkAuth(params, logoutOnFailure, redirectTo, disableNotification)
.then(() => setAuthenticated(true))
.catch(error => setAuthenticated(false));
}, [params, logoutOnFailure, redirectTo, disableNotification]);
return <div>{authenticated ? 'authenticated' : 'not authenticated'}</div>;
};

let loggedIn = true;

const authProvider: AuthProvider = {
login: () => Promise.reject('bad method'),
logout: () => {
loggedIn = false;
return Promise.resolve();
},
checkAuth: params => (params.token ? Promise.resolve() : Promise.reject()),
checkError: params => {
if (params instanceof Error && params.message === 'denied') {
return Promise.reject(new Error('logout'));
}
return Promise.resolve();
},
getPermissions: () => Promise.reject('not authenticated'),
};

describe('useCheckAuth', () => {
afterEach(() => {
logout.mockClear();
notify.mockClear();
cleanup();
});

it('should not logout if has credentials', async () => {
const { queryByText } = render(
<AuthContext.Provider value={authProvider}>
<TestComponent params={{ token: true }} />
</AuthContext.Provider>
);
await wait();
expect(logout).toHaveBeenCalledTimes(0);
expect(notify).toHaveBeenCalledTimes(0);
expect(queryByText('authenticated')).not.toBeNull();
});

it('should logout if has no credentials', async () => {
const { queryByText } = render(
<AuthContext.Provider value={authProvider}>
<TestComponent params={{ token: false }} />
</AuthContext.Provider>
);
await wait();
expect(logout).toHaveBeenCalledTimes(1);
expect(notify).toHaveBeenCalledTimes(1);
expect(queryByText('authenticated')).toBeNull();
});

it('should not logout if has no credentials and passed logoutOnFailure as false', async () => {
const { queryByText } = render(
<AuthContext.Provider value={authProvider}>
<TestComponent
params={{ token: false }}
logoutOnFailure={false}
/>
</AuthContext.Provider>
);
await wait();
expect(logout).toHaveBeenCalledTimes(0);
expect(notify).toHaveBeenCalledTimes(0);
expect(queryByText('not authenticated')).not.toBeNull();
});

it('should logout whitout showing a notification', async () => {
const { queryByText } = render(
<AuthContext.Provider value={authProvider}>
<TestComponent params={{ token: false }} disableNotification />
</AuthContext.Provider>
);
await wait();
expect(logout).toHaveBeenCalledTimes(1);
expect(notify).toHaveBeenCalledTimes(0);
expect(queryByText('authenticated')).toBeNull();
});
});
16 changes: 10 additions & 6 deletions packages/ra-core/src/auth/useCheckAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ const useCheckAuth = (): CheckAuth => {
(
params: any = {},
logoutOnFailure = true,
redirectTo = defaultAuthParams.loginUrl
redirectTo = defaultAuthParams.loginUrl,
disableNotification = false
) =>
authProvider.checkAuth(params).catch(error => {
if (logoutOnFailure) {
Expand All @@ -59,10 +60,11 @@ const useCheckAuth = (): CheckAuth => {
? error.redirectTo
: redirectTo
);
notify(
getErrorMessage(error, 'ra.auth.auth_check_error'),
'warning'
);
!disableNotification &&
notify(
getErrorMessage(error, 'ra.auth.auth_check_error'),
'warning'
);
}
throw error;
}),
Expand All @@ -81,13 +83,15 @@ const checkAuthWithoutAuthProvider = () => Promise.resolve();
* @param {Object} params The parameters to pass to the authProvider
* @param {boolean} logoutOnFailure Whether the user should be logged out if the authProvider fails to authenticatde them. True by default.
* @param {string} redirectTo The login form url. Defaults to '/login'
* @param {boolean} disableNotification Avoid showing a notification after the user is logged out. false by default.
*
* @return {Promise} Resolved to the authProvider response if the user passes the check, or rejected with an error otherwise
*/
type CheckAuth = (
params?: any,
logoutOnFailure?: boolean,
redirectTo?: string
redirectTo?: string,
disableNotification?: boolean
) => Promise<any>;

const getErrorMessage = (error, defaultMessage) =>
Expand Down
27 changes: 24 additions & 3 deletions packages/ra-core/src/auth/useLogoutIfAccessDenied.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@ useLogout.mockImplementation(() => logout);
const notify = jest.fn();
useNotify.mockImplementation(() => notify);

const TestComponent = ({ error }: { error?: any }) => {
const TestComponent = ({
error,
disableNotification,
}: {
error?: any;
disableNotification?: boolean;
}) => {
const [loggedOut, setLoggedOut] = useState(false);
const logoutIfAccessDenied = useLogoutIfAccessDenied();
useEffect(() => {
logoutIfAccessDenied(error).then(setLoggedOut);
}, [error, logoutIfAccessDenied]);
logoutIfAccessDenied(error, disableNotification).then(setLoggedOut);
}, [error, disableNotification, logoutIfAccessDenied]);
return <div>{loggedOut ? '' : 'logged in'}</div>;
};

Expand Down Expand Up @@ -100,4 +106,19 @@ describe('useLogoutIfAccessDenied', () => {
expect(notify).toHaveBeenCalledTimes(1);
expect(queryByText('logged in')).toBeNull();
});

it('should logout whitout showing a notification', async () => {
const { queryByText } = render(
<AuthContext.Provider value={authProvider}>
<TestComponent
error={new Error('denied')}
disableNotification
/>
</AuthContext.Provider>
);
await wait();
expect(logout).toHaveBeenCalledTimes(1);
expect(notify).toHaveBeenCalledTimes(0);
expect(queryByText('logged in')).toBeNull();
});
});
15 changes: 10 additions & 5 deletions packages/ra-core/src/auth/useLogoutIfAccessDenied.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ let authCheckPromise;
* useEffect(() => {
* dataProvider.getOne('secret', { id: 123 })
* .catch(error => {
* logoutIfaccessDenied(error);
* logoutIfAccessDenied(error);
* notify('server error', 'warning');
* })
* }, []);
Expand All @@ -42,7 +42,7 @@ const useLogoutIfAccessDenied = (): LogoutIfAccessDenied => {
const logout = useLogout();
const notify = useNotify();
const logoutIfAccessDenied = useCallback(
(error?: any) => {
(error?: any, disableNotification?: boolean) => {
// Sometimes, a component might trigger multiple simultaneous
// dataProvider calls which all fail and call this function.
// To avoid having multiple notifications, we first verify if
Expand All @@ -56,10 +56,11 @@ const useLogoutIfAccessDenied = (): LogoutIfAccessDenied => {
e && e.redirectTo
? e.redirectTo
: error && error.redirectTo
? error.redirectto
? error.redirectTo
: undefined;
logout({}, redirectTo);
notify('ra.notification.logged_out', 'warning');
!disableNotification &&
notify('ra.notification.logged_out', 'warning');
return true;
})
.finally(() => {
Expand All @@ -82,9 +83,13 @@ const logoutIfAccessDeniedWithoutProvider = () => Promise.resolve(false);
* If the authProvider rejects the call, logs the user out and shows a logged out notification.
*
* @param {Error} error An Error object (usually returned by the dataProvider)
* @param {boolean} disableNotification Avoid showing a notification after the user is logged out. false by default.
*
* @return {Promise} Resolved to true if there was a logout, false otherwise
*/
type LogoutIfAccessDenied = (error?: any) => Promise<boolean>;
type LogoutIfAccessDenied = (
error?: any,
disableNotification?: boolean
) => Promise<boolean>;

export default useLogoutIfAccessDenied;