diff --git a/components/ProtectedRoute.js b/components/ProtectedRoute.js index 08dfc098..6bd55650 100644 --- a/components/ProtectedRoute.js +++ b/components/ProtectedRoute.js @@ -5,7 +5,8 @@ import { useRouter } from 'next/router' import { getUserDetails } from "../controllers/auth/auth" // import cookies from 'next-cookies' // import cookieCutter from 'cookie-cutter' -import { useEffect, useState } from 'react' +import { useEffect, useState, useContext} from 'react' +import {UserContext} from '../providers/user' export default function withAuth(Component) { @@ -17,24 +18,32 @@ export default function withAuth(Component) { const [token, setToken] = useState(null) + const userCtx = useContext(UserContext) + useEffect(() => { if(window && window.document.cookie) { setToken( - JSON.parse(window.document.cookie.split('=')[1])?.token + JSON.parse(window.document.cookie.split('=')[1])?.token ?? props?.token ) } },[]) - / + + if(userCtx && userCtx?.id == 6) { + router.push('/auth/login') + return null - getUserDetails(token ?? props?.token, `${process.env.NEXT_PUBLIC_API_URL}/rest-auth/user/`) + } else { + getUserDetails(token, `${process.env.NEXT_PUBLIC_API_URL}/rest-auth/user/`) .then(async user => { if(user && user?.id == 6) { - return router.push('/auth/login') + router.push('/auth/login') + return null } }) + } return } diff --git a/controllers/auth/auth.js b/controllers/auth/auth.js index 931ffa2d..62dc6040 100644 --- a/controllers/auth/auth.js +++ b/controllers/auth/auth.js @@ -184,9 +184,10 @@ const logUserIn = (req, res, creds, was) => { } function getUserDetails (token, url) { + let savedSession = null if (typeof window != "undefined") { - let savedSession = window.localStorage.getItem('user') + savedSession = window.localStorage.getItem('user') if (savedSession && savedSession.length > 0) { savedSession = JSON.parse(window.localStorage.getItem('user')) } @@ -198,7 +199,6 @@ function getUserDetails (token, url) { } - return fetch(url, { 'method': 'GET', 'headers': { @@ -229,8 +229,8 @@ function getUserDetails (token, url) { error: true, message: err.message || err } }) + } -} const getUserContacts = async (token, url) => { return fetch(url, {