Overview
The User Management feature provides comprehensive user account administration with role-based access control (RBAC). The system supports two primary roles: ADMIN (administrators) and Inversionista (investors), with JWT-based authentication ensuring secure API access.Key Capabilities
User Registration
Self-service registration with automatic wallet creation and password encryption
Role-Based Access
Granular control with ADMIN and Inversionista roles for feature segregation
JWT Authentication
Secure token-based authentication for stateless API access
Account Management
Enable/disable users without data deletion for audit trail preservation
Data Model
TheUsuario entity implements Spring Security’s UserDetails interface:
| Field | Type | Description |
|---|---|---|
id | long | Unique identifier (auto-generated) |
nombre | String | First name |
apellidoPa | String | Paternal surname |
apellidoMa | String | Maternal surname |
telefono | String | Phone number |
correo | String | Email address (unique) |
username | String | Login username (unique) |
password | String | Encrypted password (BCrypt) |
dni | String | National ID number (unique) |
foto | String | Profile photo filename (default: “default.png”) |
fecha | Date | Registration date |
enable | String | Account status: “Activo” or “No Activo” |
idTipoUsu | long | Role ID (foreign key to Rol) |
tiporol | Rol | Role entity (ADMIN or Inversionista) |
Role Entity
TheRol entity defines user roles:
| Field | Type | Description |
|---|---|---|
idTipoUsu | Long | Role ID (1 = ADMIN, 2 = Inversionista) |
tipo | String | Role name (“ADMIN” or “Inversionista”) |
Passwords are automatically encrypted using BCrypt before storage. Users attempting to register as ADMIN are automatically downgraded to
idTipoUsu = 1 (basic user role).Workflow
User Registration Process
The registration workflow includes automatic validations and wallet creation:-
Validate Uniqueness
- Check if
usernamealready exists - Check if
correo(email) already exists - Check if
dni(national ID) already exists - Return conflict error if any duplicates found
- Check if
-
Set Automatic Fields
fecha= current dateenable= “Activo”foto= “default.png”id= 0 (triggers auto-generation)
-
Encrypt Password
- Apply BCrypt hashing to plaintext password
-
Assign Role
- Retrieve role entity by
idTipoUsu - Prevent ADMIN role assignment (security measure)
- Associate role with user
- Retrieve role entity by
-
Create User
- Persist user to database
-
Create Wallet
- Automatically create a
Cartera(wallet) for the user - Initialize with
saldo= 0 - Link to user via
idUsu
- Automatically create a
See Code Example: User Registration
See Code Example: User Registration
UsuarioController.java:94-151Main API Endpoints
User CRUD Operations
- Register User
- Update User
- Delete User
- Get User by ID
List Endpoints
- List All Users
- List Active Users
- Get User by Username
UsuarioController.java:86-91Role Management
List Available Roles
List Available Roles
UsuarioController.java:77-82Authentication Flow
JWT Token Generation
The authentication system uses JWT (JSON Web Tokens) for stateless authentication:Credential Verification
System authenticates using Spring Security’s
AuthenticationManager:- Retrieves user by username
- Compares BCrypt-encrypted password
- Verifies account is enabled
- Checks for disabled or bad credentials exceptions
Token Generation
Upon successful authentication:
- Load full
UserDetailsfor the user - Generate JWT token with user information and authorities
- Token includes role information (ADMIN or Inversionista)
See Code Example: Authentication Flow
See Code Example: Authentication Flow
AuthenticationController.java:36-60Get Current User
AuthenticationController.java:61-65
Role-Based Access Control
ADMIN Role Capabilities
Users with the ADMIN role have access to:-
Investment Opportunity Management
- Create, update, delete opportunities
- Bundle invoices into opportunities
- View all opportunities (active and inactive)
-
Invoice Management
- Register new invoices
- Update invoice details
- Delete invoices
- Search and filter invoices
-
User Administration
- View all users
- Enable/disable user accounts
- View user details
-
Financial Overview
- View all wallets and balances
- Monitor all transactions
Inversionista Role Capabilities
Users with the Inversionista role have access to:-
Investment Opportunities (Read-Only)
- View active opportunities
- See opportunity details (returns, funding progress)
- Browse and filter available investments
-
Personal Wallet
- View their own wallet balance
- Make deposits from bank accounts
- Make withdrawals to bank accounts
- View personal transaction history
-
Profile Management
- Update their own profile information
- View their account details
Endpoint URLs often indicate access level:
/api/admin/* for admin-only, /api/user/* for investors, and /api/* for public/authenticated endpoints.Default Admin User
The system should be initialized with a default admin user for initial access:Use Cases
Use Case 1: Investor Registration
Scenario: A new investor wants to create an account to start investing.-
User fills out registration form with:
- Personal information (name, phone, email)
- Username and password
- DNI (national ID)
- Selects role: Inversionista (idTipoUsu = 2)
-
Frontend calls
POST /api/registrar -
System:
- Validates username, email, and DNI are unique
- Encrypts password with BCrypt
- Creates user account with “Activo” status
- Automatically creates wallet with 0 balance
- Returns user details and wallet information
- User can immediately log in with their credentials
Use Case 2: User Login and Token Generation
Scenario: Registered user wants to access the platform.- User enters username “jperez” and password “SecurePass123!”
- Frontend calls
POST /generate-token - System:
- Authenticates credentials against BCrypt hash
- Verifies account is enabled (“Activo”)
- Loads user’s role (Inversionista)
- Generates JWT token with user info and authorities
- System returns token
- Frontend stores token and includes it in all subsequent requests:
Use Case 3: Admin Disabling a User Account
Scenario: A user violated terms of service and needs to be suspended.- Admin identifies user ID: 15
- Admin calls
DELETE /api/eliminar/15 - System:
- Sets user’s
enablefield to “No Activo” - Preserves all user data for audit trail
- Sets user’s
- User can no longer authenticate (disabled exception thrown)
- User’s data and transaction history remain in database
Use Case 4: User Updating Profile Information
Scenario: User changed their email and phone number.- User (id: 15) retrieves current info:
GET /api/buscar/15 - User modifies:
correo: “[email protected]”telefono: “987654999”
- User calls
PUT /api/actualizarwith updated data - System:
- Validates new email is unique
- Verifies user exists
- Preserves protected fields (username, password, role, fecha)
- Updates modifiable fields
- System returns success confirmation
Security Best Practices
Password Encryption
All passwords are encrypted with BCrypt. Never store or transmit plaintext passwords.
Token Validation
Validate JWT tokens on every request using JwtAuthenticationFilter. Check expiration and signature.
Role Restrictions
Prevent role escalation by blocking ADMIN role assignment during registration (line 125-128 of UsuarioController).
Soft Deletion
Never hard-delete users. Use enable/disable for audit trail preservation.
Error Handling
Common error scenarios:| Scenario | HTTP Status | Response |
|---|---|---|
| Username already exists | 409 CONFLICT | {"mensaje": "Ese username ya existe"} |
| Email already exists | 409 CONFLICT | {"mensaje": "Ese email de usuario ya existe"} |
| DNI already exists | 409 CONFLICT | {"mensaje": "El DNI de usuario ya existe"} |
| User not found | 404 NOT_FOUND | {"mensaje": "El usuario con codigo X no existe"} |
| Invalid credentials | 500 ERROR | {"mensaje": "Credenciales ivalidas"} |
| Disabled account | 500 ERROR | {"mensaje": "Usuario deshabilitado"} |
Related Features
- Wallet Transactions - Automatically created wallets for each user
- Investment Opportunities - Role-based access to opportunity management
- Invoice Management - Admin-only invoice operations