From b6c1cd672f0240c9a7343d8ec78e55c89d30061d Mon Sep 17 00:00:00 2001
From: Albin Henriksson <albhe428@student.liu.se>
Date: Mon, 5 Apr 2021 20:02:48 +0200
Subject: [PATCH] Permanent fix to login bug

---
 client/src/utils/SecureRoute.tsx        | 10 +++++++---
 client/src/utils/checkAuthentication.ts |  4 ++--
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/client/src/utils/SecureRoute.tsx b/client/src/utils/SecureRoute.tsx
index df4eab9d..c8c238df 100644
--- a/client/src/utils/SecureRoute.tsx
+++ b/client/src/utils/SecureRoute.tsx
@@ -11,11 +11,15 @@ interface SecureRouteProps extends RouteProps {
 /** Utility component to use for authentication, replace all routes that should be private with secure routes*/
 const SecureRoute: React.FC<SecureRouteProps> = ({ login, component: Component, ...rest }: SecureRouteProps) => {
   const authenticated = useAppSelector((state) => state.user.authenticated)
-  const loading = useAppSelector((state) => state.user.loading)
+  const [initialized, setInitialized] = React.useState(false)
   useEffect(() => {
-    CheckAuthentication()
+    const waitForAuthentication = async () => {
+      await CheckAuthentication()
+      setInitialized(true)
+    }
+    waitForAuthentication()
   }, [])
-  if (!loading) {
+  if (initialized) {
     if (login)
       return (
         <Route {...rest} render={(props) => (authenticated ? <Redirect to="/admin" /> : <Component {...props} />)} />
diff --git a/client/src/utils/checkAuthentication.ts b/client/src/utils/checkAuthentication.ts
index 41294b14..7f41ef47 100644
--- a/client/src/utils/checkAuthentication.ts
+++ b/client/src/utils/checkAuthentication.ts
@@ -8,7 +8,7 @@ const UnAuthorized = () => {
   logoutUser()(store.dispatch)
 }
 
-export const CheckAuthentication = () => {
+export const CheckAuthentication = async () => {
   const authToken = localStorage.token
   if (authToken) {
     const decodedToken: any = jwtDecode(authToken)
@@ -16,7 +16,7 @@ export const CheckAuthentication = () => {
       axios.defaults.headers.common['Authorization'] = authToken
       store.dispatch({ type: Types.LOADING_USER })
       console.log('loading user')
-      axios
+      await axios
         .get('/users')
         .then((res) => {
           store.dispatch({ type: Types.SET_AUTHENTICATED })
-- 
GitLab