-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSupabaseProvider.jsx
More file actions
152 lines (135 loc) · 3.92 KB
/
SupabaseProvider.jsx
File metadata and controls
152 lines (135 loc) · 3.92 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
149
150
151
152
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { supabase } from './supabaseClient.js'
// Provides auth/session/profile state to the app
const SupabaseAuthContext = createContext(null)
async function fetchMyProfile(userId) {
if (!userId) return null
const { data, error } = await supabase
.from('profiles')
.select('id,email,display_name,role,requested_role,created_at')
.eq('id', userId)
.maybeSingle()
if (error) throw error
return data || null
}
export function SupabaseProvider({ children }) {
const [session, setSession] = useState(null)
const [user, setUser] = useState(null)
const [profile, setProfile] = useState(null)
const [role, setRole] = useState(null)
const [loading, setLoading] = useState(true)
const [authError, setAuthError] = useState(null)
const refreshProfile = async (explicitUserId) => {
const userId = explicitUserId || user?.id
if (!userId) {
setProfile(null)
setRole(null)
return null
}
const p = await fetchMyProfile(userId)
setProfile(p)
setRole(p?.role || null)
return p
}
const ensureProfile = async () => {
const { error } = await supabase.rpc('ensure_profile')
if (error) console.error('ensure_profile failed', error)
}
useEffect(() => {
let mounted = true
const init = async () => {
try {
const { data, error } = await supabase.auth.getSession()
if (error) throw error
if (!mounted) return
setSession(data.session)
setUser(data.session?.user || null)
if (data.session?.user?.id) {
await ensureProfile()
await refreshProfile(data.session.user.id)
} else {
setProfile(null)
setRole(null)
}
} catch (e) {
console.error('Supabase session init failed', e)
} finally {
if (mounted) setLoading(false)
}
}
init()
const { data: subscription } = supabase.auth.onAuthStateChange(async (event, nextSession) => {
setSession(nextSession)
setUser(nextSession?.user || null)
if (event === 'SIGNED_OUT') {
setProfile(null)
setRole(null)
return
}
if (nextSession?.user?.id) {
try {
await ensureProfile()
await refreshProfile(nextSession.user.id)
} catch (e) {
console.error('Profile refresh failed', e)
}
}
})
return () => {
mounted = false
subscription?.subscription?.unsubscribe()
}
}, [])
const signInWithPassword = async (email, password) => {
setAuthError(null)
const { data, error } = await supabase.auth.signInWithPassword({ email, password })
if (error) {
setAuthError(error)
return { data: null, error }
}
return { data, error: null }
}
const signUpWithPassword = async (email, password, requestedRole) => {
setAuthError(null)
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
requested_role: requestedRole,
},
},
})
if (error) {
setAuthError(error)
return { data: null, error, needsEmailConfirmation: false }
}
const needsEmailConfirmation = !data.session
return { data, error: null, needsEmailConfirmation }
}
const signOut = async () => {
setAuthError(null)
const { error } = await supabase.auth.signOut()
if (error) setAuthError(error)
return { error: error || null }
}
const value = useMemo(
() => ({
session,
user,
profile,
role,
loading,
authError,
signInWithPassword,
signUpWithPassword,
signOut,
refreshProfile,
}),
[session, user, profile, role, loading, authError]
)
return <SupabaseAuthContext.Provider value={value}>{children}</SupabaseAuthContext.Provider>
}
export function useSupabaseAuth() {
return useContext(SupabaseAuthContext)
}