Only allowing authenticated users to ask a question

Let's move to the HomePage component and only show the Ask a question button if the user is authenticated:

  1. We'll start by importing the authentication Hook:
import { useAuth } from './Auth';
  1. Let's Hook into the authentication context and return whether the user is authenticated just before the JSX is returned:
export const HomePage: FC<Props> = ( ... ) => {
...

const { isAuthenticated } = useAuth();

return (
...
);
};

  1. We can then use the isAuthenticated property from the auth variable and a short-circuit operator to only render the Ask a question button if the user is signed in:
<Page>
<div
...
>
<PageTitle>Unanswered Questions</PageTitle>
{isAuthenticated && (
<PrimaryButton onClick={handleAskQuestionClick}>
Ask a question
</PrimaryButton>
)}
</div>
...
</Page>

That completes the change to the home page. However, the user could still get to the ask page by manually putting the relevant path in the browser.

  1. Let's stop unauthenticated users from manually navigating to the ask page and asking a question in AskPage.tsx. We are going to create an AuthorizedPage component to help us to do this that will only render its child components if the user is authenticated. Let's create a file called AuthorizedPage.tsx in the src folder with the following content:
import React, { FC, Fragment } from 'react';
import { Page } from './Page';
import { useAuth } from './Auth';

export const AuthorizedPage: FC = ({ children }) => {
const { isAuthenticated } = useAuth();
if (isAuthenticated) {
return <Fragment>{children}</Fragment>;
} else {
return <Page title="You do not have access to this page" />;
}
};

We use our useAuth Hook and render the child components if the user is authenticated. If the user isn't authenticated, we inform them that they don't have access to the page.

  1. Let's move to App.tsx and import AuthorizedPage:
import { AuthorizedPage } from './AuthorizedPage';
  1. We can then wrap the AuthorizedPage component around the AskPage component in the App component JSX:
<Route path="/ask">
<Suspense
...
>
<AuthorizedPage>
<AskPage />
</AuthorizedPage>
</Suspense>
</Route>
  1. Let's give this all a try in the running app. Make sure the user is signed out and go to the home page:

We'll see that there is no button to ask a question, as we expected.

  1. Let's try to go to the ask page by manually putting the path into the browser:

We are informed that we don't have permission to view the page, as we expected.

  1. Let's sign in now:

The Ask a question button is now available, as we expected.

That concludes the changes we need to make for asking a question.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.18.4