-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseAuth.tsx
More file actions
148 lines (131 loc) · 3.74 KB
/
useAuth.tsx
File metadata and controls
148 lines (131 loc) · 3.74 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { useEffect, useState } from "react"
import { PUBLIC_CONFIG } from "@repo/shared/env/publicConfig"
import { providers, type Provider } from "@repo/client/auth/providers"
type States =
| {
type: "unauthenticated"
submitInviteCode: (inviteCode: string) => Promise<Response>
signIn: (provider: string) => void
providers: Array<Provider>
}
| {
type: "creating-account"
createAccount: (provider: string) => void
cancelCreateAccount: () => void
providers: Array<Provider>
}
| {
type: "signed-in"
userId: string
signOut: () => Promise<Response>
linkAccount: (provider: string) => void
providers: Array<Provider>
}
let cookieCache: Map<string, string | undefined> | null = null
function getCookie(key: string) {
if (cookieCache) return cookieCache.get(key)
cookieCache = new Map()
const cookies = document.cookie.split(";")
for (const cookie of cookies) {
const [key, value] = cookie.split("=") as [string, string | undefined]
cookieCache.set(key.trim(), value?.trim())
}
return cookieCache.get(key)
}
function clearCookieCache() {
cookieCache = null
}
//eslint-disable-next-line @typescript-eslint/no-explicit-any -- cookieStore is not in lib.dom.d.ts because it's only supported in Chrome
const cookieStore = (globalThis as any).cookieStore as EventTarget
/**
* Should transition state from "unauthenticated" to "creating-account"
*/
function submitInviteCode(inviteCode: string) {
return fetch("/api/oauth/invite", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code: inviteCode }),
})
}
/**
* Should transition state from "creating-account" to "signed-in"
*/
function createAccount(provider: string) {
globalThis.location.href = `/api/oauth/connect/${provider}`
}
/**
* Should transition state from "creating-account" to "unauthenticated"
*/
function cancelCreateAccount() {
document.cookie = `${PUBLIC_CONFIG.accountCreationCookie}=; max-age=0; path=/;`
}
/**
* Should transition state from "signed-in" to "unauthenticated"
*/
function signOut() {
return fetch("/api/oauth/session", { method: "DELETE" })
}
/**
* Should transition state from "unauthenticated" to "signed-in" (only if account already exists)
*/
function signIn(provider: string) {
globalThis.location.href = `/api/oauth/connect/${provider}`
}
function linkAccount(provider: string) {
return fetch("/api/oauth/invite").then((res) => {
if (res.ok) {
window.location.href = `/api/oauth/connect/${provider}`
} else {
throw new Error("Failed to get invite code", { cause: res.statusText })
}
})
}
const filteredProviders = providers.filter((p) => __AUTH_PROVIDERS__.includes(p.key))
export function useAuth(): States {
const [userId, setUserId] = useState<string | undefined>(() =>
getCookie(PUBLIC_CONFIG.userIdCookie)
)
const [creatingAccount, setCreatingAccount] = useState(() =>
getCookie(PUBLIC_CONFIG.accountCreationCookie)
)
useEffect(() => {
const controller = new AbortController()
let doubleEventTimeout: NodeJS.Timeout
cookieStore.addEventListener(
"change",
() => {
clearCookieCache()
clearTimeout(doubleEventTimeout)
doubleEventTimeout = setTimeout(() => {
setUserId(getCookie(PUBLIC_CONFIG.userIdCookie))
setCreatingAccount(getCookie(PUBLIC_CONFIG.accountCreationCookie))
}, 10)
},
{ signal: controller.signal }
)
return () => controller.abort()
}, [])
if (userId) {
return {
type: "signed-in",
userId,
signOut,
linkAccount,
providers: filteredProviders,
}
}
if (creatingAccount) {
return {
type: "creating-account",
createAccount,
cancelCreateAccount,
providers: filteredProviders,
}
}
return {
type: "unauthenticated",
submitInviteCode,
signIn,
providers: filteredProviders,
}
}