File size: 4,060 Bytes
564baf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b225792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a2f2fa
 
564baf9
 
 
 
 
 
 
 
 
1a3d3dd
 
 
 
 
 
 
 
 
564baf9
1a3d3dd
 
 
 
 
 
 
 
564baf9
1a3d3dd
 
 
564baf9
1a3d3dd
 
 
 
 
 
 
564baf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { createContext, useContext, useEffect, useState } from 'react';
import { auth, db } from '../firebase/config';
import { onAuthStateChanged, signInWithEmailAndPassword, signOut } from 'firebase/auth';
import { ref, get } from 'firebase/database';

export const AuthContext = createContext();

export const useAuth = () => {
  return useContext(AuthContext);
};

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [userRole, setUserRole] = useState(null);
  const [loading, setLoading] = useState(true);

  const login = async (email, password) => {
    // Manejo de cuentas Demo para facilitar el acceso
    const isDemoAdmin = email === 'admin@rest-os.com' && password === 'admin-password123';
    const isDemoWaiter = (email === 'mesero@rest-os.com' && password === 'mesero-password123') || (email === 'mesero@rest-os.com' && password === 'waiter-password123');

    if (isDemoAdmin || isDemoWaiter) {
      const { signInWithEmailAndPassword, createUserWithEmailAndPassword } = await import('firebase/auth');
      try {
        // Intentar login real para obtener token de Firebase
        const res = await signInWithEmailAndPassword(auth, email, password);
        return res.user;
      } catch (error) {
        if (error.code === 'auth/user-not-found' || error.code === 'auth/invalid-credential' || error.code === 'auth/invalid-email') {
          try {
            // Si no existe, crear el usuario en Firebase automáticamente
            const res = await createUserWithEmailAndPassword(auth, email, password);
            // Registrar rol en DB para que el sistema lo reconozca
            const { set, ref: dbRef } = await import('firebase/database');
            await set(dbRef(db, `users/${res.user.uid}`), {
              name: isDemoAdmin ? 'Admin Demo' : 'Mesero Demo',
              email: email,
              role: isDemoAdmin ? 'admin' : 'mesero'
            });
            return res.user;
          } catch (createError) {
            console.error("Error creando usuario demo en Firebase", createError);
            // Fallback a objeto mock si falla la creación (ej. reglas de seguridad de Auth)
            const mockUser = { uid: isDemoAdmin ? 'demo-admin-uid' : 'demo-mesero-uid', email, isDemo: true };
            setCurrentUser(mockUser);
            setUserRole(isDemoAdmin ? 'admin' : 'mesero');
            return mockUser;
          }
        }
        throw error;
      }
    }

    return signInWithEmailAndPassword(auth, email, password);
  };

  const logout = () => {
    return signOut(auth);
  };

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      try {
        if (user) {
          setCurrentUser(user);
          
          // Si es un usuario demo, asignar rol directamente sin consultar DB (evita permission_denied)
          if (user.email === 'admin@rest-os.com') {
            setUserRole('admin');
          } else if (user.email === 'mesero@rest-os.com') {
            setUserRole('mesero');
          } else {
            // Obtener rol del usuario desde DB para usuarios reales
            const userRef = ref(db, `users/${user.uid}`);
            const snapshot = await get(userRef);
            if (snapshot.exists()) {
              setUserRole(snapshot.val().role);
            } else {
              setUserRole('comensal'); 
            }
          }
        } else {
          setCurrentUser(null);
          setUserRole(null);
        }
      } catch (error) {
        console.error("Error al obtener el rol del usuario", error);
        // Fallback en caso de error
        if (user && user.email === 'admin@rest-os.com') setUserRole('admin');
        else setUserRole('comensal');
      } finally {
        setLoading(false);
      }
    });

    return unsubscribe;
  }, []);

  const value = {
    currentUser,
    userRole,
    login,
    logout
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
};