Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.33% covered (warning)
83.33%
45 / 54
87.50% covered (warning)
87.50%
7 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
UserController
83.33% covered (warning)
83.33%
45 / 54
87.50% covered (warning)
87.50%
7 / 8
17.19
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hashPassword
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 verifyPassword
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 registerUser
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
3
 loginUser
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 logout
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 getUserById
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 register
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Controllers;
3
4use Models\User;
5
6class UserController {
7    private $conn;
8    private const HASH_COST = 12; // Costo de hash para password_hash
9
10    public function __construct($conn) {
11        $this->conn = $conn;
12    }
13
14    private function hashPassword($password) {
15        return password_hash($password, PASSWORD_BCRYPT, ['cost' => self::HASH_COST]);
16    }
17
18    private function verifyPassword($password, $hashedPassword) {
19        return password_verify($password, $hashedPassword);
20    }
21
22    public function registerUser($userData) {
23        try {
24            $user = new User();
25            $user->setName($userData['name']);
26            $user->setEmail($userData['email']);
27            $user->setUserType($userData['user_type'] ?? 'user');
28
29            // Verificar si el correo ya existe
30            $stmt = $this->conn->prepare("SELECT id FROM users WHERE email = ?");
31            $stmt->execute([$user->getEmail()]);
32            if($stmt->fetch()) {
33                return ['success' => false, 'message' => 'El correo ya está registrado'];
34            }
35
36            // Usar password_hash en lugar de md5
37            $stmt = $this->conn->prepare(
38                "INSERT INTO users (name, email, password, user_type) 
39                 VALUES (?, ?, ?, ?)"
40            );
41            
42            $stmt->execute([
43                $user->getName(),
44                $user->getEmail(),
45                $this->hashPassword($userData['password']),
46                $user->getUserType()
47            ]);
48            
49            return ['success' => true, 'message' => 'Registro exitoso!'];
50        } catch (\Exception $e) {
51            error_log("Error en registro: " . $e->getMessage());
52            return ['success' => false, 'message' => 'Error en el registro'];
53        }
54    }
55
56    public function loginUser($email, $password) {
57        try {
58            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
59            $stmt->execute([$email]);
60            $user = $stmt->fetch(\PDO::FETCH_ASSOC);
61
62            if ($user && $this->verifyPassword($password, $user['password'])) {
63                $_SESSION['user_id'] = $user['id'];
64                $_SESSION['user_name'] = $user['name'];
65                $_SESSION['user_type'] = $user['user_type'];
66                $_SESSION['user_email'] = $user['email'];
67                return ['success' => true, 'user_type' => $user['user_type']];
68            }
69
70            return ['success' => false, 'message' => 'Correo o contraseña incorrectos'];
71        } catch (\Exception $e) {
72            error_log("Error en login: " . $e->getMessage());
73            return ['success' => false, 'message' => 'Error en el inicio de sesión'];
74        }
75    }
76
77    public function logout() {
78        try {
79            // Asegurarse de que la sesión está iniciada
80            if (session_status() === PHP_SESSION_NONE) {
81                session_start();
82            }
83            
84            // Limpiar todas las variables de sesión
85            $_SESSION = array();
86            
87            // Destruir la sesión
88            session_destroy();
89            
90            // Redireccionar al login
91            header('location: ../auth/login.php');
92            exit();
93        } catch (\Exception $e) {
94            error_log("Error en logout: " . $e->getMessage());
95            return ['success' => false, 'message' => 'Error al cerrar sesión'];
96        }
97    }
98
99    public function getUserById($userId) {
100        try {
101            $stmt = $this->conn->prepare("SELECT id, name, email, user_type FROM users WHERE id = ?");
102            $stmt->execute([$userId]);
103            return $stmt->fetch(\PDO::FETCH_ASSOC);
104        } catch (\Exception $e) {
105            error_log("Error al obtener usuario: " . $e->getMessage());
106            return null;
107        }
108    }
109
110    // Alias para mantener compatibilidad
111    public function register($userData) {
112        return $this->registerUser($userData);
113    }
114}