Actualizar frontend/src/lib/auth.jsx

This commit is contained in:
2026-07-10 14:30:32 -05:00
parent 329294fc13
commit 9266dd82b9

View File

@@ -10,54 +10,68 @@ export function AuthProvider({ children }) {
const [permisos, setPermisos] = useState([]); // ["ocupabilidad", "cobranza", ...] const [permisos, setPermisos] = useState([]); // ["ocupabilidad", "cobranza", ...]
const [cargando, setCargando] = useState(true); const [cargando, setCargando] = useState(true);
// Cargar perfil (rol) y permisos del usuario logueado // Cargar perfil (rol) y permisos del usuario logueado.
// Nunca lanza: ante cualquier error devuelve false (evita que la app se cuelgue).
const cargarPerfil = useCallback(async (userId) => { const cargarPerfil = useCallback(async (userId) => {
// 1) Traer el rol del usuario desde la tabla "perfiles" try {
const { data: perf, error: e1 } = await supabase // 1) Traer el rol del usuario desde la tabla "perfiles"
.from("perfiles") const { data: perf, error: e1 } = await supabase
.select("nombre, rol, activo") .from("perfiles")
.eq("id", userId) .select("nombre, rol, activo")
.single(); .eq("id", userId)
.single();
if (e1 || !perf || perf.activo === false) { if (e1 || !perf || perf.activo === false) {
setPerfil(null);
setPermisos([]);
return false;
}
// 2) Traer los módulos permitidos para ese rol desde "permisos"
const { data: perms } = await supabase
.from("permisos")
.select("modulo, puede_ver")
.eq("rol", perf.rol);
const modulos = (perms || [])
.filter((p) => p.puede_ver)
.map((p) => p.modulo);
setPerfil({ nombre: perf.nombre, rol: perf.rol });
setPermisos(modulos);
return true;
} catch (e) {
console.error("[auth] cargarPerfil falló:", e);
setPerfil(null); setPerfil(null);
setPermisos([]); setPermisos([]);
return false; return false;
} }
// 2) Traer los módulos permitidos para ese rol desde "permisos"
const { data: perms } = await supabase
.from("permisos")
.select("modulo, puede_ver")
.eq("rol", perf.rol);
const modulos = (perms || [])
.filter((p) => p.puede_ver)
.map((p) => p.modulo);
setPerfil({ nombre: perf.nombre, rol: perf.rol });
setPermisos(modulos);
return true;
}, []); }, []);
// Al iniciar: revisar si ya hay sesión activa.
// Al iniciar: revisar si ya hay sesión activa // try/finally garantiza que "cargando" SIEMPRE se apague (aunque falle la red).
useEffect(() => { useEffect(() => {
let activo = true; let activo = true;
supabase.auth.getSession().then(async ({ data }) => { (async () => {
if (!activo) return; try {
const s = data?.session || null; const { data } = await supabase.auth.getSession();
setSession(s); if (!activo) return;
if (s?.user) await cargarPerfil(s.user.id); const s = data?.session || null;
setCargando(false); setSession(s);
}); if (s?.user) await cargarPerfil(s.user.id);
} catch (e) {
console.error("[auth] getSession falló:", e);
} finally {
if (activo) setCargando(false);
}
})();
// Escuchar cambios de sesión (login/logout) // Escuchar cambios de sesión (login/logout)
const { data: sub } = supabase.auth.onAuthStateChange(async (_evt, s) => { const { data: sub } = supabase.auth.onAuthStateChange(async (_evt, s) => {
setSession(s); try {
if (s?.user) await cargarPerfil(s.user.id); setSession(s);
else { setPerfil(null); setPermisos([]); } if (s?.user) await cargarPerfil(s.user.id);
else { setPerfil(null); setPermisos([]); }
} catch (e) {
console.error("[auth] onAuthStateChange falló:", e);
} finally {
if (activo) setCargando(false);
}
}); });
return () => { activo = false; sub?.subscription?.unsubscribe(); }; return () => { activo = false; sub?.subscription?.unsubscribe(); };
}, [cargarPerfil]); }, [cargarPerfil]);