Spaces:
Runtime error
Runtime error
Download src/lib/withAuth.js from kirangawande0176/DevSync: direct link, hf CLI and curl.
- Browser
- Download file 2.42 kB
-
https://huggingface.co/spaces/kirangawande0176/DevSync/resolve/main/src/lib/withAuth.js
- Command line
-
hf download hf://spaces/kirangawande0176/DevSync/src/lib/withAuth.js
-
curl -L -o withAuth.js https://huggingface.co/spaces/kirangawande0176/DevSync/resolve/main/src/lib/withAuth.js
2.42 kB
| import React, { useEffect, useState, useContext, createContext } from "react"; | |
| import { useRouter } from "next/router"; | |
| import { supabase } from '@/lib/supabase'; | |
| const AuthContext = createContext(); | |
| const supabase = createClient( | |
| "https://uegxrbknglbvxsyarymt.supabase.co", | |
| "sb_publishable_foN8TkkgR8bFamza4wP2aw_Ll_SToSt" | |
| ); | |
| export const withAuth = ({ children }) => { | |
| const [user, setUser] = useState(null); | |
| const [userRole, setUserRole] = useState(null); | |
| const [loading, setLoading] = useState(true); | |
| const router = useRouter(); | |
| useEffect(() => { | |
| // ✅ CHECK EXISTING SESSION | |
| supabase.auth.getSession().then(({ data: { session } }) => { | |
| setUser(session?.user || null); | |
| if (session?.user) { | |
| fetchUserRole(session.user.id); | |
| } | |
| setLoading(false); | |
| }); | |
| // ✅ LISTEN FOR AUTH CHANGES | |
| const { | |
| data: { subscription }, | |
| } = supabase.auth.onAuthStateChanged((event, session) => { | |
| console.log("🔐 Auth state changed:", event); | |
| setUser(session?.user || null); | |
| if (session?.user) { | |
| fetchUserRole(session.user.id); | |
| } else { | |
| setUserRole(null); | |
| } | |
| // ✅ REDIRECT ON SIGN OUT | |
| if (event === "SIGNED_OUT") { | |
| router.push("/"); | |
| } | |
| // ✅ REDIRECT ON VERIFIED EMAIL | |
| if (event === "SIGNED_IN") { | |
| const userRole = localStorage.getItem("userRole"); | |
| if (userRole === "admin") router.push("/admin"); | |
| else if (userRole === "employee") router.push("/employee"); | |
| else if (userRole === "client") router.push("/client"); | |
| else router.push("/dashboard"); | |
| } | |
| }); | |
| return () => subscription?.unsubscribe(); | |
| }, []); | |
| const fetchUserRole = async (userId) => { | |
| try { | |
| const { data, error } = await supabase | |
| .from("users") | |
| .select("role") | |
| .eq("id", userId) | |
| .single(); | |
| if (error) throw error; | |
| setUserRole(data?.role); | |
| localStorage.setItem("userRole", data?.role); | |
| } catch (error) { | |
| console.error("Error fetching user role:", error); | |
| } | |
| }; | |
| return ( | |
| <AuthContext.Provider value={{ user, userRole, loading }}> | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; | |
| export const useAuth = () => { | |
| const context = useContext(AuthContext); | |
| if (!context) { | |
| throw new Error("useAuth must be used within AuthProvider"); | |
| } | |
| return context; | |
| }; | |