-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAuthContext.tsx
More file actions
172 lines (146 loc) · 4.65 KB
/
Copy pathAuthContext.tsx
File metadata and controls
172 lines (146 loc) · 4.65 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import React, { createContext, useContext, useEffect, useState } from 'react';
import { Session, User } from '@supabase/supabase-js';
import { supabase } from '@/integrations/supabase/client';
import { useNavigate } from 'react-router-dom';
import { toast } from '@/hooks/use-toast';
interface AuthContextType {
user: User | null;
session: Session | null;
userRole: string | null;
loading: boolean;
signIn: (email: string, password: string) => Promise<void>;
signUp: (email: string, password: string, fullName: string) => Promise<void>;
signOut: () => Promise<void>;
}
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [session, setSession] = useState<Session | null>(null);
const [userRole, setUserRole] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
// Function to fetch user role from database
const fetchUserRole = async (userId: string) => {
try {
const { data, error } = await supabase
.from('profiles') // Assuming your table is named 'profiles'
.select('user_role')
.eq('id', userId)
.single();
if (error && error.code !== 'PGRST116') { // PGRST116 is "not found" error
console.error('Error fetching user role:', error);
return null;
}
return data?.user_role || null;
} catch (error) {
console.error('Error fetching user role:', error);
return null;
}
};
useEffect(() => {
let lastUserId = null;
let lastEvent = null;
const fetchAndSetUserRole = async (userId) => {
if (!userId || userId === lastUserId) return;
lastUserId = userId;
const role = await fetchUserRole(userId);
setUserRole(role);
};
supabase.auth.getSession().then(async ({ data: { session: currentSession } }) => {
setSession(currentSession);
setUser(currentSession?.user ?? null);
if (currentSession?.user) {
await fetchAndSetUserRole(currentSession.user.id);
}
setLoading(false);
});
const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, currentSession) => {
setSession(currentSession);
setUser(currentSession?.user ?? null);
if (event === lastEvent) return;
lastEvent = event;
if (currentSession?.user) {
await fetchAndSetUserRole(currentSession.user.id);
} else {
setUserRole(null);
}
if (event === 'SIGNED_IN') {
toast({ title: "Welcome back!", description: "You have successfully signed in." });
} else if (event === 'SIGNED_OUT') {
toast({ title: "Signed out", description: "You have been signed out successfully." });
}
}
);
return () => subscription.unsubscribe();
}, [navigate]);
const signIn = async (email: string, password: string) => {
try {
const { error } = await supabase.auth.signInWithPassword({ email, password });
if (error) throw error;
// Don't navigate here - let the Login component handle it via <Navigate>
} catch (error: any) {
toast({
title: "Error signing in",
description: error.message,
variant: "destructive"
});
throw error;
}
};
const signUp = async (email: string, password: string, fullName: string) => {
try {
const { error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
full_name: fullName
}
}
});
if (error) throw error;
toast({
title: "Account created",
description: "Please check your email to verify your account.",
});
// Don't navigate here - let the Register component handle it via <Navigate>
} catch (error: any) {
toast({
title: "Error signing up",
description: error.message,
variant: "destructive"
});
throw error;
}
};
const signOut = async () => {
try {
await supabase.auth.signOut();
navigate('/');
} catch (error: any) {
toast({
title: "Error signing out",
description: error.message,
variant: "destructive"
});
}
};
const value = {
user,
session,
userRole,
loading,
signIn,
signUp,
signOut
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};