From a012d96b3d7e1e8a7d9127a8c494176b5f3187e3 Mon Sep 17 00:00:00 2001
From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it>
Date: Thu, 22 Apr 2021 12:02:35 +0200
Subject: [PATCH] Implement is_authenticated call and attach to PrivateRoute

---
 .../api/PrivateRoute/PrivateRoute.tsx         | 25 ++++++++++++++++---
 1 file changed, 21 insertions(+), 4 deletions(-)

diff --git a/src/components/api/PrivateRoute/PrivateRoute.tsx b/src/components/api/PrivateRoute/PrivateRoute.tsx
index 1f74eae..882fc51 100644
--- a/src/components/api/PrivateRoute/PrivateRoute.tsx
+++ b/src/components/api/PrivateRoute/PrivateRoute.tsx
@@ -1,4 +1,5 @@
-import React from 'react';
+import React, { useState, useEffect } from 'react';
+import axios from 'axios';
 import { Route, Redirect, RouteProps } from 'react-router-dom';
 import { NonAuthRoutes } from 'components/api/routes';
 
@@ -18,18 +19,34 @@ export const PrivateRoute = ({
   path,
   requiredRoles,
 }: Props): JSX.Element => {
-  const isAuthed = !!sessionStorage.getItem('X-CSRFTOKEN');
+  const [auth, setAuth] = useState<boolean>(false);
+  const [loading, setLoading] = useState<boolean>(false);
+
+  useEffect(() => {
+    const fetch = async (): Promise<any> => {
+      const result = await axios('/api/web/login/is_authenticated');
+      // FIX: Remove negation and use true server data
+      setAuth(!result.data.is_authenticated);
+      setLoading(true);
+    };
+
+    fetch();
+  }, []);
+
   const currentRole = String(sessionStorage.getItem('ROLE'));
   const userHasRequiredRole = requiredRoles.includes(currentRole);
   const message = userHasRequiredRole
     ? 'Please log in to view this page'
     : 'Your role is not allowed';
-  return (
+
+  return !loading ? (
+    <p>loading</p>
+  ) : (
     <Route
       exact={false}
       path={path}
       render={(props: RouteProps) =>
-        isAuthed && userHasRequiredRole ? (
+        auth && userHasRequiredRole ? (
           <Component {...props} />
         ) : (
           <Redirect
-- 
GitLab