feat: subir versión final Tablero CDC
This commit is contained in:
+109
-40
@@ -2,12 +2,13 @@ import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { onAuthStateChanged, signInWithPopup, signOut, type User } from "firebase/auth";
|
||||
import { auth, googleProvider } from "@/lib/firebase";
|
||||
import type { User as SupabaseUser } from "@supabase/supabase-js";
|
||||
import { supabase } from "@/lib/supabase";
|
||||
|
||||
const ALLOWED_DOMAIN = "gomezleemarketing.com";
|
||||
const GERARDO_EMAIL = "gmarrero@gomezleemarketing.com";
|
||||
@@ -17,8 +18,44 @@ function isAllowedEmail(email: string | null | undefined): boolean {
|
||||
return email.toLowerCase().endsWith(`@${ALLOWED_DOMAIN}`);
|
||||
}
|
||||
|
||||
function getRedirectTo(): string {
|
||||
if (typeof window === "undefined") return "/tablero-cdc/";
|
||||
return new URL(import.meta.env.BASE_URL || "/", window.location.origin).toString();
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
uid: string;
|
||||
email: string | null;
|
||||
displayName: string | null;
|
||||
photoURL: string | null;
|
||||
raw: SupabaseUser;
|
||||
}
|
||||
|
||||
function normalizeSupabaseUser(user: SupabaseUser): AuthUser {
|
||||
const metadata = user.user_metadata || {};
|
||||
|
||||
const displayName =
|
||||
metadata.full_name ||
|
||||
metadata.name ||
|
||||
metadata.display_name ||
|
||||
user.email?.split("@")[0] ||
|
||||
null;
|
||||
|
||||
const photoURL = metadata.avatar_url || metadata.picture || null;
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
uid: user.id,
|
||||
email: user.email ?? null,
|
||||
displayName,
|
||||
photoURL,
|
||||
raw: user,
|
||||
};
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: User | null;
|
||||
user: AuthUser | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
isGerardo: boolean;
|
||||
@@ -29,67 +66,99 @@ interface AuthContextValue {
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const applyUser = useCallback(async (supabaseUser: SupabaseUser | null) => {
|
||||
if (!supabaseUser) {
|
||||
setUser(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAllowedEmail(supabaseUser.email)) {
|
||||
await supabase.auth.signOut();
|
||||
setUser(null);
|
||||
setError("Solo se permite acceso con correos corporativos de GomezLee Marketing.");
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(normalizeSupabaseUser(supabaseUser));
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = onAuthStateChanged(auth, async (firebaseUser) => {
|
||||
if (firebaseUser) {
|
||||
// Validate domain on every session restore (page reload, etc.)
|
||||
if (!isAllowedEmail(firebaseUser.email)) {
|
||||
await signOut(auth);
|
||||
let mounted = true;
|
||||
|
||||
supabase.auth
|
||||
.getSession()
|
||||
.then(async ({ data, error: sessionError }) => {
|
||||
if (!mounted) return;
|
||||
|
||||
if (sessionError) {
|
||||
console.error("Error al recuperar sesión de Supabase:", sessionError);
|
||||
setUser(null);
|
||||
setError("Solo se permite acceso con correos corporativos de GomezLee Marketing.");
|
||||
} else {
|
||||
setUser(firebaseUser);
|
||||
setError(null);
|
||||
setError("No se pudo recuperar la sesión. Intenta iniciar sesión de nuevo.");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
|
||||
await applyUser(data.session?.user ?? null);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!mounted) return;
|
||||
console.error("Error inesperado al recuperar sesión:", err);
|
||||
setUser(null);
|
||||
}
|
||||
setError("No se pudo recuperar la sesión. Intenta iniciar sesión de nuevo.");
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
|
||||
const { data: listener } = supabase.auth.onAuthStateChange((_event, session) => {
|
||||
void applyUser(session?.user ?? null);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => unsubscribe();
|
||||
}, []);
|
||||
return () => {
|
||||
mounted = false;
|
||||
listener.subscription.unsubscribe();
|
||||
};
|
||||
}, [applyUser]);
|
||||
|
||||
const loginWithGoogle = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const result = await signInWithPopup(auth, googleProvider);
|
||||
const email = result.user.email?.toLowerCase() ?? "";
|
||||
|
||||
if (!isAllowedEmail(email)) {
|
||||
await signOut(auth);
|
||||
setUser(null);
|
||||
setError("Solo se permite acceso con correos corporativos de GomezLee Marketing.");
|
||||
return;
|
||||
}
|
||||
const { error: loginError } = await supabase.auth.signInWithOAuth({
|
||||
provider: "google",
|
||||
options: {
|
||||
redirectTo: getRedirectTo(),
|
||||
queryParams: {
|
||||
prompt: "select_account",
|
||||
hd: ALLOWED_DOMAIN,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
setUser(result.user);
|
||||
} catch (err: unknown) {
|
||||
// User closed popup or other cancellable error — don't treat as fatal
|
||||
if (
|
||||
err &&
|
||||
typeof err === "object" &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "auth/popup-closed-by-user"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
console.error("Error al iniciar sesión con Google:", err);
|
||||
if (loginError) {
|
||||
console.error("Error al iniciar sesión con Google:", loginError);
|
||||
setError("No se pudo iniciar sesión. Intenta de nuevo.");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await signOut(auth);
|
||||
const { error: logoutError } = await supabase.auth.signOut();
|
||||
|
||||
if (logoutError) {
|
||||
console.error("Error al cerrar sesión:", logoutError);
|
||||
setError("No se pudo cerrar sesión. Intenta de nuevo.");
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(null);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const isGerardo = !!user && user.email?.toLowerCase() === GERARDO_EMAIL;
|
||||
const isGerardo = useMemo(() => !!user && user.email?.toLowerCase() === GERARDO_EMAIL, [user]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, error, isGerardo, loginWithGoogle, logout }}>
|
||||
|
||||
Reference in New Issue
Block a user