Documentation > API Reference > User Management API

User Management API

Complete user account management, role-based access control, and administrative functions through programmatic interfaces.

Overview

The User Management API provides comprehensive functionality for managing user accounts, roles, permissions, and access controls. It supports role-based access control (RBAC), multi-factor authentication (MFA), and detailed user activity tracking.

Base URL

/api/v1/users

Authentication

All endpoints require valid JWT authentication with administrative privileges for most operations.

User Management Concepts

User Roles

  • Administrator: Full system access and user management privileges
  • Operator: Host management and monitoring capabilities
  • Viewer: Read-only access to system information
  • Guest: Limited access to basic system status

Permissions

  • Host Management: Create, modify, delete hosts and agents
  • Package Management: Install, update, remove packages
  • User Administration: Manage user accounts and permissions
  • System Configuration: Modify system settings and configuration
  • Monitoring Access: View metrics, alerts, and system health
  • Report Generation: Create and access system reports

Authentication Methods

  • Local Authentication: Username and password stored locally
  • LDAP Integration: Active Directory and LDAP authentication
  • OAuth2/OIDC: External identity provider integration
  • Multi-Factor Authentication: TOTP, SMS, and hardware token support

API Endpoints

Get All Users

GET /api/v1/users

Retrieve a list of all users with their basic information and roles.

Query Parameters

  • page - Page number for pagination (default: 1)
  • limit - Number of users per page (default: 50, max: 100)
  • role - Filter by user role
  • active - Filter by active status (true/false)
  • search - Search by username, email, or full name

Request

GET /api/v1/users?page=1&limit=20&active=true
Authorization: Bearer {jwt_token}

Response

{
  "users": [
    {
      "id": "user-uuid-1",
      "username": "admin",
      "email": "admin@example.com",
      "full_name": "System Administrator",
      "role": "administrator",
      "active": true,
      "last_login": "2024-01-15T10:30:00Z",
      "created_at": "2024-01-01T00:00:00Z",
      "mfa_enabled": true,
      "permissions": [
        "host_management",
        "user_administration",
        "system_configuration",
        "package_management",
        "monitoring_access",
        "report_generation"
      ]
    },
    {
      "id": "user-uuid-2",
      "username": "operator1",
      "email": "operator@example.com",
      "full_name": "John Operator",
      "role": "operator",
      "active": true,
      "last_login": "2024-01-15T09:45:00Z",
      "created_at": "2024-01-05T14:30:00Z",
      "mfa_enabled": false,
      "permissions": [
        "host_management",
        "package_management",
        "monitoring_access"
      ]
    }
  ],
  "pagination": {
    "current_page": 1,
    "total_pages": 3,
    "total_users": 52,
    "per_page": 20
  }
}

Get User Details

GET /api/v1/users/{user_id}

Retrieve detailed information about a specific user.

Request

GET /api/v1/users/user-uuid-1
Authorization: Bearer {jwt_token}

Response

{
  "id": "user-uuid-1",
  "username": "admin",
  "email": "admin@example.com",
  "full_name": "System Administrator",
  "role": "administrator",
  "active": true,
  "created_at": "2024-01-01T00:00:00Z",
  "updated_at": "2024-01-10T15:30:00Z",
  "last_login": "2024-01-15T10:30:00Z",
  "login_count": 127,
  "password_changed_at": "2024-01-01T00:00:00Z",
  "mfa_enabled": true,
  "mfa_setup_at": "2024-01-01T00:05:00Z",
  "permissions": [
    "host_management",
    "user_administration",
    "system_configuration",
    "package_management",
    "monitoring_access",
    "report_generation"
  ],
  "preferences": {
    "timezone": "UTC",
    "language": "en",
    "dashboard_layout": "default",
    "notifications": {
      "email": true,
      "browser": true,
      "security_alerts": true
    }
  },
  "activity_summary": {
    "last_30_days": {
      "logins": 15,
      "actions_performed": 234,
      "hosts_managed": 12,
      "packages_installed": 8
    }
  }
}

Create User

POST /api/v1/users

Create a new user account with specified role and permissions.

Request

POST /api/v1/users
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "username": "newuser",
  "email": "newuser@example.com",
  "full_name": "New User",
  "password": "SecurePassword123!",
  "role": "operator",
  "active": true,
  "force_password_change": true,
  "send_welcome_email": true,
  "permissions": [
    "host_management",
    "package_management",
    "monitoring_access"
  ]
}

Response

{
  "id": "user-uuid-3",
  "username": "newuser",
  "email": "newuser@example.com",
  "full_name": "New User",
  "role": "operator",
  "active": true,
  "created_at": "2024-01-15T10:35:00Z",
  "force_password_change": true,
  "permissions": [
    "host_management",
    "package_management",
    "monitoring_access"
  ],
  "status": "created",
  "welcome_email_sent": true
}

Update User

PUT /api/v1/users/{user_id}

Update user information, role, permissions, or status.

Request

PUT /api/v1/users/user-uuid-3
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "full_name": "Updated User Name",
  "email": "updated@example.com",
  "role": "administrator",
  "active": true,
  "permissions": [
    "host_management",
    "user_administration",
    "system_configuration",
    "package_management",
    "monitoring_access",
    "report_generation"
  ]
}

Response

{
  "id": "user-uuid-3",
  "username": "newuser",
  "email": "updated@example.com",
  "full_name": "Updated User Name",
  "role": "administrator",
  "active": true,
  "updated_at": "2024-01-15T10:40:00Z",
  "permissions": [
    "host_management",
    "user_administration",
    "system_configuration",
    "package_management",
    "monitoring_access",
    "report_generation"
  ],
  "status": "updated"
}

Delete User

DELETE /api/v1/users/{user_id}

Delete a user account. This action is irreversible.

Query Parameters

  • transfer_ownership - Transfer owned resources to another user
  • backup_data - Create backup of user data before deletion

Request

DELETE /api/v1/users/user-uuid-3?transfer_ownership=user-uuid-1
Authorization: Bearer {jwt_token}

Response

{
  "id": "user-uuid-3",
  "username": "newuser",
  "status": "deleted",
  "deleted_at": "2024-01-15T10:45:00Z",
  "data_backup_created": true,
  "ownership_transferred_to": "user-uuid-1",
  "resources_transferred": {
    "hosts": 5,
    "reports": 2,
    "configurations": 3
  }
}

Change Password

POST /api/v1/users/{user_id}/password

Change a user's password. Users can change their own password, administrators can change any password.

Request

POST /api/v1/users/user-uuid-2/password
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "current_password": "OldPassword123!",
  "new_password": "NewSecurePassword456!",
  "force_logout_other_sessions": true
}

Response

{
  "user_id": "user-uuid-2",
  "status": "password_changed",
  "changed_at": "2024-01-15T10:50:00Z",
  "sessions_invalidated": 3,
  "password_strength": {
    "score": 4,
    "requirements_met": [
      "minimum_length",
      "uppercase",
      "lowercase",
      "numbers",
      "special_characters"
    ]
  }
}

Setup Multi-Factor Authentication

POST /api/v1/users/{user_id}/mfa/setup

Initialize MFA setup for a user account.

Request

POST /api/v1/users/user-uuid-2/mfa/setup
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "method": "totp",
  "device_name": "iPhone 12"
}

Response

{
  "user_id": "user-uuid-2",
  "mfa_method": "totp",
  "setup_key": "JBSWY3DPEHPK3PXP",
  "qr_code_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
  "backup_codes": [
    "12345678",
    "87654321",
    "13579246",
    "97531864",
    "24681357"
  ],
  "expires_at": "2024-01-15T11:00:00Z",
  "instructions": "Scan the QR code with your authenticator app and enter the verification code to complete setup."
}

Verify MFA Setup

POST /api/v1/users/{user_id}/mfa/verify

Complete MFA setup by verifying the authentication code.

Request

POST /api/v1/users/user-uuid-2/mfa/verify
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "verification_code": "123456"
}

Response

{
  "user_id": "user-uuid-2",
  "mfa_enabled": true,
  "setup_completed_at": "2024-01-15T10:55:00Z",
  "status": "mfa_activated",
  "backup_codes_remaining": 5
}

Get User Permissions

GET /api/v1/users/{user_id}/permissions

Retrieve detailed permissions for a specific user.

Request

GET /api/v1/users/user-uuid-2/permissions
Authorization: Bearer {jwt_token}

Response

{
  "user_id": "user-uuid-2",
  "role": "operator",
  "permissions": {
    "host_management": {
      "enabled": true,
      "actions": [
        "view_hosts",
        "edit_hosts",
        "approve_hosts",
        "delete_hosts"
      ],
      "restrictions": {
        "host_groups": ["production", "staging"],
        "max_hosts": 100
      }
    },
    "package_management": {
      "enabled": true,
      "actions": [
        "view_packages",
        "install_packages",
        "update_packages",
        "remove_packages"
      ],
      "restrictions": {
        "allowed_package_managers": ["apt", "yum"],
        "security_updates_only": false
      }
    },
    "monitoring_access": {
      "enabled": true,
      "actions": [
        "view_metrics",
        "view_alerts",
        "acknowledge_alerts"
      ],
      "restrictions": {
        "metric_retention": "30d",
        "alert_modification": false
      }
    }
  },
  "inherited_from_role": [
    "host_management",
    "package_management",
    "monitoring_access"
  ],
  "custom_permissions": []
}

Update User Permissions

PUT /api/v1/users/{user_id}/permissions

Update specific permissions for a user, overriding role defaults.

Request

PUT /api/v1/users/user-uuid-2/permissions
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "permissions": [
    "host_management",
    "package_management",
    "monitoring_access",
    "report_generation"
  ],
  "custom_restrictions": {
    "host_management": {
      "max_hosts": 50,
      "host_groups": ["staging", "development"]
    },
    "package_management": {
      "security_updates_only": true
    }
  }
}

Response

{
  "user_id": "user-uuid-2",
  "permissions_updated": true,
  "updated_at": "2024-01-15T11:00:00Z",
  "changes": {
    "added": ["report_generation"],
    "removed": [],
    "modified_restrictions": [
      "host_management.max_hosts",
      "host_management.host_groups",
      "package_management.security_updates_only"
    ]
  }
}

Get User Activity Log

GET /api/v1/users/{user_id}/activity

Retrieve user activity log including logins, actions, and system changes.

Query Parameters

  • start_date - Start date for activity log (ISO 8601)
  • end_date - End date for activity log (ISO 8601)
  • action_type - Filter by action type
  • limit - Number of entries to return (default: 100)

Request

GET /api/v1/users/user-uuid-2/activity?start_date=2024-01-01&limit=50
Authorization: Bearer {jwt_token}

Response

{
  "user_id": "user-uuid-2",
  "activity_log": [
    {
      "id": "activity-001",
      "timestamp": "2024-01-15T10:55:00Z",
      "action_type": "authentication",
      "action": "login_success",
      "ip_address": "192.168.1.100",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
      "location": {
        "country": "United States",
        "city": "New York"
      },
      "mfa_used": false
    },
    {
      "id": "activity-002",
      "timestamp": "2024-01-15T10:30:00Z",
      "action_type": "package_management",
      "action": "package_install",
      "target": {
        "host_id": "host-uuid-5",
        "hostname": "web-server-03",
        "package": "nginx"
      },
      "result": "success",
      "duration_ms": 45000
    },
    {
      "id": "activity-003",
      "timestamp": "2024-01-15T09:15:00Z",
      "action_type": "host_management",
      "action": "host_approve",
      "target": {
        "host_id": "host-uuid-6",
        "hostname": "db-server-02"
      },
      "result": "success"
    }
  ],
  "pagination": {
    "current_page": 1,
    "total_pages": 12,
    "total_entries": 573,
    "per_page": 50
  },
  "summary": {
    "total_logins": 47,
    "total_actions": 573,
    "most_common_actions": [
      "package_install",
      "host_view",
      "metric_access"
    ]
  }
}

Get Current User Profile

GET /api/v1/users/me

Retrieve the current authenticated user's profile information.

Request

GET /api/v1/users/me
Authorization: Bearer {jwt_token}

Response

{
  "id": "user-uuid-2",
  "username": "operator1",
  "email": "operator@example.com",
  "full_name": "John Operator",
  "role": "operator",
  "permissions": [
    "host_management",
    "package_management",
    "monitoring_access"
  ],
  "preferences": {
    "timezone": "America/New_York",
    "language": "en",
    "dashboard_layout": "compact",
    "notifications": {
      "email": true,
      "browser": false,
      "security_alerts": true
    }
  },
  "mfa_enabled": false,
  "session_info": {
    "login_time": "2024-01-15T10:55:00Z",
    "ip_address": "192.168.1.100",
    "expires_at": "2024-01-16T10:55:00Z"
  }
}

Update User Preferences

PUT /api/v1/users/me/preferences

Update the current user's preferences and settings.

Request

PUT /api/v1/users/me/preferences
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "timezone": "Europe/London",
  "language": "en",
  "dashboard_layout": "detailed",
  "notifications": {
    "email": false,
    "browser": true,
    "security_alerts": true,
    "maintenance_alerts": true
  },
  "display_settings": {
    "theme": "dark",
    "items_per_page": 25,
    "show_advanced_options": true
  }
}

Response

{
  "user_id": "user-uuid-2",
  "preferences_updated": true,
  "updated_at": "2024-01-15T11:05:00Z",
  "preferences": {
    "timezone": "Europe/London",
    "language": "en",
    "dashboard_layout": "detailed",
    "notifications": {
      "email": false,
      "browser": true,
      "security_alerts": true,
      "maintenance_alerts": true
    },
    "display_settings": {
      "theme": "dark",
      "items_per_page": 25,
      "show_advanced_options": true
    }
  }
}

Role-Based Access Control

Get Available Roles

GET /api/v1/users/roles

Retrieve all available user roles and their permissions.

Request

GET /api/v1/users/roles
Authorization: Bearer {jwt_token}

Response

{
  "roles": [
    {
      "name": "administrator",
      "display_name": "Administrator",
      "description": "Full system access with all administrative privileges",
      "permissions": [
        "host_management",
        "user_administration",
        "system_configuration",
        "package_management",
        "monitoring_access",
        "report_generation",
        "security_management"
      ],
      "restrictions": {},
      "user_count": 3
    },
    {
      "name": "operator",
      "display_name": "Operator",
      "description": "Host and package management with monitoring access",
      "permissions": [
        "host_management",
        "package_management",
        "monitoring_access"
      ],
      "restrictions": {
        "max_hosts": 100,
        "security_updates_only": false
      },
      "user_count": 15
    },
    {
      "name": "viewer",
      "display_name": "Viewer",
      "description": "Read-only access to system information",
      "permissions": [
        "monitoring_access"
      ],
      "restrictions": {
        "read_only": true,
        "metric_retention": "7d"
      },
      "user_count": 28
    }
  ]
}

Create Custom Role

POST /api/v1/users/roles

Create a custom role with specific permissions and restrictions.

Request

POST /api/v1/users/roles
Authorization: Bearer {jwt_token}
Content-Type: application/json

{
  "name": "security_analyst",
  "display_name": "Security Analyst",
  "description": "Security-focused role with vulnerability and compliance access",
  "permissions": [
    "monitoring_access",
    "report_generation",
    "security_management"
  ],
  "restrictions": {
    "security_reports_only": true,
    "vulnerability_access": true,
    "compliance_access": true
  }
}

Response

{
  "role": {
    "name": "security_analyst",
    "display_name": "Security Analyst",
    "description": "Security-focused role with vulnerability and compliance access",
    "permissions": [
      "monitoring_access",
      "report_generation",
      "security_management"
    ],
    "restrictions": {
      "security_reports_only": true,
      "vulnerability_access": true,
      "compliance_access": true
    },
    "created_at": "2024-01-15T11:10:00Z",
    "user_count": 0
  },
  "status": "created"
}

Error Handling

Common Error Responses

400 Bad Request

{
  "error": "invalid_user_data",
  "message": "Username already exists",
  "field": "username",
  "value": "existing_user"
}

403 Forbidden

{
  "error": "insufficient_permissions",
  "message": "User does not have permission to manage other users",
  "required_permission": "user_administration"
}

404 Not Found

{
  "error": "user_not_found",
  "message": "User with ID 'user-invalid' not found",
  "user_id": "user-invalid"
}

422 Unprocessable Entity

{
  "error": "validation_failed",
  "message": "Password does not meet security requirements",
  "validation_errors": [
    {
      "field": "password",
      "error": "minimum_length",
      "requirement": "Password must be at least 12 characters long"
    },
    {
      "field": "password",
      "error": "special_characters",
      "requirement": "Password must contain at least one special character"
    }
  ]
}

Code Examples

Python Example - User Management

import requests

class SysManageUserManager:
    def __init__(self, api_base, token):
        self.api_base = api_base
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

    def create_user(self, username, email, full_name, role, password):
        """Create a new user account"""
        user_data = {
            'username': username,
            'email': email,
            'full_name': full_name,
            'role': role,
            'password': password,
            'active': True,
            'force_password_change': True,
            'send_welcome_email': True
        }

        response = requests.post(
            f'{self.api_base}/users',
            headers=self.headers,
            json=user_data
        )

        if response.status_code == 201:
            return response.json()
        else:
            raise Exception(f"Failed to create user: {response.text}")

    def setup_user_mfa(self, user_id):
        """Setup MFA for a user"""
        setup_response = requests.post(
            f'{self.api_base}/users/{user_id}/mfa/setup',
            headers=self.headers,
            json={'method': 'totp', 'device_name': 'Authenticator App'}
        )

        if setup_response.status_code == 200:
            setup_data = setup_response.json()
            print(f"MFA Setup Key: {setup_data['setup_key']}")
            print("Please scan the QR code and enter verification code")

            # In a real application, you would prompt the user for the code
            verification_code = input("Enter verification code: ")

            verify_response = requests.post(
                f'{self.api_base}/users/{user_id}/mfa/verify',
                headers=self.headers,
                json={'verification_code': verification_code}
            )

            if verify_response.status_code == 200:
                print("MFA setup completed successfully")
                return verify_response.json()
            else:
                raise Exception(f"MFA verification failed: {verify_response.text}")
        else:
            raise Exception(f"MFA setup failed: {setup_response.text}")

    def get_user_activity(self, user_id, days=7):
        """Get user activity for the last N days"""
        from datetime import datetime, timedelta

        start_date = (datetime.now() - timedelta(days=days)).isoformat()

        response = requests.get(
            f'{self.api_base}/users/{user_id}/activity',
            headers=self.headers,
            params={'start_date': start_date, 'limit': 100}
        )

        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Failed to get user activity: {response.text}")

# Usage example
api_base = "https://your-server.example.com/api/v1"
token = "your_jwt_token_here"

user_manager = SysManageUserManager(api_base, token)

# Create new user
new_user = user_manager.create_user(
    username="security_analyst1",
    email="analyst@example.com",
    full_name="Security Analyst",
    role="security_analyst",
    password="SecurePassword123!"
)
print(f"Created user: {new_user['id']}")

# Setup MFA for the new user
user_manager.setup_user_mfa(new_user['id'])

# Get recent activity
activity = user_manager.get_user_activity(new_user['id'], days=30)
print(f"User has {len(activity['activity_log'])} recorded activities")

JavaScript Example - User Profile Management

class UserProfileManager {
    constructor(apiBase, token) {
        this.apiBase = apiBase;
        this.headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };
    }

    async getCurrentUser() {
        const response = await fetch(`${this.apiBase}/users/me`, {
            headers: this.headers
        });

        if (!response.ok) {
            throw new Error(`Failed to get current user: ${response.statusText}`);
        }

        return await response.json();
    }

    async updatePreferences(preferences) {
        const response = await fetch(`${this.apiBase}/users/me/preferences`, {
            method: 'PUT',
            headers: this.headers,
            body: JSON.stringify(preferences)
        });

        if (!response.ok) {
            throw new Error(`Failed to update preferences: ${response.statusText}`);
        }

        return await response.json();
    }

    async changePassword(currentPassword, newPassword) {
        const response = await fetch(`${this.apiBase}/users/me/password`, {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword,
                force_logout_other_sessions: true
            })
        });

        if (!response.ok) {
            throw new Error(`Failed to change password: ${response.statusText}`);
        }

        return await response.json();
    }

    async getUserPermissions(userId) {
        const response = await fetch(`${this.apiBase}/users/${userId}/permissions`, {
            headers: this.headers
        });

        if (!response.ok) {
            throw new Error(`Failed to get permissions: ${response.statusText}`);
        }

        return await response.json();
    }
}

// Usage example
const apiBase = 'https://your-server.example.com/api/v1';
const token = 'your_jwt_token_here';
const profileManager = new UserProfileManager(apiBase, token);

// Get current user profile
profileManager.getCurrentUser()
    .then(user => {
        console.log('Current user:', user);

        // Update user preferences
        return profileManager.updatePreferences({
            timezone: 'America/Los_Angeles',
            language: 'en',
            dashboard_layout: 'detailed',
            notifications: {
                email: true,
                browser: true,
                security_alerts: true
            }
        });
    })
    .then(result => {
        console.log('Preferences updated:', result);
    })
    .catch(error => {
        console.error('Error:', error);
    });