Require accessToken to browse pages
This commit is contained in:
committed by
Anders Borch
parent
4655544197
commit
049664b98e
19
front/src/components/auth/RequireAuth.tsx
Normal file
19
front/src/components/auth/RequireAuth.tsx
Normal file
@ -0,0 +1,19 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useHasAccessToken } from '../../hooks/auth/useHasAccessToken';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
function RequireAuth({ children }: { children: JSX.Element }): JSX.Element {
|
||||
const hasAccessToken = useHasAccessToken();
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasAccessToken) {
|
||||
navigate('/auth/login');
|
||||
}
|
||||
}, [hasAccessToken, navigate]);
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
export default RequireAuth;
|
||||
@ -0,0 +1,17 @@
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import RequireAuth from '../RequireAuth';
|
||||
|
||||
const component = {
|
||||
title: 'RequireAuth',
|
||||
component: RequireAuth,
|
||||
};
|
||||
|
||||
export default component;
|
||||
|
||||
export const RequireAuthWithHelloChild = () => (
|
||||
<MemoryRouter>
|
||||
<RequireAuth>
|
||||
<div>Hello</div>
|
||||
</RequireAuth>
|
||||
</MemoryRouter>
|
||||
);
|
||||
9
front/src/components/auth/__tests__/RequireAuth.test.tsx
Normal file
9
front/src/components/auth/__tests__/RequireAuth.test.tsx
Normal file
@ -0,0 +1,9 @@
|
||||
import { render } from '@testing-library/react';
|
||||
|
||||
import { RequireAuthWithHelloChild } from '../__stories__/RequireAuth.stories';
|
||||
|
||||
it('Checks the Require Auth renders', () => {
|
||||
const { getAllByText } = render(<RequireAuthWithHelloChild />);
|
||||
|
||||
expect(getAllByText('Hello')).toBeTruthy();
|
||||
});
|
||||
Reference in New Issue
Block a user