175 lines
4.9 KiB
PHP
175 lines
4.9 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Core\Database;
|
|
use App\Core\HttpHelper;
|
|
|
|
use App\Repositories\UserRepository;
|
|
use Firebase\JWT\JWT;
|
|
use Firebase\JWT\Key;
|
|
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
|
|
class AuthController extends BaseController
|
|
{
|
|
protected $userRepository;
|
|
private $jwtSecret;
|
|
|
|
public function __construct()
|
|
{
|
|
$database = new Database();
|
|
$this->userRepository = new UserRepository($database);
|
|
$this->jwtSecret = $_ENV["JWT_SECRET"];
|
|
}
|
|
|
|
public function showLogin()
|
|
{
|
|
$this->render("auth/login");
|
|
}
|
|
|
|
public function login(Request $request)
|
|
{
|
|
$email = HttpHelper::getParam(
|
|
$request,
|
|
"email",
|
|
null,
|
|
FILTER_SANITIZE_EMAIL
|
|
);
|
|
$password = HttpHelper::getParam($request, "password");
|
|
|
|
$user = $this->userRepository->findBy("email", $email);
|
|
|
|
if (!$user) {
|
|
$this->render("auth/login", [
|
|
"error" => "Credenciales incorrectas",
|
|
]);
|
|
return;
|
|
}
|
|
|
|
if (!password_verify($password, $user["password_hash"])) {
|
|
$this->render("auth/login", ["error" => "Contraseña incorrecta"]);
|
|
return;
|
|
}
|
|
|
|
$payload = [
|
|
"user_id" => $user["user_id"],
|
|
"email" => $user["email"],
|
|
"exp" => time() + 60 * 60, // Expiración de 1 hora
|
|
];
|
|
|
|
$jwt = JWT::encode($payload, $this->jwtSecret, "HS256");
|
|
|
|
setcookie("jwt", $jwt, time() + 60 * 60, "/", "", false, true);
|
|
|
|
header("Location: /home");
|
|
}
|
|
|
|
public function showRegister()
|
|
{
|
|
$this->render("auth/register");
|
|
}
|
|
|
|
public function register(Request $request)
|
|
{
|
|
$username = HttpHelper::getParam($request, "username");
|
|
$email = HttpHelper::getParam(
|
|
$request,
|
|
"email",
|
|
null,
|
|
FILTER_SANITIZE_EMAIL
|
|
);
|
|
$passwordPlain = HttpHelper::getParam($request, "password");
|
|
$errors = []; // Guardar errores
|
|
|
|
$validations = [
|
|
"username" => [
|
|
"required" => true,
|
|
"message" => "El nombre de usuario es obligatorio.",
|
|
],
|
|
"email" => [
|
|
"required" => true,
|
|
"message" => "El correo electrónico es obligatorio.",
|
|
"validate" => function ($value) {
|
|
return filter_var($value, FILTER_VALIDATE_EMAIL)
|
|
? null
|
|
: "El correo electrónico no es válido.";
|
|
},
|
|
],
|
|
"password" => [
|
|
"required" => true,
|
|
"message" => "La contraseña es obligatoria.",
|
|
"minLength" => 8,
|
|
"lengthMessage" =>
|
|
"La contraseña debe tener al menos 8 caracteres.",
|
|
],
|
|
];
|
|
|
|
$inputData = [
|
|
"username" => $username,
|
|
"email" => $email,
|
|
"password" => $passwordPlain,
|
|
];
|
|
|
|
foreach ($validations as $key => $rules) {
|
|
$value = $inputData[$key] ?? null;
|
|
|
|
if ($rules["required"] && empty($value)) {
|
|
$errors[$key] = $rules["message"];
|
|
continue;
|
|
}
|
|
|
|
if (
|
|
isset($rules["minLength"]) &&
|
|
!is_null($value) &&
|
|
strlen($value) < $rules["minLength"]
|
|
) {
|
|
$errors[$key] = $rules["lengthMessage"];
|
|
}
|
|
|
|
if (isset($rules["validate"]) && empty($errors[$key])) {
|
|
$customError = $rules["validate"]($value);
|
|
if ($customError) {
|
|
$errors[$key] = $customError;
|
|
}
|
|
}
|
|
|
|
if ($key === "email" && empty($errors[$key])) {
|
|
$existingUser = $this->userRepository->findBy("email", $email);
|
|
if ($existingUser) {
|
|
$errors[$key] =
|
|
"El correo electrónico ya está registrado. Por favor, utiliza otro correo o inicia sesión.";
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!empty($errors)) {
|
|
$this->render("auth/register", [
|
|
"errors" => $errors,
|
|
"old" => ["username" => $username, "email" => $email],
|
|
]);
|
|
return;
|
|
}
|
|
|
|
// Continuar con el registro
|
|
$password = password_hash($passwordPlain, PASSWORD_DEFAULT);
|
|
|
|
$userData = [
|
|
"username" => $username,
|
|
"email" => $email,
|
|
"password_hash" => $password,
|
|
];
|
|
|
|
$this->userRepository->insert($userData);
|
|
$this->render("auth/register", [
|
|
"success" => "Usuario registrado con éxito.",
|
|
]);
|
|
}
|
|
|
|
public function logout()
|
|
{
|
|
setcookie("jwt", "", time() - 3600, "/"); // Eliminar la cookie JWT
|
|
header("Location: /login");
|
|
}
|
|
}
|