> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiperai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create New User

> Create a new user account. Only accessible by administrators.


# Create New User

Create a new user account. Only accessible by administrators.

## Endpoint

```
POST /users
```

## Description

This endpoint allows administrators to create new user accounts in the system. You can specify various user attributes including role, license, and authentication type. This is an administrative endpoint that requires appropriate permissions.

## User Creation Flow

**Basic Auth** (`authType: "basic"`): User receives a welcome email with a password setup link. Account is created unverified until password is set.

**Enterprise SSO** (`authType: "enterprise"`): User is created verified and can sign in via enterprise SSO (Auth0, Microsoft AD, etc.). No password setup required.

## Authentication

Required. Include your API key in the Authorization header.

```bash theme={null}
Authorization: Bearer sk-your-api-key-here
```

## Request

### Request Body

| Parameter        | Type    | Required | Default   | Description                                                  |
| ---------------- | ------- | -------- | --------- | ------------------------------------------------------------ |
| `name`           | string  | Yes      | -         | User's full name                                             |
| `username`       | string  | No       | -         | Unique username (auto-generated from email if not provided)  |
| `email`          | string  | Yes      | -         | User's email address                                         |
| `role`           | string  | No       | user      | User's role (admin, user, globalReader)                      |
| `license`        | string  | No       | Essential | User's license tier (Essential, Growth, Ultra, Early Access) |
| `roleId`         | string  | No       | -         | Custom role ID (MongoDB ObjectId)                            |
| `setupCompleted` | boolean | No       | false     | Whether user setup is completed                              |
| `authType`       | string  | No       | basic     | Authentication type (basic, enterprise)                      |

### Example Request

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/users" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "username": "johndoe",
    "email": "john@example.com",
    "role": "user",
    "license": "Growth",
    "setupCompleted": false,
    "authType": "enterprise"
  }'
```

## Response

### Success Response (201)

```json theme={null}
{
  "success": true,
  "message": "User created successfully",
  "user": {
    "id": "60a7c8f5e8b4f5001f7a8c23",
    "name": "John Doe",
    "username": "johndoe",
    "email": "john@example.com",
    "role": "user",
    "license": "Growth",
    "status": 1,
    "isVerified": false,
    "setupCompleted": false,
    "authType": "basic",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
}
```

### Response Fields

| Field                 | Type    | Description                           |
| --------------------- | ------- | ------------------------------------- |
| `success`             | boolean | Always `true` for successful requests |
| `message`             | string  | Success message                       |
| `user`                | object  | Created user object                   |
| `user.id`             | string  | User's unique identifier              |
| `user.name`           | string  | User's full name                      |
| `user.username`       | string  | User's username                       |
| `user.email`          | string  | User's email address                  |
| `user.role`           | string  | User's role                           |
| `user.license`        | string  | User's license tier                   |
| `user.status`         | integer | User status (1=active)                |
| `user.isVerified`     | boolean | Whether user is verified              |
| `user.setupCompleted` | boolean | Whether user setup is completed       |
| `user.authType`       | string  | Authentication type                   |
| `user.createdAt`      | string  | User creation timestamp               |

## Example Usage

### JavaScript

```javascript theme={null}
const response = await fetch('https://{customer.name}.hiperai.ai/api/external/users', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-your-api-key-here',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    username: 'johndoe',
    email: 'john@example.com',
    role: 'user',
    license: 'Growth'
  })
});

const data = await response.json();

if (data.success) {
  console.log('User created:', data.user.name);
  console.log('User ID:', data.user.id);
}
```

### Python

```python theme={null}
import requests

headers = {
    'Authorization': 'Bearer sk-your-api-key-here',
    'Content-Type': 'application/json'
}

data = {
    'name': 'John Doe',
    'username': 'johndoe',
    'email': 'john@example.com',
    'role': 'user',
    'license': 'Growth'
}

response = requests.post('https://{customer.name}.hiperai.ai/api/external/users', 
                       headers=headers, json=data)
result = response.json()

if result['success']:
    print('User created:', result['user']['name'])
    print('User ID:', result['user']['id'])
```

### cURL

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/users" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "username": "johndoe",
    "email": "john@example.com",
    "role": "user",
    "license": "Growth"
  }'
```

## Error Responses

### 400 Bad Request

```json theme={null}
{
  "success": false,
  "error": "Invalid request parameters",
  "message": "The 'name' field is required"
}
```

### 400 Invalid AuthType

```json theme={null}
{
  "success": false,
  "error": "Invalid authType",
  "message": "authType must be either \"basic\" or \"enterprise\""
}
```

### 400 Missing Required Fields

```json theme={null}
{
  "success": false,
  "error": "Missing required fields",
  "message": "Name and email are required"
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": "Invalid API key",
  "message": "The provided API key is invalid or has been revoked"
}
```

### 403 Forbidden

```json theme={null}
{
  "success": false,
  "error": "Access denied",
  "message": "Admin access required"
}
```

### 409 Conflict

```json theme={null}
{
  "success": false,
  "error": "User already exists",
  "message": "A user with this email already exists"
}
```

## Validations and Business Rules

* **License value**: Must be one of the allowed licenses (`Essential`, `Growth`, `Ultra`, `Early Access`). Invalid values return 400.
* **License capacity**: Enforced via `checkLicenseCapacity`. If capacity is full for the selected tier, returns 400.
* **Email normalization**: Lowercased and trimmed before validation and storage.
* **Username normalization**: Lowercased and trimmed before validation and storage. Auto-generated from email if not provided.
* **Email format**: Validated with a simple regex; invalid emails return 400.
* **Username format**: Must match `^[a-z0-9.-]{3,30}$`; invalid usernames return 400.
* **Uniqueness**: `email`, `username`, and `name` must be unique. Conflicts return 409.
* **Email invite behavior**: For basic auth, users receive welcome emails with password setup links.

## Normalization and Storage

* `email` and `username` are always stored lowercased and trimmed.

## Typical Error Shapes

### 400 Invalid License

```json theme={null}
{
  "success": false,
  "error": "Invalid license",
  "message": "License must be one of: Essential, Growth, Ultra, Early Access"
}
```

### 400 License Unavailable

```json theme={null}
{
  "success": false,
  "error": "License unavailable",
  "message": "No Growth licenses available (used/limit)"
}
```

### 400 Invalid Email

```json theme={null}
{
  "success": false,
  "error": "Invalid email",
  "message": "Email format is invalid"
}
```

### 400 Invalid Username

```json theme={null}
{
  "success": false,
  "error": "Invalid username",
  "message": "Username must be 3-30 chars, lowercase letters, digits, \".\", "-", or \"\""
}
```

### 409 Conflict (Uniqueness)

```json theme={null}
{
  "success": false,
  "error": "Email/Username/Name already exists",
  "message": "A user with this email already exists"
}
```

## User Roles

| Role           | Description   | Permissions                  |
| -------------- | ------------- | ---------------------------- |
| `admin`        | Administrator | Full system access           |
| `user`         | Regular user  | Standard user access         |
| `globalReader` | Global Reader | Read-only admin panel access |

## License Tiers

| License        | Description       | Features          |
| -------------- | ----------------- | ----------------- |
| `Essential`    | Basic tier        | Limited features  |
| `Growth`       | Professional tier | Enhanced features |
| `Ultra`        | Premium tier      | Full features     |
| `Early Access` | Early access tier | Beta features     |

## Authentication Types

| Type         | Description                                                           |
| ------------ | --------------------------------------------------------------------- |
| `basic`      | Username/password authentication (user receives password setup email) |
| `enterprise` | Enterprise SSO integration (Auth0, Microsoft AD, etc.)                |

## Use Cases

* **User Onboarding**: Create new user accounts for team members
* **Passwordless Onboarding**: Create users who receive email invites to set their own passwords
* **SSO Integration**: Create users who authenticate via external identity providers
* **Bulk User Creation**: Programmatically create multiple users
* **Integration**: Create users from external systems
* **Administrative Tasks**: Manage user accounts through API

## Rate Limits

This endpoint follows the standard rate limits:

* 60 requests per minute
* 1000 requests per hour


## OpenAPI

````yaml POST /users
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /users:
    post:
      tags:
        - User Management
      summary: Create New User
      description: |
        Create a new user account. Only accessible by administrators.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - username
                - email
                - password
              properties:
                name:
                  type: string
                  description: User's full name
                  example: John Doe
                username:
                  type: string
                  description: Unique username
                  example: johndoe
                email:
                  type: string
                  format: email
                  description: User's email address
                  example: john@example.com
                password:
                  type: string
                  description: User's password
                  example: securepassword123
                role:
                  type: string
                  enum:
                    - admin
                    - user
                    - globalReader
                  default: user
                  description: User's role
                  example: user
                license:
                  type: string
                  enum:
                    - Essential
                    - Growth
                    - Ultra
                    - Early Access
                  default: Essential
                  description: User's license tier
                  example: Growth
                roleId:
                  type: string
                  description: Custom role ID (MongoDB ObjectId)
                  example: 60a7c8f5e8b4f5001f7a8c24
                setupCompleted:
                  type: boolean
                  default: false
                  description: Whether user setup is completed
                  example: false
                authType:
                  type: string
                  enum:
                    - basic
                    - auth0
                  default: basic
                  description: Authentication type
                  example: basic
            example:
              name: John Doe
              username: johndoe
              email: john@example.com
              password: securepassword123
              role: user
              license: Growth
              setupCompleted: false
              authType: basic
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: User created successfully
                  user:
                    type: object
                    properties:
                      id:
                        type: string
                        example: 60a7c8f5e8b4f5001f7a8c23
                      name:
                        type: string
                        example: John Doe
                      username:
                        type: string
                        example: johndoe
                      email:
                        type: string
                        example: john@example.com
                      role:
                        type: string
                        example: user
                      license:
                        type: string
                        example: Growth
                      status:
                        type: integer
                        example: 1
                      isVerified:
                        type: boolean
                        example: true
                      setupCompleted:
                        type: boolean
                        example: false
                      authType:
                        type: string
                        example: basic
                      createdAt:
                        type: string
                        format: date-time
                        example: '2024-01-15T10:30:00.000Z'
        '400':
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied - admin only
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: User already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````