-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProtectRoute.js
36 lines (29 loc) · 1014 Bytes
/
ProtectRoute.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { useEffect } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { useWallet } from './WalletContext'
export default function ProtectRoute({children}) {
const { push } = useRouter()
const path = usePathname()
const { status } = useWallet()
const allowedPaths = {
// everything except /welcome, /create-wallet, /unlock-wallet
loaded: /^(?!\/(?:unlock-wallet|create-wallet|welcome)(?:\/|$)).*$/,
// allows /unlock-wallet
locked: /\/unlock-wallet/,
// allows /welcome or /create-wallet
not_exists: /^(\/welcome|\/create-wallet)$/
}
const redirectPaths = {
loaded: '/',
locked: '/unlock-wallet',
not_exists: '/welcome'
}
const shouldRedirect = !(allowedPaths[status] || /(?:)/).test(path)
useEffect(() => {
if (shouldRedirect)
push(redirectPaths[status])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [status])
console.log('ProtectRoute', status)
return shouldRedirect ? null : children
}