Skip to main content

Overview

The User Management system handles operator accounts that access the Canchas Deportivas platform. Users are the internal staff who manage fields, clients, and reservations.

User Entity

Users are represented by the CE_usuarios entity:
capa_entidad/CE_Usuarios.cs
public class CE_usuarios
{
    public int IdUsuario { get; set; }
    public string? Nombre { get; set; }
    public string? Clave { get; set; }
    public bool Estado { get; set; }
}
The entity stores user credentials with a password field (Clave) and active status tracking.

Business Logic Layer

The business layer provides validation and CRUD operations:
capa_negocio/CN_Usuarios.cs
public class CN_Usuarios
{
    CD_Usuarios oCD_Usuarios = new CD_Usuarios();

    public List<CE_usuarios> Listar()
    {
        try
        {
            return oCD_Usuarios.ListarUsuarios();
        }
        catch (Exception ex)
        {
            throw new Exception("Error al obtener la lista de usuarios: " + ex.Message);
        }
    }
}

Create a New User

The Insertar method includes comprehensive validation:
capa_negocio/CN_Usuarios.cs
public void Insertar(CE_usuarios usuario)
{
    // Validate username
    if (string.IsNullOrWhiteSpace(usuario.Nombre))
    {
        throw new ArgumentException("El nombre de usuario no puede estar vacío.");
    }
    
    // Validate password exists
    if (string.IsNullOrWhiteSpace(usuario.Clave))
    {
        throw new ArgumentException("La contraseña es obligatoria.");
    }

    // Validate password length
    if (usuario.Clave.Length < 6)
    {
        throw new ArgumentException("La contraseña debe tener al menos 6 caracteres.");
    }

    try
    {
        oCD_Usuarios.InsertarUsuarios(usuario);
    }
    catch (Exception ex)
    {
        throw new Exception("Error al insertar el usuario: " + ex.Message);
    }
}
Password validation requires a minimum of 6 characters. Consider implementing additional security measures like password hashing in production.

Validation Rules

1

Username Validation

Username cannot be null, empty, or whitespace only.
if (string.IsNullOrWhiteSpace(usuario.Nombre))
{
    throw new ArgumentException("El nombre de usuario no puede estar vacío.");
}
2

Password Required

Password must be provided when creating a new user.
if (string.IsNullOrWhiteSpace(usuario.Clave))
{
    throw new ArgumentException("La contraseña es obligatoria.");
}
3

Password Length

Password must be at least 6 characters long.
if (usuario.Clave.Length < 6)
{
    throw new ArgumentException("La contraseña debe tener al menos 6 caracteres.");
}

Update User Information

The update method validates the user ID and username:
capa_negocio/CN_Usuarios.cs
public void Actualizar(CE_usuarios usuario)
{
    // Validate user ID
    if (usuario.IdUsuario <= 0)
    {
        throw new ArgumentException("Se requiere un ID de Usuario válido para actualizar.");
    }

    // Validate username
    if (string.IsNullOrWhiteSpace(usuario.Nombre))
    {
        throw new ArgumentException("El nombre de usuario no puede estar vacío.");
    }

    try
    {
        oCD_Usuarios.ActualizarUsuarios(usuario);
    }
    catch (Exception ex)
    {
        throw new Exception("Error al actualizar el usuario: " + ex.Message);
    }
}
The update method does not re-validate password length, allowing users to keep their existing passwords.

Delete a User

The delete operation validates the user ID:
capa_negocio/CN_Usuarios.cs
public void Eliminar(int idUsuario)
{
    // Validate user ID
    if (idUsuario <= 0)
    {
        throw new ArgumentException("Se requiere un ID de Usuario para eliminar.");
    }

    try
    {
        oCD_Usuarios.EliminarUsuarios(idUsuario);
    }
    catch (Exception ex)
    {
        throw new Exception("Error al eliminar el usuario: " + ex.Message);
    }
}
Be cautious when deleting users who may have created reservations. Consider soft deletion or status changes instead.

User Tracking in Reservations

Users are tracked in the reservation system through the IdUsuario field:
capa_entidad/CE_Reservas.cs
public class CE_Reservas
{
    public int IdReserva { get; set; }
    public int IdCancha { get; set; }
    public int IdCliente { get; set; }
    public int IdUsuario { get; set; }  // Operator who created the reservation
    // ... other properties
}
In the reservation form, the user ID is typically set to the logged-in operator:
Views/Reservas/InsertarReservas.cshtml
<div class="mb-3">
    <label asp-for="Reserva.IdUsuario" class="form-label fw-bold">
        Usuario (Operador)
    </label>
    <div class="input-group">
        <span class="input-group-text">
            <i class="bi bi-person-badge-fill"></i>
        </span>
        <input asp-for="Reserva.IdUsuario" value="1" 
               class="form-control" readonly 
               style="background-color: #e9ecef;" />
    </div>
</div>
The current implementation sets a default user ID. In a production system, this should be dynamically set based on the authenticated user’s session.

Error Handling Pattern

All user management operations follow a consistent error handling pattern:
try
{
    // Perform operation
    oCD_Usuarios.InsertarUsuarios(usuario);
}
catch (Exception ex)
{
    throw new Exception("Error al insertar el usuario: " + ex.Message);
}

Security Considerations

The following security enhancements should be implemented for production use:

Password Hashing

Store hashed passwords instead of plain text using bcrypt or similar.

Authentication

Implement proper login/logout functionality with session management.

Authorization

Add role-based access control to restrict actions based on user permissions.

Password Policies

Enforce stronger password requirements including special characters and numbers.

User State Management

The Estado boolean property tracks whether a user account is active:
public bool Estado { get; set; }
This allows for soft deletion or temporary deactivation of user accounts without removing their historical data from reservations.

Integration with System

Users integrate with the broader system through:
  • Reservations: Track which operator created each booking
  • Audit Trail: Maintain accountability for data changes
  • Access Control: Determine who can perform various operations

User Workflow

1

Create User Account

Administrator creates a new user account with username and password.
2

Validate Credentials

System validates password meets minimum requirements.
3

Activate Account

User account is set to active status upon creation.
4

Perform Operations

User logs in and performs field, client, and reservation management tasks.
5

Track Actions

All reservations created by the user are tracked via IdUsuario.

Best Practices

When implementing user management in production:
  • Use a proven authentication library or framework
  • Implement password hashing with salt
  • Add login attempt limiting to prevent brute force attacks
  • Use HTTPS to protect credentials in transit
  • Implement proper session timeout mechanisms
  • Log all authentication and authorization events

Next Steps

Reservation System

See how users track reservations they create

Architecture Overview

Understand the three-tier architecture

Build docs developers (and LLMs) love