Skip to main content

PATCH /usuarios//rol

Updates a user’s role. This is an admin-only operation for managing user permissions.

Authentication

Admin Only: This endpoint requires admin privileges
Only users with the admin role can assign roles to other users.

Path Parameters

user_id
string
required
The MongoDB ObjectId of the user whose role will be updated

Request Body

rol
string
required
The new role to assign. Must be one of: visitante, editor, or admin

Request

cURL
curl -X PATCH "http://localhost:8000/usuarios/507f1f77bcf86cd799439011/rol" \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "rol": "editor"
  }'
Python
import requests

user_id = "507f1f77bcf86cd799439011"
url = f"http://localhost:8000/usuarios/{user_id}/rol"
headers = {
    "Authorization": "Bearer ADMIN_JWT_TOKEN",
    "Content-Type": "application/json"
}
data = {
    "rol": "editor"
}

response = requests.patch(url, headers=headers, json=data)
print(response.json())
JavaScript
const userId = '507f1f77bcf86cd799439011';
const response = await fetch(`http://localhost:8000/usuarios/${userId}/rol`, {
  method: 'PATCH',
  headers: {
    'Authorization': 'Bearer ADMIN_JWT_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    rol: 'editor'
  })
});

const result = await response.json();
console.log(result);

Response

message
string
Success message confirming the role update
user_id
string
The ID of the user whose role was updated
nuevo_rol
string
The newly assigned role

Example Response

{
  "message": "Rol actualizado correctamente",
  "user_id": "507f1f77bcf86cd799439011",
  "nuevo_rol": "editor"
}

Error Responses

Status CodeDescription
400Bad Request - Missing rol field or invalid role value
401Unauthorized - Invalid or missing JWT token
403Forbidden - User is not an admin
404Not Found - User with given ID does not exist
500Internal Server Error - Database or processing error

Valid Role Values

visitante

Default role for new users. Read-only access to public content.

editor

Can create and edit routes, toggle destination status.

admin

Full access to all platform features and user management.

Implementation Reference

This endpoint is implemented in src/infrastructure/api/routers/usuario_router.py:202-223:
@router.patch("/{user_id}/rol", dependencies=[Depends(require_admin)])
def asignar_rol(user_id: str, data: dict, db=Depends(get_database)):
    try:
        nuevo_rol = data.get("rol")
        if not nuevo_rol:
            raise HTTPException(status_code=400, detail="Debes enviar el campo 'rol'.")

        repo = UsuarioRepositoryImpl(db)
        use_case = AsignarRol(repo)
        usuario = use_case.ejecutar(user_id, nuevo_rol)

        return {
            "message": "Rol actualizado correctamente",
            "user_id": usuario.id,
            "nuevo_rol": usuario.rol,
        }

    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    except Exception as e:
        raise HTTPException(status_code=500, detail="Error interno: " + str(e))
The AsignarRol use case validates the role value and updates the user document in MongoDB.

Use Cases

  • Promote user to editor: Grant content management permissions to trusted users
  • Promote user to admin: Give full platform access to administrators
  • Demote user: Revoke elevated permissions (e.g., from editor to visitante)
  • User moderation: Adjust permissions based on user behavior
Role changes take effect immediately. The user will need to log in again to receive a JWT token with the updated role.

Build docs developers (and LLMs) love