> For the complete documentation index, see [llms.txt](https://developmet-space.gitbook.io/nexgate-api/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developmet-space.gitbook.io/nexgate-api/nexgate-authentication-api.md).

# NexGate Authentication API

NexGate is a social commerce platform that provides secure authentication services with OTP-based verification. This documentation covers the complete authentication API including registration, login,

### API Response Standards

All API responses follow a consistent structure to ensure predictable client integration.

#### Success Response Structure

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Operation completed successfully",
  "action_time": "2024-09-07T15:30:45",
  "data": {
    // Response data object
  }
}
```

#### Error Response Structure

```json
{
  "success": false,
  "httpStatus": "BAD_REQUEST",
  "message": "Error description",
  "action_time": "2024-09-07T15:30:45",
  "data": "Detailed error information or validation errors"
}
```

#### Response Fields Specification

| Field         | Type          | Description                                           |
| ------------- | ------------- | ----------------------------------------------------- |
| `success`     | boolean       | Indicates if the request was successful               |
| `httpStatus`  | string        | HTTP status code as string                            |
| `message`     | string        | Human-readable message describing the result          |
| `action_time` | string        | ISO 8601 timestamp of when the response was generated |
| `data`        | object/string | Response payload or error details                     |

### Base Configuration

#### API Base URL

```
Production: https://apinexgate.glueauth.com/api/v1//auth
Development: http://localhost:8080/api/v1/auth
```

#### Required Headers

```http
Content-Type: application/json
Accept: application/json
```

#### Authentication Headers (for protected endpoints)

```http
Authorization: Bearer {access_token}
```

### Authentication Flow

The NexGate authentication system follows a secure OTP-based verification process:

#### Flow Diagram

```
1. Registration Request → Temp Token + OTP Sent
2. OTP Verification → Access Token + Refresh Token
3. Login Request → Temp Token + OTP Sent  
4. Login OTP Verification → Access Token + Refresh Token
5. Token Refresh → New Access Token
```

#### Key Security Features

* OTP-based verification for all critical operations
* JWT tokens with configurable expiration
* Rate limiting on OTP requests
* Automatic username generation
* Multi-channel OTP delivery support

### API Endpoints

#### Endpoint Access Levels

🔓 **PUBLIC** - No authentication required\
🔒 **PROTECTED** - Requires valid access token

***

#### 1. User Registration

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /register`

**Description:** Creates a new user account and sends verification OTP to the specified channel.

**Request Specification**

```http
POST /api/v1/auth/register
Content-Type: application/json

{
  "phoneNumber": "+14155552671",
  "password": "PiedPiper2024!",
  "email": "richard.hendricks@piedpiper.com",
  "firstName": "Richard",
  "lastName": "Hendricks", 
  "middleName": "Thomas",
  "verificationChannel": "EMAIL"
}
```

**Request Body Schema**

| Field                 | Type   | Constraints                   | Required | Description                |
| --------------------- | ------ | ----------------------------- | -------- | -------------------------- |
| `phoneNumber`         | string | E.164 format                  | ✅        | International phone number |
| `password`            | string | Min 8 chars, complexity rules | ✅        | User password              |
| `email`               | string | Valid email format            | ✅        | User email address         |
| `firstName`           | string | Max 30 characters             | ✅        | User's first name          |
| `lastName`            | string | Max 30 characters             | ✅        | User's last name           |
| `middleName`          | string | Max 30 characters             | ✅        | User's middle name         |
| `verificationChannel` | enum   | See verification channels     | ✅        | OTP delivery method        |

⚠️ **Password Complexity Rules**

* Minimum 8 characters
* At least one uppercase letter (A-Z)
* At least one lowercase letter (a-z)
* At least one digit (0-9)
* At least one special character (@$!%\*?\&#)

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Registration successful",
  "action_time": "2024-09-07T15:30:45",
  "data": {
    "tempToken": "eyJhbGciOiJIUzI1NiJ9...",
    "message": "OTP has been sent to your email",
    "expireAt": "2024-09-07T15:40:45"
  }
}
```

**Error Responses**

**User Already Exists (400)**

```json
{
  "success": false,
  "httpStatus": "BAD_REQUEST",
  "message": "User with provided credentials already exist, please login",
  "action_time": "2024-09-07T15:30:45",
  "data": "User with provided credentials already exist, please login"
}
```

**Validation Errors (422)**

```json
{
  "success": false,
  "httpStatus": "UNPROCESSABLE_ENTITY", 
  "message": "Validation failed",
  "action_time": "2024-09-07T15:30:45",
  "data": {
    "email": "Email should be valid",
    "password": "Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one digit, and one special character",
    "phoneNumber": "Phone number must be in valid international format (e.g., +1234567890)"
  }
}
```

***

#### 2. Verify Registration OTP

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /verify-otp`

**Description:** Verifies the OTP sent during registration and completes account setup.

**Request Specification**

```http
POST /api/v1/auth/verify-otp
Content-Type: application/json

{
  "tempToken": "eyJhbGciOiJIUzI1NiJ9...",
  "otpCode": "123456"
}
```

**Request Body Schema**

| Field       | Type   | Constraints      | Required | Description                           |
| ----------- | ------ | ---------------- | -------- | ------------------------------------- |
| `tempToken` | string | Valid JWT token  | ✅        | Temporary token from registration     |
| `otpCode`   | string | Exactly 6 digits | ✅        | OTP received via verification channel |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Registration completed successfully. You are now logged in.",
  "action_time": "2024-09-07T15:35:45",
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiJ9.ACCESS_TOKEN...",
    "refreshToken": "eyJhbGciOiJIUzI1NiJ9.REFRESH_TOKEN...",
    "userData": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "userName": "richard-a1B2c3D",
      "firstName": "Richard",
      "lastName": "Hendricks",
      "middleName": "Thomas", 
      "email": "richard.hendricks@piedpiper.com",
      "isVerified": true,
      "isEmailVerified": true,
      "isPhoneVerified": false,
      "roles": ["ROLE_NORMAL_USER"],
      "createdAt": "2024-09-07T15:30:45",
      "editedAt": "2024-09-07T15:35:45"
    }
  }
}
```

**Error Responses**

**Invalid OTP (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN",
  "message": "Invalid OTP code",
  "action_time": "2024-09-07T15:35:45",
  "data": "Invalid OTP code"
}
```

**Token Expired (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN", 
  "message": "Token has expired",
  "action_time": "2024-09-07T15:35:45",
  "data": "Token has expired"
}
```

**Max Attempts Exceeded (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN",
  "message": "Maximum verification attempts exceeded", 
  "action_time": "2024-09-07T15:35:45",
  "data": "Maximum verification attempts exceeded"
}
```

***

#### 3. Resend OTP

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /resend-otp`

**Description:** Resends OTP for registration, login, or password reset operations.

**Request Specification**

```http
POST /api/v1/auth/resend-otp
Content-Type: application/json

{
  "tempToken": "eyJhbGciOiJIUzI1NiJ9..."
}
```

**Request Body Schema**

| Field       | Type   | Constraints     | Required | Description                             |
| ----------- | ------ | --------------- | -------- | --------------------------------------- |
| `tempToken` | string | Valid JWT token | ✅        | Temporary token from previous operation |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "OTP resent successfully",
  "action_time": "2024-09-07T15:37:45",
  "data": {
    "newTempToken": "eyJhbGciOiJIUzI1NiJ9.NEW_TOKEN...",
    "message": "OTP has been resent successfully",
    "expireAt": "2024-09-07T15:47:45",
    "attemptsRemaining": 4,
    "nextResendAllowedAt": "2024-09-07T15:39:45"
  }
}
```

**Error Responses**

**Rate Limit Exceeded (400)**

```json
{
  "success": false,
  "httpStatus": "BAD_REQUEST",
  "message": "Resend limit exceeded. Please wait before requesting again.",
  "action_time": "2024-09-07T15:37:45", 
  "data": "Resend limit exceeded. Please wait before requesting again."
}
```

**Invalid Token (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN",
  "message": "Invalid or expired temporary token",
  "action_time": "2024-09-07T15:37:45",
  "data": "Invalid or expired temporary token"
}
```

***

#### 4. User Login

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /login`

**Description:** Authenticates user credentials and sends login OTP.

**Request Specification**

```http
POST /api/v1/auth/login
Content-Type: application/json

{
  "identifier": "dinesh.chugtai@piedpiper.com",
  "password": "JavaIsBetter123!"
}
```

**Request Body Schema**

| Field        | Type   | Constraints               | Required | Description      |
| ------------ | ------ | ------------------------- | -------- | ---------------- |
| `identifier` | string | Email, username, or phone | ✅        | User identifier  |
| `password`   | string | User's password           | ✅        | Account password |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK", 
  "message": "Login successful",
  "action_time": "2024-09-07T16:00:45",
  "data": {
    "tempToken": "eyJhbGciOiJIUzI1NiJ9...",
    "message": "OTP has been sent to your email",
    "expireAt": "2024-09-07T16:10:45"
  }
}
```

**Error Responses**

**User Not Found (404)**

```json
{
  "success": false,
  "httpStatus": "NOT_FOUND",
  "message": "User not found",
  "action_time": "2024-09-07T16:00:45",
  "data": "User not found"
}
```

**Invalid Credentials (401)**

```json
{
  "success": false,
  "httpStatus": "UNAUTHORIZED",
  "message": "Invalid credentials",
  "action_time": "2024-09-07T16:00:45",
  "data": "Invalid credentials"
}
```

***

#### 5. Request Password Reset

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /psw-reset-otp`

**Description:** Initiates password reset process by sending OTP to user's email.

**Request Specification**

```http
POST /api/v1/auth/psw-reset-otp
Content-Type: application/json

{
  "email": "gilfoyle@piedpiper.com"
}
```

**Request Body Schema**

| Field   | Type   | Constraints        | Required | Description              |
| ------- | ------ | ------------------ | -------- | ------------------------ |
| `email` | string | Valid email format | ✅        | Registered email address |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Password reset OTP sent successfully",
  "action_time": "2024-09-07T16:15:45",
  "data": {
    "tempToken": "eyJhbGciOiJIUzI1NiJ9...",
    "message": "Password reset OTP has been sent to your email",
    "expireAt": "2024-09-07T16:25:45"
  }
}
```

**Error Responses**

**Account Not Found (404)**

```json
{
  "success": false,
  "httpStatus": "NOT_FOUND", 
  "message": "No account found with this email",
  "action_time": "2024-09-07T16:15:45",
  "data": "No account found with this email"
}
```

**Account Not Verified (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN",
  "message": "Account is not verified. Please complete registration first.",
  "action_time": "2024-09-07T16:15:45",
  "data": "Account is not verified. Please complete registration first."
}
```

***

#### 6. Reset Password

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /reset-password`

**Description:** Completes password reset using OTP verification.

**Request Specification**

```http
POST /api/v1/auth/reset-password
Content-Type: application/json

{
  "tempToken": "eyJhbGciOiJIUzI1NiJ9...",
  "code": "123456", 
  "newPassword": "NewSecurePass123!"
}
```

**Request Body Schema**

| Field         | Type   | Constraints               | Required | Description                       |
| ------------- | ------ | ------------------------- | -------- | --------------------------------- |
| `tempToken`   | string | Valid JWT token           | ✅        | Token from password reset request |
| `code`        | string | 6-digit OTP               | ✅        | OTP received via email            |
| `newPassword` | string | Password complexity rules | ✅        | New password                      |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Password reset successfully",
  "action_time": "2024-09-07T16:20:45",
  "data": "Your password has been updated. You can now login with your new password."
}
```

**Error Responses**

**Invalid OTP (403)**

```json
{
  "success": false,
  "httpStatus": "FORBIDDEN",
  "message": "Invalid OTP code",
  "action_time": "2024-09-07T16:20:45",
  "data": "Invalid OTP code"
}
```

**Password Validation Error (422)**

```json
{
  "success": false,
  "httpStatus": "UNPROCESSABLE_ENTITY",
  "message": "Validation failed",
  "action_time": "2024-09-07T16:20:45",
  "data": {
    "newPassword": "Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one digit, and one special character"
  }
}
```

***

#### 7. Refresh Token

🔓 **PUBLIC ENDPOINT** - No authentication required

**Endpoint:** `POST /refreshToken`

**Description:** Generates a new access token using a valid refresh token.

**Request Specification**

```http
POST /api/v1/auth/refreshToken
Content-Type: application/json

{
  "refreshToken": "eyJhbGciOiJIUzI1NiJ9.REFRESH_TOKEN..."
}
```

**Request Body Schema**

| Field          | Type   | Constraints             | Required | Description              |
| -------------- | ------ | ----------------------- | -------- | ------------------------ |
| `refreshToken` | string | Valid JWT refresh token | ✅        | Refresh token from login |

**Success Response (200 OK)**

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Token refreshed successful", 
  "action_time": "2024-09-07T17:00:45",
  "data": {
    "newToken": "eyJhbGciOiJIUzI1NiJ9.NEW_ACCESS_TOKEN..."
  }
}
```

**Error Responses**

**Invalid Refresh Token (401)**

```json
{
  "success": false,
  "httpStatus": "UNAUTHORIZED",
  "message": "Invalid token",
  "action_time": "2024-09-07T17:00:45",
  "data": "Invalid token"
}
```

**Expired Refresh Token (401)**

```json
{
  "success": false,
  "httpStatus": "UNAUTHORIZED",
  "message": "Refresh token has expired. Please login again",
  "action_time": "2024-09-07T17:00:45", 
  "data": "Refresh token has expired. Please login again"
}
```

***

### Data Models

#### AccountResponse Schema

```json
{
  "id": "string (UUID)",
  "userName": "string (auto-generated)",
  "firstName": "string (max 30 chars)",
  "lastName": "string (max 30 chars)", 
  "middleName": "string (max 30 chars)",
  "email": "string (email format)",
  "isVerified": "boolean",
  "isEmailVerified": "boolean",
  "isPhoneVerified": "boolean",
  "roles": ["string array"],
  "createdAt": "string (ISO 8601)",
  "editedAt": "string (ISO 8601)"
}
```

#### Token Response Schema

```json
{
  "accessToken": "string (JWT)",
  "refreshToken": "string (JWT)"
}
```

#### Temporary Token Response Schema

```json
{
  "tempToken": "string (JWT)",
  "message": "string",
  "expireAt": "string (ISO 8601)",
  "attemptsRemaining": "number (optional)",
  "nextResendAllowedAt": "string (ISO 8601, optional)"
}
```

#### Verification Channels Enum

```json
[
  "EMAIL",
  "SMS", 
  "WHATSAPP",
  "VOICE_CALL",
  "PUSH_NOTIFICATION",
  "EMAIL_AND_SMS",
  "SMS_AND_WHATSAPP",
  "ALL_CHANNELS"
]
```

#### User Roles Enum

```json
[
  "ROLE_SUPER_ADMIN",
  "ROLE_STAFF_ADMIN", 
  "ROLE_NORMAL_USER"
]
```

ℹ️ **Username Generation Rules**

* Format: `{emailPrefix}-{randomSuffix}`
* Email prefix extracted before @ symbol
* Random suffix: 7 characters (alphanumeric)
* Example: `richard.hendricks@piedpiper.com` → `richard-a1B2c3D`
* Auto-generated to ensure uniqueness

### Error Handling

#### HTTP Status Codes

| Status | Description           | Usage                              |
| ------ | --------------------- | ---------------------------------- |
| 200    | OK                    | Successful operations              |
| 400    | Bad Request           | Rate limits, business logic errors |
| 401    | Unauthorized          | Invalid/expired tokens             |
| 403    | Forbidden             | Verification errors, permissions   |
| 404    | Not Found             | User/resource not found            |
| 422    | Unprocessable Entity  | Validation errors                  |
| 500    | Internal Server Error | Server-side errors                 |

#### Error Response Patterns

**Validation Errors (422)**

* **Structure**: `data` contains field-specific error messages
* **Format**: `{"fieldName": "Error message"}`
* **Usage**: Form validation failures

⚠️ **Validation Error Example**

```json
{
  "success": false,
  "httpStatus": "UNPROCESSABLE_ENTITY",
  "message": "Validation failed",
  "action_time": "2024-09-07T15:30:45",
  "data": {
    "email": "Email should be valid",
    "password": "Password requirements not met"
  }
}
```

**Authentication Errors (401/403)**

* **Structure**: `data` contains error description string
* **Format**: Simple string message
* **Usage**: Token validation, OTP verification

**Rate Limiting Errors (400)**

* **Structure**: `data` contains rate limit information
* **Format**: String with retry information
* **Usage**: Too many requests

**Business Logic Errors (400/404)**

* **Structure**: `data` contains descriptive error message
* **Format**: String explanation
* **Usage**: User not found, account states

### Rate Limiting

#### OTP Request Limits

| Operation          | Limit      | Window     | Cooldown  |
| ------------------ | ---------- | ---------- | --------- |
| Registration OTP   | 5 requests | 10 minutes | N/A       |
| Login OTP          | 5 requests | 10 minutes | N/A       |
| Password Reset OTP | 5 requests | 10 minutes | N/A       |
| Resend OTP         | 5 requests | 10 minutes | 2 minutes |

#### OTP Verification Limits

| Operation        | Max Attempts | Action on Exceed  |
| ---------------- | ------------ | ----------------- |
| OTP Verification | 3 attempts   | Token invalidated |
| Temp Token Usage | 1 use        | Token invalidated |

#### Token Expiration Times

| Token Type      | Expiration | Renewable         |
| --------------- | ---------- | ----------------- |
| Access Token    | 1 hour     | Yes (via refresh) |
| Refresh Token   | 365 days   | No                |
| Temporary Token | 10 minutes | Yes (via resend)  |

⚠️ **Rate Limiting Best Practices**

* Implement exponential backoff for failed requests
* Display remaining attempts to users
* Show cooldown timers for resend operations
* Handle rate limit responses gracefully

### Security Specifications

#### JWT Token Structure

* **Algorithm**: HS256 (HMAC SHA-256)
* **Type Claims**:
  * `ACCESS` for access tokens
  * `REFRESH` for refresh tokens
  * `TEMP` for temporary tokens
* **Standard Claims**: `sub`, `iat`, `exp`
* **Custom Claims**: `tokenType`, `purpose` (for temp tokens)

#### Password Security

* **Encoding**: BCrypt with configurable rounds
* **Complexity**: Enforced server-side
* **History**: Not tracked (current implementation)
* **Reset**: OTP-based verification required

#### OTP Security

* **Generation**: Cryptographically secure random 6-digit codes
* **Storage**: Hashed using BCrypt
* **Delivery**: Multiple channels supported
* **Expiration**: 10 minutes from generation
* **Attempts**: Maximum 3 verification attempts

#### Account Security Features

* **Email Verification**: Required for password reset
* **Account Verification**: Required for full access
* **Role-Based Access**: Three-tier role system
* **Automatic Bucket Creation**: MinIO storage provisioning
* **Audit Trail**: Creation and modification timestamps

ℹ️ **Security Recommendations**

* Store access tokens in memory or sessionStorage
* Store refresh tokens in httpOnly cookies when possible
* Implement proper CSRF protection
* Use HTTPS in production
* Validate all input on client and server side

***

**API Version**: 1.0\
**Last Updated**: September 7, 2025
