forked from koshikraj/ottopus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequire-session.tsx
More file actions
57 lines (50 loc) · 2.07 KB
/
Copy pathrequire-session.tsx
File metadata and controls
57 lines (50 loc) · 2.07 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'use client'
import { usePrivy } from '@privy-io/react-auth'
import { usePathname, useRouter } from 'next/navigation'
import { useEffect, type ReactNode } from 'react'
import { FullPageLoader } from '@/components/motion'
import { usePrivyAvailable } from './privy-provider'
/**
* Keeps signed-out visitors out of the app shell.
*
* Client-side, because that is where the session is — Privy holds the token in
* the browser and there is no cookie for the server to read. This is a
* redirect, not a security boundary: everything that matters is enforced by the
* service, which verifies the token on every request and never trusts the fact
* that a page rendered.
*
* Renders a loader rather than the page while Privy is deciding. Showing the
* portfolio and then yanking it away is worse than a moment of nothing, and the
* page behind would briefly display someone else's shape of data.
*
* Does nothing when Privy is not configured, so a checkout without env still
* shows the app instead of bouncing forever between two routes.
*/
export function RequireSession({ children }: { children: ReactNode }) {
return usePrivyAvailable() ? <Guarded>{children}</Guarded> : <>{children}</>
}
function Guarded({ children }: { children: ReactNode }) {
const { ready, authenticated } = usePrivy()
const router = useRouter()
const pathname = usePathname()
const blocked = ready && !authenticated
useEffect(() => {
if (blocked) router.replace(`/signin?next=${encodeURIComponent(pathname)}`)
}, [blocked, router, pathname])
if (!ready || blocked) {
// L4, the cold-boot loader. This is the genuine article rather than a
// navigation: the layout holds across shell routes, so once Privy has
// answered it never renders again for the life of the session.
return (
<FullPageLoader
title={blocked ? 'Taking you to sign in' : 'Getting your ocean in order'}
messages={
blocked
? ['One moment.']
: ['Finding your session', 'Waking Otto up', 'Checking who is listening']
}
/>
)
}
return <>{children}</>
}