Skip to content
Snippets Groups Projects
Verified Commit be557891 authored by Defendi Alberto's avatar Defendi Alberto
Browse files

Remove superflous api call and use AuthContext to pass isAuthenticated

and role.
parent dbb38d5d
No related branches found
No related tags found
2 merge requests!56Refined auth flow and new website pages.,!44New route type (RestrictedRoute) and better api calls.
import React, { useState, useEffect, useContext } from 'react';
import axios from 'axios';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { NonAuthRoutes } from 'api/routes';
import { AuthContext } from 'components/AuthUser/AuthContext';
......@@ -8,7 +7,6 @@ import { AuthContext } from 'components/AuthUser/AuthContext';
* A wrapper for <Route> that redirects to the login screen if you're not yet authenticated.
* Every non-public route must be wrapped with this component.
* */
type Props = {
Component: React.FC<RouteProps>;
path: string;
......@@ -21,29 +19,11 @@ export const PrivateRoute = ({
path,
requiredRoles,
}: Props): JSX.Element => {
const [auth, setAuth] = useState<boolean>(false);
const [serverRole, setServerRole] = useState<string>('');
const { role } = useContext(AuthContext);
const { role, isAuth } = useContext(AuthContext);
useEffect(() => {
const fetch = async (): Promise<void> => {
await axios('/api/web/login/is_authenticated').then((res) =>
setAuth(res.data.is_authenticated),
);
};
// Check if the role is contained in the roles array (passed as props).
const userHasRequiredRole = requiredRoles.includes(role);
/*
Check if user is logged in.
Avoiding this condition would call is\_authenticated every time
this component state is triggered, falling in unnecessary calls to the
server.
*/
fetch();
axios('/api/web/login/get_role').then((response) =>
setServerRole(response.data.role),
);
}, [auth]);
const userHasRequiredRole = requiredRoles.includes(serverRole);
const message = userHasRequiredRole
? 'Please log in to view this page'
: 'Your role is not allowed';
......@@ -53,15 +33,14 @@ export const PrivateRoute = ({
exact={false}
path={path}
render={(props: RouteProps) =>
auth && userHasRequiredRole ? (
isAuth && userHasRequiredRole ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname:
userHasRequiredRole && auth
? `${NonAuthRoutes.auth}${NonAuthRoutes.signIn}`
: NonAuthRoutes.unauthorized,
pathname: !userHasRequiredRole
? `${NonAuthRoutes.auth}${NonAuthRoutes.signIn}`
: NonAuthRoutes.unauthorized,
state: {
message,
requestedPath: path,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment