Skip to main content

Overview

The Users API provides endpoints for user account management, including registration, profile updates, password changes, and account deletion. Base URL: /api/usuarios Source: UsuarioController.java

Authentication

  • Public endpoints: User registration (POST /api/usuarios/register)
  • Authenticated endpoints: View/update own profile, change password, delete account
  • Admin endpoints: List all users - requires ROLE_ADMIN

Endpoints

Register User

POST /api/usuarios/register
Register a new user account. The system automatically generates a verification token and sends an activation email. Authentication: None (public endpoint) Request Body:
nombre
string
required
User’s first name
apellido
string
required
User’s last name
email
string
required
User’s email address (must be unique)
password
string
required
User’s password (will be encrypted with BCrypt)
telefono
string
Phone number
direccion
string
Default shipping address
Example Request:
cURL
curl -X POST http://localhost:8080/api/usuarios/register \
  -H "Content-Type: application/json" \
  -d '{
    "nombre": "Juan",
    "apellido": "Pérez",
    "email": "[email protected]",
    "password": "SecurePass123",
    "telefono": "+1234567890",
    "direccion": "123 Main Street, City"
  }'
Response: 201 Created
{
  "message": "Usuario registrado con éxito. Por favor, revisa tu correo para activar tu cuenta.",
  "usuario": {
    "id": 10,
    "nombre": "Juan",
    "apellido": "Pérez",
    "email": "[email protected]",
    "enabled": false,
    "tokenVerificacion": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
  }
}
Automatic Actions:
  • Password is encrypted using BCrypt
  • Account is created with enabled = false
  • Unique verification token (UUID) is generated
  • Email with activation link is sent to the user
Users must verify their email before they can log in. The login endpoint will return 403 Forbidden if the account is not enabled.

List All Users (Admin)

GET /api/usuarios
Retrieve all registered users. Authentication: Required - ROLE_ADMIN Response: 200 OK - Array of user objects Example Request:
cURL
curl -X GET http://localhost:8080/api/usuarios \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN"

Get User by ID

GET /api/usuarios/{id}
Retrieve a specific user’s profile. Authentication: Required (user can access their own profile; admins can access any profile)
id
long
required
User ID
Responses:
  • 200 OK - User object
  • 404 Not Found - User does not exist
Response Body:
id
long
User ID
nombre
string
First name
apellido
string
Last name
email
string
Email address
telefono
string
Phone number
direccion
string
Shipping address
enabled
boolean
Account activation status
roles
array
Array of role objects (ROLE_USER, ROLE_ADMIN)
Example Request:
cURL
curl -X GET http://localhost:8080/api/usuarios/5 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Update User Profile

PUT /api/usuarios/{id}
Update user profile information. Authentication: Required (user can update their own profile; admins can update any profile)
id
long
required
User ID
Request Body: User object with updated fields (nombre, apellido, telefono, direccion) Responses:
  • 200 OK - Updated user object
  • 404 Not Found - User does not exist
Example Request:
cURL
curl -X PUT http://localhost:8080/api/usuarios/5 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "nombre": "Juan",
    "apellido": "Pérez",
    "telefono": "+1234567890",
    "direccion": "456 New Address, City"
  }'
Do not include password or email in the update request. Use dedicated endpoints for those operations.

Change Password

PATCH /api/usuarios/{id}/password
Change user’s password (requires current password for verification). Authentication: Required (user can change their own password)
id
long
required
User ID
Request Body:
actualPassword
string
required
Current password
nuevaPassword
string
required
New password
Example Request:
cURL
curl -X PATCH http://localhost:8080/api/usuarios/5/password \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "actualPassword": "OldPass123",
    "nuevaPassword": "NewSecurePass456"
  }'
Responses:
  • 200 OK
    {"message": "Contraseña actualizada"}
    
  • 400 Bad Request
    {"message": "Error al cambiar contraseña"}
    
The service validates that actualPassword matches the user’s current password before applying the change. The new password is encrypted with BCrypt.

Delete User Account

DELETE /api/usuarios/{id}
Delete a user account. Authentication: Required (user can delete their own account; admins can delete any account)
id
long
required
User ID
Response: 204 No Content Example Request:
cURL
curl -X DELETE http://localhost:8080/api/usuarios/5 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
Deleting a user account is permanent. All associated data (orders, cart) may be affected. Consider implementing a soft delete or account deactivation instead.

User Model

The complete user object structure:
{
  "id": 5,
  "nombre": "Juan",
  "apellido": "Pérez",
  "email": "[email protected]",
  "telefono": "+1234567890",
  "direccion": "123 Main Street, City",
  "enabled": true,
  "tokenVerificacion": null,
  "roles": [
    {
      "id": 1,
      "nombre": "ROLE_USER"
    }
  ],
  "fechaRegistro": "2024-01-15T10:30:00"
}

Integration Examples

Frontend: User Registration Flow

JavaScript
async function registerUser(userData) {
  try {
    const response = await fetch('http://localhost:8080/api/usuarios/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData)
    });
    
    if (response.ok) {
      const result = await response.json();
      console.log('Registration successful:', result.message);
      // Show message: "Check your email to activate your account"
      return result;
    } else {
      console.error('Registration failed');
    }
  } catch (error) {
    console.error('Error during registration:', error);
  }
}

// Usage
await registerUser({
  nombre: 'Juan',
  apellido: 'Pérez',
  email: '[email protected]',
  password: 'SecurePass123',
  telefono: '+1234567890',
  direccion: '123 Main Street'
});

Frontend: Update User Profile

JavaScript
async function updateProfile(userId, updates, token) {
  const response = await fetch(`http://localhost:8080/api/usuarios/${userId}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updates)
  });
  
  return response.json();
}

// Usage
await updateProfile(5, {
  telefono: '+9876543210',
  direccion: '456 New Address'
}, userToken);

Frontend: Change Password

JavaScript
async function changePassword(userId, currentPassword, newPassword, token) {
  const response = await fetch(`http://localhost:8080/api/usuarios/${userId}/password`, {
    method: 'PATCH',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      actualPassword: currentPassword,
      nuevaPassword: newPassword
    })
  });
  
  if (response.ok) {
    const result = await response.json();
    console.log('Password updated:', result.message);
  } else {
    console.error('Failed to change password');
  }
}

Security Considerations

Password Encryption

All passwords are encrypted using BCrypt with Spring Security’s default strength (10 rounds).

Email Verification

Users must verify their email via a unique UUID token before accessing protected resources.

Role-Based Access

Endpoints enforce RBAC - users can only access their own data unless they have ROLE_ADMIN.

JWT Authentication

All authenticated endpoints require a valid JWT token in the Authorization header.

Error Responses

Status CodeScenarioCommon Cause
400 Bad RequestRegistration failedEmail already exists
401 UnauthorizedMissing/invalid tokenUser not logged in
403 ForbiddenAccount not enabledEmail not verified
403 ForbiddenAccess deniedUser accessing another user’s data
404 Not FoundUser does not existInvalid user ID
500 Internal Server ErrorEmail sending failedSMTP configuration issue

Authentication API

Login, registration, and password recovery

Orders API

View user order history

Build docs developers (and LLMs) love