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

Fetch role from server and clean axios requests.

parent 4b0ff168
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.
......@@ -3,7 +3,6 @@ import axios from 'axios';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { NonAuthRoutes } from 'api/routes';
import { AuthContext } from 'components/AuthUser/AuthContext';
import { Roles } from 'api/userRoles';
/**
* A wrapper for <Route> that redirects to the login screen if you're not yet authenticated.
......@@ -23,23 +22,28 @@ export const PrivateRoute = ({
requiredRoles,
}: Props): JSX.Element => {
const [auth, setAuth] = useState<boolean>(false);
const [serverRole, setServerRole] = useState<string>('');
const { role } = useContext(AuthContext);
useEffect(() => {
const fetch = async (): Promise<unknown> => {
const result = await axios('/api/web/login/is_authenticated');
setAuth(result.data.is_authenticated);
return null;
const fetch = async (): Promise<void> => {
await axios('/api/web/login/is_authenticated').then((res) =>
setAuth(res.data.is_authenticated),
);
};
/*
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.
*/
if (role !== Roles.visitor) fetch();
fetch();
axios('/api/web/login/get_role').then((response) =>
setServerRole(response.data.role),
);
}, [auth]);
const userHasRequiredRole = requiredRoles.includes(role);
const userHasRequiredRole = requiredRoles.includes(serverRole);
const message = userHasRequiredRole
? 'Please log in to view this page'
: 'Your role is not allowed';
......@@ -54,9 +58,10 @@ export const PrivateRoute = ({
) : (
<Redirect
to={{
pathname: userHasRequiredRole
? `${NonAuthRoutes.auth}${NonAuthRoutes.signIn}`
: NonAuthRoutes.unauthorized,
pathname:
userHasRequiredRole && auth
? `${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.
Please register or to comment