File "AuthController.php"
Full Path: C:/wamp64/www/Seleccion/controllers/AuthController.php
File size: 6.96 KB
MIME-type: text/x-php
Charset: utf-8
<?php
// controllers/AuthController.php
require_once __DIR__ . '/../models/UsuarioModel.php';
require_once __DIR__ . '/../config/Database.php';
class AuthController {
private $db;
private $usuarioModel;
// ⚠️ IMPORTANTE: Usa tu clave secreta correcta
private $recaptchaSecret = '6LcUafsrAAAAAL2xMNSvimYvzrMlC3YFSgUJGQPx';
public function __construct() {
$database = new Database();
$this->db = $database->connect();
$this->usuarioModel = new Usuario($this->db);
}
// Mostrar el formulario de login
public function index() {
// Si ya está logueado, redirigir al panel
if(isset($_SESSION['user_id'])) {
header('Location: index.php?controller=requisicion&action=panel');
exit;
}
require_once __DIR__ . '/../views/autenticacion/login.php';
}
// Procesar el login
public function login() {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$cedula = trim($_POST['cedula'] ?? '');
$password = $_POST['password'] ?? '';
$recaptchaResponse = $_POST['g-recaptcha-response'] ?? '';
// 1. VALIDAR QUE LOS CAMPOS NO ESTÉN VACÍOS
if(empty($cedula) || empty($password)) {
$_SESSION['flash_error'] = "Por favor complete todos los campos.";
header('Location: index.php?controller=auth&action=index');
exit;
}
// 2. VALIDAR reCAPTCHA PRIMERO
if(empty($recaptchaResponse)) {
$_SESSION['flash_error'] = "Por favor complete el reCAPTCHA correctamente.";
header('Location: index.php?controller=auth&action=index');
exit;
}
// 3. VERIFICAR EL reCAPTCHA CON GOOGLE
if(!$this->validarRecaptcha($recaptchaResponse)) {
$_SESSION['flash_error'] = "La verificación de seguridad falló. Por favor, inténtalo de nuevo.";
header('Location: index.php?controller=auth&action=index');
exit;
}
// 4. INTENTAR AUTENTICAR (solo si el reCAPTCHA es válido)
if($this->usuarioModel->autenticar($cedula, $password)) {
// Crear variables de sesión
$_SESSION['user_id'] = $this->usuarioModel->id;
$_SESSION['user_nombre'] = $this->usuarioModel->nombre;
$_SESSION['user_cedula'] = $this->usuarioModel->cedula;
$_SESSION['user_rol'] = $this->usuarioModel->rol;
$_SESSION['login_time'] = time();
// Regenerar ID de sesión para seguridad
session_regenerate_id(true);
// Redireccionar al panel
header('Location: index.php?controller=requisicion&action=panel');
exit;
} else {
// Error de login
$_SESSION['flash_error'] = "Cédula o contraseña incorrectos.";
header('Location: index.php?controller=auth&action=index');
exit;
}
} else {
// Si no es POST, redirigir al formulario
header('Location: index.php?controller=auth&action=index');
exit;
}
}
// Cerrar sesión
public function logout() {
// Limpiar todas las variables de sesión
$_SESSION = array();
// Destruir la cookie de sesión
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-3600, '/');
}
// Destruir la sesión
session_destroy();
// Redirigir al login
header('Location: index.php?controller=auth&action=index');
exit;
}
// Validar reCAPTCHA con Google (método mejorado)
private function validarRecaptcha($response) {
if(empty($response)) {
error_log("reCAPTCHA: Response vacío");
return false;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = [
'secret' => $this->recaptchaSecret,
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']
];
// Usar cURL en lugar de file_get_contents (más confiable)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
error_log("reCAPTCHA cURL error: " . curl_error($ch));
curl_close($ch);
// Fallback: intentar con file_get_contents
return $this->validarRecaptchaFallback($response);
}
curl_close($ch);
if($httpcode !== 200) {
error_log("reCAPTCHA HTTP error: " . $httpcode);
return false;
}
$resultJson = json_decode($result);
if($resultJson === null) {
error_log("reCAPTCHA: Error al decodificar JSON");
return false;
}
// Log para debugging
if(!$resultJson->success) {
error_log("reCAPTCHA falló. Errores: " . json_encode($resultJson->{'error-codes'} ?? []));
}
return $resultJson->success ?? false;
}
// Método alternativo usando file_get_contents
private function validarRecaptchaFallback($response) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = [
'secret' => $this->recaptchaSecret,
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
'timeout' => 10
]
];
$context = stream_context_create($options);
$result = @file_get_contents($url, false, $context);
if($result === false) {
error_log("reCAPTCHA fallback: file_get_contents falló");
return false;
}
$resultJson = json_decode($result);
if(!$resultJson->success) {
error_log("reCAPTCHA fallback falló. Errores: " . json_encode($resultJson->{'error-codes'} ?? []));
}
return $resultJson->success ?? false;
}
}
?>