modulo de autenticacion

This commit is contained in:
Brisa
2026-06-30 14:57:24 -03:00
parent d04a7ce69d
commit b960bd05d6
5 changed files with 615 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
<?php
session_start();
// Generar código aleatorio
$codigo = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 5);
$_SESSION['captcha'] = $codigo;
// Crear imagen
$imagen = imagecreatetruecolor(120, 40);
// Colores
$fondo = imagecolorallocate($imagen, 255, 255, 255);
$texto = imagecolorallocate($imagen, 0, 0, 0);
// Fondo blanco
imagefilledrectangle($imagen, 0, 0, 120, 40, $fondo);
// Escribir texto
imagestring($imagen, 5, 30, 10, $codigo, $texto);
// Tipo de imagen
header("Content-type: image/png");
// Mostrar imagen
imagepng($imagen);
imagedestroy($imagen);
?>
+178
View File
@@ -0,0 +1,178 @@
<?php
session_start();
include("db.php");
$error_msg = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
$captcha_ingresado = $_POST['captcha'];
// 1. Validamos captcha
if (strtolower($captcha_ingresado) != strtolower($_SESSION['captcha'])) {
escribir_log("Fallo de captcha: El usuario $email ingresó mal el código."); // <--- LOG
header("Location: login.php?error=captcha");
exit();
}
// Buscamos usuario
$stmt = $conexion->prepare("SELECT id_usuario, nombre, password, rol FROM usuarios WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$usuario = $result->fetch_assoc();
// Validamos contraseña hash
if (password_verify($password, $usuario['password'])) {
$_SESSION['id_usuario'] = $usuario['id_usuario'];
$_SESSION['usuario'] = $usuario['nombre'];
$_SESSION['rol'] = $usuario['rol'];
escribir_log("Login exitoso: " . $usuario['nombre'] . " (Rol: " . $usuario['rol'] . ")"); // <--- LOG
// Redirección inteligente según el Rol
if ($_SESSION['rol'] === 'admin') {
// Si es el dueño, directo a la cocina y estadísticas
header("Location: admin/dashboard.php");
} else {
// Si es un cliente de Paraná, directo a que compre algo rico
header("Location: index.php");
}
exit();
} else {
escribir_log("Contraseña incorrecta: Intento fallido para el email $email"); // <--- LOG
header("Location: login.php?error=password");
exit();
}
} else {
escribir_log("Usuario inexistente: Intento de login con email no registrado: $email"); // <--- LOG
header("Location: login.php?error=user");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Login - La Pecosa</title>
<link rel="stylesheet" href="css/all.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Roboto, sans-serif;
display: flex; justify-content: center; align-items: center;
height: 100vh; background-color: #fffef8; margin: 0;
}
.login-card {
background: white; padding: 50px 40px; border-radius: 20px;
text-align: center; width: 100%; max-width: 400px;
box-shadow: 0 10px 30px rgba(0,0,0,0.04);
border: 1px solid rgba(224, 40, 40, 0.05);
}
h2 {
color: #333; font-size: 1.8rem; font-weight: 800;
text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 30px;
}
h2::after {
content: ''; display: block; width: 45px; height: 4px;
background-color: #e02828; margin: 10px auto 0; border-radius: 2px;
}
input {
display: block; margin: 15px auto; padding: 15px; width: 100%;
border: none; background-color: #f8f9fa; border-radius: 10px; font-size: 1rem;
}
input:focus { outline: none; background-color: #ffffff; box-shadow: 0 0 0 2px rgba(224, 40, 40, 0.1); }
button[type="submit"] {
background: #e02828; color: white; border: none; padding: 15px;
width: 100%; cursor: pointer; border-radius: 50px; font-weight: 700;
text-transform: uppercase; margin-top: 15px; transition: 0.3s;
}
.captcha-box { background: #fdfdfd; padding: 20px; border-radius: 15px; border: 1px dashed #eee; margin: 20px 0; }
.btn-reload { background: transparent; color: #888; font-size: 13px; border: 1px solid #ddd; padding: 6px 15px; border-radius: 50px; cursor: pointer; margin-bottom: 10px; }
#msg-error {
background-color: #ffeaea; color: #e02828; font-size: 14px;
padding: 10px; border-radius: 8px; margin-bottom: 20px;
display: none; font-weight: 600;
}
.register-link { display: block; margin-top: 25px; font-size: 14px; color: #777; text-decoration: none; }
.register-link strong { color: #e02828; }
.olvido-link {
font-size: 13px;
color: #888;
text-decoration: none;
transition: 0.3s;
}
.olvido-link:hover {
color: #e02828;
}
</style>
</head>
<body>
<div class="login-card">
<h2>Login</h2>
<div id="msg-error"></div>
<form action="login.php" method="POST">
<input type="email" name="email" placeholder="Email" required autofocus>
<input type="password" name="password" placeholder="Contraseña" required>
<div style="text-align: right; width: 100%; margin-top: -10px; margin-bottom: 10px;">
<a href="recuperar_contraseña.php" class="olvido-link">¿Olvidaste tu contraseña?</a>
</div>
<div class="captcha-box">
<img src="captcha.php" id="captchaImg"><br>
<button type="button" class="btn-reload" onclick="recargarCaptcha()">
<i class="fa-solid fa-rotate"></i> Recargar
</button>
<input type="text" name="captcha" placeholder="Código" required
style="margin-bottom: 0; background: white; border: 1px solid #eee;">
</div>
<button type="submit">Entrar</button>
</form>
<a href="registro.php" class="register-link">
¿No tenés cuenta? <strong>Registrate gratis</strong>
</a>
</div>
<script>
function recargarCaptcha(){
document.getElementById("captchaImg").src = "captcha.php?v=" + Date.now();
}
const urlParams = new URLSearchParams(window.location.search);
const errorType = urlParams.get('error');
const mensajeType = urlParams.get('msj');
const errorDiv = document.getElementById('msg-error');
// Si hay un error de login (captcha, clave, etc)
if (errorType) {
errorDiv.style.display = 'block';
if (errorType === 'captcha') errorDiv.innerText = "¡Código Captcha incorrecto!";
if (errorType === 'password') errorDiv.innerText = "Email o contraseña incorrectos.";
if (errorType === 'user') errorDiv.innerText = "El usuario no existe.";
}
// Si viene del carrito por no estar logueado
if (mensajeType === 'debes_iniciar_sesion') {
errorDiv.style.display = 'block';
errorDiv.style.backgroundColor = "#fff4e5";
errorDiv.style.color = "#856404";
errorDiv.style.border = "1px solid #ffeeba";
errorDiv.innerText = "⚠️ ¡Hola! Para comprar en La Pecosa primero debés iniciar sesión.";
}
</script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<?php
include("db.php");
if (isset($_SESSION['usuario'])) {
escribir_log("Cierre de sesión: El usuario " . $_SESSION['usuario'] . " salió del sistema.");
}
session_unset();
session_destroy();
header("Location: index.php");
exit();
?>
+167
View File
@@ -0,0 +1,167 @@
<?php
session_start();
include("db.php");
$mensaje = "";
$tipo_mensaje = "";
$paso = 1;
if (isset($_SESSION['codigo_verificado'])) {
$paso = 3;
} elseif (isset($_SESSION['email_recuperacion'])) {
$paso = 2;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['btn_paso1'])) {
$email = $_POST['email'];
$stmt = $conexion->prepare("SELECT id_usuario FROM usuarios WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
$codigo = rand(100000, 999999);
$update = $conexion->prepare("UPDATE usuarios SET reset_codigo = ?, reset_expiracion = DATE_ADD(NOW(), INTERVAL 15 MINUTE) WHERE email = ?");
$update->bind_param("is", $codigo, $email);
if ($update->execute()) {
$apiKey = RESEND_API_KEY;
$datos_mail = [
"from" => "La Pecosa <onboarding@resend.dev>",
"to" => [$email],
"subject" => "Código de Recuperación - La Pecosa",
"html" => "
<div style='font-family: sans-serif; border: 1px solid #eee; padding: 20px; border-radius: 10px;'>
<h2 style='color: #e02828;'>Hola!</h2>
<p>Solicitaste restablecer tu contraseña en <strong>La Pecosa</strong>.</p>
<p style='font-size: 24px; font-weight: bold; color: #333; letter-spacing: 2px;'>$codigo</p>
<p style='color: #888; font-size: 12px;'>Este código vence en 15 minutos.</p>
</div>"
];
$ch = curl_init('https://api.resend.com/emails');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $apiKey, 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($datos_mail));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$respuesta = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code == 200 || $http_code == 201) {
$_SESSION['email_recuperacion'] = $email;
$tipo_mensaje = "exito";
$mensaje = "¡Código enviado! Revisá tu casilla de correo.";
$paso = 2;
escribir_log("Recuperación: Código enviado correctamente a $email");
} else {
$tipo_mensaje = "error";
$mensaje = "Error al enviar el mail.";
escribir_log("Error mail: Falló Resend para $email (HTTP $http_code)");
}
}
} else {
escribir_log("Alerta: Intento de recuperación para email NO registrado: $email");
$tipo_mensaje = "exito";
$mensaje = "Si el correo es correcto, recibirás un código.";
}
}
if (isset($_POST['btn_paso2'])) {
$codigo_ingresado = $_POST['codigo'];
$email = $_SESSION['email_recuperacion'];
$stmt = $conexion->prepare("SELECT id_usuario FROM usuarios WHERE email = ? AND reset_codigo = ? AND reset_expiracion > NOW()");
$stmt->bind_param("si", $email, $codigo_ingresado);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
$_SESSION['codigo_verificado'] = true;
$paso = 3;
escribir_log("Recuperación: Código verificado con éxito para $email");
} else {
$tipo_mensaje = "error";
$mensaje = "Código incorrecto o expirado.";
escribir_log("Alerta: Código INCORRECTO ingresado para $email");
}
}
if (isset($_POST['btn_paso3'])) {
$pass = $_POST['password'];
$confirm = $_POST['confirm_password'];
$email = $_SESSION['email_recuperacion'];
if ($pass === $confirm) {
$password_hash = password_hash($pass, PASSWORD_BCRYPT);
$update = $conexion->prepare("UPDATE usuarios SET password = ?, reset_codigo = NULL, reset_expiracion = NULL WHERE email = ?");
$update->bind_param("ss", $password_hash, $email);
if ($update->execute()) {
escribir_log("Recuperación exitosa: Contraseña actualizada para $email");
session_destroy();
header("Location: login.php?mensaje=actualizada");
exit();
}
} else {
$tipo_mensaje = "error";
$mensaje = "Las contraseñas no coinciden.";
}
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Recuperar Contraseña - La Pecosa</title>
<link rel="stylesheet" href="css/all.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Roboto, sans-serif; background-color: #fffef8; display: flex; justify-content: center; align-items: center; height: 100vh; }
.card { background: white; padding: 50px 40px; border-radius: 20px; text-align: center; width: 100%; max-width: 400px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); border: 1px solid rgba(224, 40, 40, 0.05); }
h2 { color: #333; font-size: 1.5rem; margin-bottom: 20px; text-transform: uppercase; letter-spacing: 1px; }
input { display: block; margin: 15px auto; padding: 15px; width: 100%; border: none; background-color: #f8f9fa; border-radius: 10px; font-size: 1rem; }
button { background: #e02828; color: white; border: none; padding: 15px; width: 100%; cursor: pointer; border-radius: 50px; font-weight: 700; margin-top: 10px; transition: 0.3s; }
.msg { padding: 12px; border-radius: 10px; margin-bottom: 20px; font-size: 14px; font-weight: 600; }
.msg-error { background-color: #ffeaea; color: #e02828; }
.msg-exito { background-color: #eaffea; color: #28a745; }
</style>
</head>
<body>
<div class="card">
<?php if ($mensaje): ?>
<div class="msg msg-<?php echo $tipo_mensaje; ?>"><?php echo $mensaje; ?></div>
<?php endif; ?>
<?php if ($paso == 1): ?>
<h2>Olvidé mi clave</h2>
<form method="POST">
<input type="email" name="email" placeholder="Tu email" required>
<button type="submit" name="btn_paso1">Enviar código</button>
</form>
<?php elseif ($paso == 2): ?>
<h2>Verificar Código</h2>
<p style="font-size: 14px; color: #666; margin-bottom: 15px;">Ingresá el código enviado a tu mail.</p>
<form method="POST">
<input type="number" name="codigo" placeholder="000000" required>
<button type="submit" name="btn_paso2">Verificar</button>
</form>
<?php elseif ($paso == 3): ?>
<h2>Nueva Contraseña</h2>
<form method="POST">
<input type="password" name="password" placeholder="Nueva contraseña" required>
<input type="password" name="confirm_password" placeholder="Confirmar contraseña" required>
<button type="submit" name="btn_paso3">Cambiar Contraseña</button>
</form>
<?php endif; ?>
<a href="login.php" style="display:block; margin-top:20px; font-size:14px; color:#e02828; text-decoration:none;">Volver al inicio</a>
</div>
</body>
</html>
+230
View File
@@ -0,0 +1,230 @@
<?php
include("db.php");
$mensaje = "";
$tipo_mensaje = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$nombre = trim($_POST['nombre']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$acepto_politicas = isset($_POST['acepto_politicas']) ? true : false;
$rol = "usuario";
// 1. Validamos políticas
if (!$acepto_politicas) {
$tipo_mensaje = "error";
$mensaje = "Debes aceptar las políticas de privacidad para registrarte.";
escribir_log("Registro fallido: Usuario no aceptó políticas (IP: " . $_SERVER['REMOTE_ADDR'] . ")");
}
// 2. Validamos contraseñas
elseif ($password !== $confirm_password) {
$tipo_mensaje = "error";
$mensaje = "Las contraseñas no coinciden.";
} else {
// 3. Verificamos si el email ya existe
$checkEmail = $conexion->prepare("SELECT id_usuario FROM usuarios WHERE email = ?");
$checkEmail->bind_param("s", $email);
$checkEmail->execute();
$res = $checkEmail->get_result();
if ($res->num_rows > 0) {
$tipo_mensaje = "error";
$mensaje = "El email ya está registrado.";
escribir_log("Intento de registro duplicado: El email $email ya existe.");
} else {
// 4. Encriptamos y guardamos
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $conexion->prepare("INSERT INTO usuarios (nombre, email, password, rol) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $nombre, $email, $password_hash, $rol);
if ($stmt->execute()) {
$tipo_mensaje = "exito";
$mensaje = "¡Registro exitoso! Ya podés iniciar sesión.";
escribir_log("Nuevo usuario: $nombre ha creado una cuenta ($email).");
} else {
$tipo_mensaje = "error";
$mensaje = "Error al registrar: " . $conexion->error;
escribir_log("Error crítico de registro " . $conexion->error);
}
}
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Registro - La Pecosa</title>
<link rel="stylesheet" href="css/all.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #fffef8;
margin: 0;
}
.register-card {
background: white;
padding: 50px 40px;
border-radius: 20px;
text-align: center;
width: 100%;
max-width: 400px;
box-shadow: 0 10px 30px rgba(0,0,0,0.04);
border: 1px solid rgba(224, 40, 40, 0.05);
}
h2 {
color: #333;
font-size: 1.8rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 1.5px;
margin-bottom: 30px;
}
h2::after {
content: '';
display: block;
width: 45px;
height: 4px;
background-color: #e02828;
margin: 10px auto 0;
border-radius: 2px;
}
.msg {
padding: 12px;
border-radius: 10px;
margin-bottom: 20px;
font-size: 14px;
font-weight: 600;
}
.msg-error { background-color: #ffeaea; color: #e02828; }
.msg-exito { background-color: #eaffea; color: #28a745; }
input {
display: block;
margin: 15px auto;
padding: 15px;
width: 100%;
border: none;
background-color: #f8f9fa;
border-radius: 10px;
font-size: 1rem;
transition: 0.3s;
}
input:focus {
outline: none;
background-color: #ffffff;
box-shadow: 0 0 0 2px rgba(224, 40, 40, 0.1);
}
button {
background: #e02828;
color: white;
border: none;
padding: 15px;
width: 100%;
cursor: pointer;
border-radius: 50px;
font-weight: 700;
font-size: 1rem;
text-transform: uppercase;
letter-spacing: 1px;
margin-top: 15px;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(224, 40, 40, 0.2);
}
button:hover {
background: #c71f1f;
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(224, 40, 40, 0.3);
}
.login-link {
display: block;
margin-top: 25px;
font-size: 14px;
color: #777;
text-decoration: none;
}
.login-link strong { color: #e02828; }
.input-error { border: 2px solid #e02828 !important; }
.input-success { border: 2px solid #28a745 !important; }
</style>
</head>
<body>
<div class="register-card">
<h2>Crear Cuenta</h2>
<?php if ($mensaje != ""): ?>
<div class="msg msg-<?php echo $tipo_mensaje; ?>">
<?php echo $mensaje; ?>
</div>
<?php endif; ?>
<form action="registro.php" method="POST" id="registroForm">
<input type="text" name="nombre" placeholder="Nombre completo" required>
<input type="email" name="email" placeholder="Correo electrónico" required>
<input type="password" name="password" id="password" placeholder="Crear contraseña" required>
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirmar contraseña" required>
<div style="text-align: left; margin: 20px 0; font-size: 13px; color: #666; display: flex; align-items: flex-start; gap: 10px;">
<input type="checkbox" name="acepto_politicas" id="acepto_politicas" required
style="width: 18px; height: 18px; margin: 0; cursor: pointer; accent-color: #e02828;">
<label for="acepto_politicas" style="cursor: pointer; line-height: 1.4;">
Acepto las <a href="privacidad.php" target="_blank" style="color: #e02828; text-decoration: none; font-weight: 700;">Políticas de Privacidad</a>
y el uso de mi ubicación para envíos.
</label>
</div>
<button type="submit">Registrarme</button>
</form>
<a href="login.php" class="login-link">
¿Ya tenés cuenta? <strong>Iniciá sesión acá</strong>
</a>
</div>
<script>
const pass = document.getElementById('password');
const confirmPass = document.getElementById('confirm_password');
function validarContraseñas() {
if (confirmPass.value === "") {
confirmPass.classList.remove('input-error', 'input-success');
return;
}
if (pass.value !== confirmPass.value) {
confirmPass.classList.add('input-error');
confirmPass.classList.remove('input-success');
} else {
confirmPass.classList.add('input-success');
confirmPass.classList.remove('input-error');
}
}
confirmPass.addEventListener('input', validarContraseñas);
pass.addEventListener('input', validarContraseñas);
</script>
</body>
</html>