forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
82 lines (71 loc) · 2.16 KB
/
Copy pathauth.ts
File metadata and controls
82 lines (71 loc) · 2.16 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
import { createServerFn } from '@tanstack/react-start'
import { getAuth } from '@clerk/tanstack-react-start/server'
import { getWebRequest } from '@tanstack/react-start/server'
import { redirect } from '@tanstack/react-router'
/**
* Get the current authenticated user from Clerk
*/
export const getCurrentUser = createServerFn({ method: 'GET' }).handler(
async () => {
const request = getWebRequest()
if (!request) {
return { user: null, isAuthenticated: false }
}
const { userId } = await getAuth(request)
return {
userId,
isAuthenticated: !!userId,
}
}
)
/**
* Server function to check if the current user is authenticated
* In Clerk's waitlist mode, if a user can authenticate, they have been approved from the waitlist
*/
export const checkUserAccess = createServerFn({ method: 'GET' }).handler(
async () => {
const request = getWebRequest()
if (!request) {
return { allowed: false, reason: 'No request context' }
}
const { userId } = await getAuth(request)
if (!userId) {
return {
allowed: false,
reason:
'User not authenticated - please join waitlist or sign in if approved',
isAuthenticated: false,
}
}
// In waitlist mode, if user is authenticated via Clerk, they have been approved from the waitlist
return {
allowed: true,
reason: 'User is authenticated and approved from waitlist',
isAuthenticated: true,
userId,
}
}
)
/**
* Require authentication - redirects to waitlist for new users, login for approved users
* Use this in route loaders or beforeLoad hooks for protected routes
*/
export const requireAuth = createServerFn({ method: 'GET' }).handler(
async () => {
const request = getWebRequest()
if (!request) {
throw redirect({ to: '/login' })
}
const { userId } = await getAuth(request)
if (!userId) {
// In login mode, unauthenticated users should go to login
throw redirect({ to: '/login' })
}
// In waitlist mode, authenticated users have been approved and have access
return {
userId,
isAuthenticated: true,
hasAccess: true,
}
}
)