diff --git a/packages/ra-ui-materialui/src/auth/Logout.spec.tsx b/packages/ra-ui-materialui/src/auth/Logout.spec.tsx new file mode 100644 index 00000000000..92e4324a61a --- /dev/null +++ b/packages/ra-ui-materialui/src/auth/Logout.spec.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { render, screen, waitFor } from '@testing-library/react'; +import { UserAuthenticated, UserUnauthenticated } from './Logout.stories'; + +it('should display logout button if the auth succeeds', async () => { + render(); + + await waitFor(() => { + const logoutButton = screen.queryByText( + 'ra.auth.logout' + ) as HTMLInputElement; + expect(logoutButton).not.toBeNull(); + }); +}); + +it('should not display logout button if the auth fails', async () => { + render(); + + await waitFor(() => { + const logoutButton = screen.queryByText( + 'ra.auth.logout' + ) as HTMLInputElement; + expect(logoutButton).toBeNull(); + }); +}); diff --git a/packages/ra-ui-materialui/src/auth/Logout.stories.tsx b/packages/ra-ui-materialui/src/auth/Logout.stories.tsx new file mode 100644 index 00000000000..a6552839d8c --- /dev/null +++ b/packages/ra-ui-materialui/src/auth/Logout.stories.tsx @@ -0,0 +1,29 @@ +import { Typography } from '@mui/material'; +import * as React from 'react'; +import { AdminContext } from '../AdminContext'; +import { Logout } from './Logout'; + +export default { title: 'ra-ui-materialui/auth/Logout' }; + +const MinimalAdmin = (props: { authenticated: boolean }) => { + const authProvider = { + login: () => Promise.resolve(), + logout: () => Promise.resolve(), + checkAuth: () => + props.authenticated ? Promise.resolve() : Promise.reject(), + checkError: () => Promise.resolve(), + getPermissions: () => Promise.resolve(), + }; + return ( + + + Should {props.authenticated ? '' : 'not '}display logout button + + + + ); +}; + +export const UserAuthenticated = () => ; + +export const UserUnauthenticated = () => ; diff --git a/packages/ra-ui-materialui/src/auth/Logout.tsx b/packages/ra-ui-materialui/src/auth/Logout.tsx index 8172f183f45..6257c1bf939 100644 --- a/packages/ra-ui-materialui/src/auth/Logout.tsx +++ b/packages/ra-ui-materialui/src/auth/Logout.tsx @@ -12,7 +12,7 @@ import { MenuItemProps } from '@mui/material/MenuItem'; import ExitIcon from '@mui/icons-material/PowerSettingsNew'; import clsx from 'clsx'; -import { useTranslate, useLogout } from 'ra-core'; +import { useTranslate, useLogout, useAuthState } from 'ra-core'; /** * Logout button component, to be passed to the Admin component @@ -24,6 +24,7 @@ export const Logout: FunctionComponent< > = React.forwardRef(function Logout(props, ref) { const { className, redirectTo, icon, ...rest } = props; + const { authenticated } = useAuthState(); const isXSmall = useMediaQuery((theme: Theme) => theme.breakpoints.down('sm') ); @@ -34,6 +35,9 @@ export const Logout: FunctionComponent< redirectTo, logout, ]); + + if (!authenticated) return null; + return (