Overview
Mis Compras implements a secure authentication system that handles user registration, login, and session management. The system uses PHP for backend processing with password hashing and localStorage for client-side session persistence.
Key Features
User Registration Create new accounts with email validation and password encryption
Secure Login Authenticate users with bcrypt password verification
Session Management Maintain user sessions using PHP sessions and localStorage
Password Security Passwords are hashed using PHP’s password_hash function
Database Schema
The authentication system uses the usuarios table:
CREATE TABLE ` usuarios ` (
`id_usuario` int NOT NULL AUTO_INCREMENT,
`nombre` varchar ( 100 ) NOT NULL ,
`email` varchar ( 100 ) NOT NULL UNIQUE ,
`contrasena` varchar ( 255 ) NOT NULL ,
`fecha_registro` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `id_usuario` )
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
User Registration
Registration Flow
User submits registration form
The form collects name, email, and password from the user
Server validates input
PHP backend checks for required fields and duplicate emails
Password is hashed
The password is encrypted using PASSWORD_DEFAULT algorithm
User record is created
New user data is inserted into the database
Backend Implementation
The registration endpoint (php/registro.php) handles user creation:
<? php
include '../conexion.php' ;
if ( $_SERVER [ "REQUEST_METHOD" ] === "POST" ) {
$nombre = $_POST [ "nombre" ] ?? '' ;
$email = $_POST [ "email" ] ?? '' ;
$contrasena = $_POST [ "contrasena" ] ?? '' ;
if ( empty ( $nombre ) || empty ( $email ) || empty ( $contrasena )) {
echo json_encode ([ "success" => false , "message" => "⚠️ Faltan campos." ]);
exit ;
}
// Encrypt password
$hash = password_hash ( $contrasena , PASSWORD_DEFAULT );
// Check for duplicate email
$verificar = $conn -> prepare ( " SELECT id_usuario FROM usuarios WHERE email = ?" );
$verificar -> bind_param ( "s" , $email );
$verificar -> execute ();
$verificar -> store_result ();
if ( $verificar -> num_rows > 0 ) {
echo json_encode ([ "success" => false , "message" => "⚠️ Este correo ya está registrado." ]);
exit ;
}
// Insert new user
$sql = $conn -> prepare ( " INSERT INTO usuarios (nombre, email, contrasena) VALUES (?, ?, ?)" );
$sql -> bind_param ( "sss" , $nombre , $email , $hash );
if ( $sql -> execute ()) {
echo json_encode ([ "success" => true , "message" => "🎉 ¡Registro exitoso!" ]);
} else {
echo json_encode ([ "success" => false , "message" => "❌ Error al registrar el usuario." ]);
}
}
?>
The system uses password_hash() with PASSWORD_DEFAULT, which currently uses bcrypt and automatically handles salt generation.
User Login
Login Flow
User submits credentials
Email and password are sent via POST request
Server looks up user
Database is queried for the provided email
Password verification
password_verify() compares the input with stored hash
Session is created
User data is stored in PHP session and returned to client
Client stores session
User ID and name are saved in localStorage
Backend Implementation
The login endpoint (php/login.php) authenticates users:
<? php
header ( 'Content-Type: application/json' );
include '../conexion.php' ;
if ( $_SERVER [ "REQUEST_METHOD" ] === "POST" ) {
$email = $_POST [ "email" ] ?? '' ;
$contrasena = $_POST [ "contrasena" ] ?? '' ;
if ( empty ( $email ) || empty ( $contrasena )) {
echo json_encode ([ "éxito" => false , "mensaje" => "Faltan campos." ]);
exit ;
}
$stmt = $conn -> prepare ( " SELECT id_usuario, contrasena, nombre FROM usuarios WHERE email = ?" );
$stmt -> bind_param ( "s" , $email );
$stmt -> execute ();
$resultado = $stmt -> get_result ();
if ( $resultado -> num_rows === 1 ) {
$usuario = $resultado -> fetch_assoc ();
if ( password_verify ( $contrasena , $usuario [ "contrasena" ])) {
// Create session
session_start ();
$_SESSION [ "id_usuario" ] = $usuario [ "id_usuario" ];
$_SESSION [ "nombre" ] = $usuario [ "nombre" ];
echo json_encode ([
"éxito" => true ,
"mensaje" => "Inicio de sesión exitoso" ,
"usuario" => [
"id" => $usuario [ "id_usuario" ],
"nombre" => $usuario [ "nombre" ]
]
]);
} else {
echo json_encode ([ "éxito" => false , "mensaje" => "Contraseña incorrecta." ]);
}
} else {
echo json_encode ([ "éxito" => false , "mensaje" => "Correo no registrado." ]);
}
}
?>
Frontend Implementation
The client-side login handler (login.js) manages the authentication flow:
document . addEventListener ( "DOMContentLoaded" , () => {
const formLogin = document . getElementById ( "form-login" );
formLogin . addEventListener ( "submit" , async ( e ) => {
e . preventDefault ();
const formData = new FormData ( formLogin );
try {
const response = await fetch ( "php/login.php" , {
method: "POST" ,
body: formData ,
});
const text = await response . text ();
let data = JSON . parse ( text );
// If login successful
if ( data . éxito || data . success ) {
const usuario = data . usuario || {};
// Save to localStorage
localStorage . setItem ( "id_usuario" , usuario . id );
localStorage . setItem ( "nombre_usuario" , usuario . nombre );
// Redirect to profile
setTimeout (() => {
window . location . href = "perfil.html" ;
}, 2500 );
} else {
alert ( data . mensaje || "❌ Error al iniciar sesión." );
}
} catch ( error ) {
console . error ( "❌ Error en login:" , error );
alert ( "Error de conexión con el servidor." );
}
});
});
Session Management
Storage Strategy
The platform uses a dual-storage approach for session management:
Server-side : PHP sessions store user ID and name
Client-side : localStorage persists authentication state across page loads
Accessing Current User
To retrieve the logged-in user in JavaScript:
const id_usuario = localStorage . getItem ( "id_usuario" );
const nombre_usuario = localStorage . getItem ( "nombre_usuario" );
if ( ! id_usuario ) {
// User not logged in - redirect to login
window . location . href = "login.html" ;
}
Protected Pages
Pages that require authentication check for the user session:
document . addEventListener ( "DOMContentLoaded" , () => {
const id_usuario = localStorage . getItem ( "id_usuario" );
if ( ! id_usuario ) {
alert ( "No has iniciado sesión." );
window . location . href = "login.html" ;
return ;
}
// Load user data
fetch ( "php/obtener_usuario.php?id=" + id_usuario )
. then ( res => res . json ())
. then ( data => {
const usuario = data . usuario || {};
document . getElementById ( "nombre" ). textContent = usuario . nombre || "" ;
document . getElementById ( "email" ). textContent = usuario . email || "" ;
document . getElementById ( "fecha" ). textContent = usuario . fecha_registro || "" ;
});
});
Security Considerations
Important security measures implemented in the authentication system:
Password Hashing : All passwords are hashed using bcrypt before storage
Prepared Statements : SQL queries use prepared statements to prevent injection attacks
Email Uniqueness : The system prevents duplicate email registrations
Input Validation : All user inputs are validated before processing
CORS Headers : API endpoints include appropriate CORS headers for security
API Reference
POST /php/registro.php
Register a new user account.
Request Body:
nombre (string, required): User’s full name
email (string, required): User’s email address
contrasena (string, required): User’s password
Response:
{
"success" : true ,
"message" : "🎉 ¡Registro exitoso!"
}
POST /php/login.php
Authenticate an existing user.
Request Body:
email (string, required): User’s email address
contrasena (string, required): User’s password
Response:
{
"éxito" : true ,
"mensaje" : "Inicio de sesión exitoso" ,
"usuario" : {
"id" : 17 ,
"nombre" : "John Doe"
}
}
GET /php/obtener_usuario.php
Retrieve user profile information.
Query Parameters:
id (integer, required): User ID
Response:
{
"usuario" : {
"nombre" : "John Doe" ,
"email" : "[email protected] " ,
"fecha_registro" : "2025-11-12 00:35:50"
}
}
Next Steps
Product Management Learn how to create and manage product listings
Shopping Cart Explore the shopping cart functionality