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 :
User’s email address (must be unique)
User’s password (will be encrypted with BCrypt)
Example Request :
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)
Retrieve all registered users.
Authentication : Required - ROLE_ADMIN
Response : 200 OK - Array of user objects
Example Request :
curl -X GET http://localhost:8080/api/usuarios \
-H "Authorization: Bearer ADMIN_JWT_TOKEN"
Get User by ID
Retrieve a specific user’s profile.
Authentication : Required (user can access their own profile; admins can access any profile)
Responses :
200 OK - User object
404 Not Found - User does not exist
Response Body :
Account activation status
Array of role objects (ROLE_USER, ROLE_ADMIN)
Example Request :
curl -X GET http://localhost:8080/api/usuarios/5 \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
Update User Profile
Update user profile information.
Authentication : Required (user can update their own profile; admins can update any profile)
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 -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)
Request Body :
Example Request :
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)
Response : 204 No Content
Example Request :
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
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
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
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 Code Scenario Common Cause 400 Bad RequestRegistration failed Email already exists 401 UnauthorizedMissing/invalid token User not logged in 403 ForbiddenAccount not enabled Email not verified 403 ForbiddenAccess denied User accessing another user’s data 404 Not FoundUser does not exist Invalid user ID 500 Internal Server ErrorEmail sending failed SMTP configuration issue
Authentication API Login, registration, and password recovery
Orders API View user order history