Advertisement
metalni

AuthGuard

Sep 15th, 2022
1,520
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ** React Imports
  2. import { ReactNode, ReactElement, useEffect } from 'react'
  3.  
  4. // ** Next Imports
  5. import { useRouter } from 'next/router'
  6.  
  7. // ** Hooks Import
  8. import { useAuth } from 'src/hooks/useAuth'
  9.  
  10. interface AuthGuardProps {
  11.   children: ReactNode
  12.   fallback: ReactElement | null
  13. }
  14.  
  15. const AuthGuard = (props: AuthGuardProps) => {
  16.   const { children, fallback } = props
  17.   const auth = useAuth()
  18.   const router = useRouter()
  19.  
  20.   useEffect(
  21.     () => {
  22.       if (!router.isReady) {
  23.         return
  24.       }
  25.  
  26.       if (auth.user === null) {
  27.         if (router.asPath !== '/') {
  28.           router.replace({
  29.             pathname: '/login',
  30.             query: { returnUrl: router.asPath }
  31.           })
  32.         } else {
  33.           router.replace('/login')
  34.         }
  35.       }
  36.     },
  37.     // eslint-disable-next-line react-hooks/exhaustive-deps
  38.     [router.route]
  39.   )
  40.  
  41.   if (auth.loading || auth.user === null) {
  42.     return fallback
  43.   }
  44.  
  45.   return <>{children}</>
  46. }
  47.  
  48. export default AuthGuard
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement