Skip to content
Snippets Groups Projects

Move back cookie fetch to SignInForm. Role fetched and saved into a Context. Small refactorings.

Merged Defendi Alberto requested to merge feature/role into dev
10 files
+ 122
179
Compare changes
  • Side-by-side
  • Inline
Files
10
import React, { useState, useEffect } from 'react';
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';
import { Roles } from 'api/userRoles';
/**
* 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 = {
@@ -20,27 +23,28 @@ export const PrivateRoute = ({
requiredRoles,
}: Props): JSX.Element => {
const [auth, setAuth] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const { role } = useContext(AuthContext);
useEffect(() => {
const fetch = async (): Promise<unknown> => {
const result = await axios('/api/web/login/is_authenticated');
setAuth(result.data.is_authenticated);
setLoading(true);
return null;
};
fetch();
}, []);
const currentRole = String(sessionStorage.getItem('ROLE'));
const userHasRequiredRole = requiredRoles.includes(currentRole);
/*
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();
}, [auth]);
const userHasRequiredRole = requiredRoles.includes(role);
const message = userHasRequiredRole
? 'Please log in to view this page'
: 'Your role is not allowed';
return !loading ? (
<p>loading</p>
) : (
return (
<Route
exact={false}
path={path}
@@ -51,7 +55,7 @@ export const PrivateRoute = ({
<Redirect
to={{
pathname: userHasRequiredRole
? NonAuthRoutes.signIn
? `${NonAuthRoutes.auth}${NonAuthRoutes.signIn}`
: NonAuthRoutes.unauthorized,
state: {
message,
Loading