Skip to main content

Auth Service API

The Auth Service handles user authentication, role-based access control (RBAC), and API key management. It provides secure JWT-based authentication and granular permission management for multi-tenant applications.
Base URL: https://paymentgateway.redahaloubi.com/api/v1All endpoints are prefixed with /api/v1

Authentication Methods

The Auth Service supports multiple authentication methods depending on the use case:
Use Case: Dashboard, merchant portals, web applications
Authorization: Bearer {access_token}
Token Lifecycle:
  • Access Token: 24 hours
  • Refresh Token: 7 days
  • Algorithm: HS256 (HMAC-SHA256)
Obtain tokens via: /auth/login endpoint

Rate Limits

Login Endpoint

5 requests per minute per IP addressAfter 5 failed login attempts, account is locked for 30 minutes

Register Endpoint

7 requests per hour per IP addressPrevents spam account creation

Other Endpoints

100 requests per second per userStandard rate limit for authenticated endpoints

API Key Endpoints

50 requests per second per merchantUsed for payment processing

Authentication Endpoints

Register User

POST
endpoint
/auth/register
Create a new user account. Email verification is required before full access. Request Body
name
string
required
Full name of the userMin length: 2 characters
email
string
required
Valid email addressFormat: Standard email validationUnique: Must not be already registered
password
string
required
Secure passwordMin length: 8 charactersSecurity: Hashed with bcrypt (cost 10)
Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Merchant",
    "email": "[email protected]",
    "password": "SecurePass123!"
  }'
Response (201 Created)
{
  "success": true,
  "data": {
    "user": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "John Merchant",
      "email": "[email protected]",
      "email_verified": false,
      "status": "pending_verification",
      "created_at": "2026-01-24T10:00:00Z"
    }
  },
  "message": "Registration successful. Please verify your email."
}
400 Bad Request - Email Already Exists
{
  "success": false,
  "error": "email already registered"
}
400 Bad Request - Weak Password
{
  "success": false,
  "error": "password must be at least 8 characters"
}
400 Bad Request - Invalid Email
{
  "success": false,
  "error": "invalid email format"
}
429 Too Many Requests
{
  "success": false,
  "error": "rate limit exceeded. try again in 3600 seconds"
}

Login

POST
endpoint
/auth/login
Authenticate user and receive JWT access and refresh tokens. Request Body
email
string
required
Registered email address
password
string
required
User’s password
Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123!"
  }'
Response (200 OK)
{
  "success": true,
  "data": {
    "user": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "John Merchant",
      "email": "[email protected]",
      "email_verified": false,
      "status": "active"
    },
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1NTBlODQwMC1lMjliLTQxZDQtYTcxNi00NDY2NTU0NDAwMDAiLCJleHAiOjE3MDU4NTcxMDB9.xXx_xXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1NTBlODQwMC1lMjliLTQxZDQtYTcxNi00NDY2NTU0NDAwMDAiLCJ0eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwNjI5MzEwMH0.yYy_yYyYyYyYyYyYyYyYyYyYyYyYyYyYyYyYyYyYyYy",
    "token_type": "Bearer",
    "expires_in": 86400
  }
}
401 Unauthorized - Invalid Credentials
{
  "success": false,
  "error": "invalid email or password"
}
401 Unauthorized - Account Locked
{
  "success": false,
  "error": "account locked due to too many failed login attempts. try again in 30 minutes"
}
401 Unauthorized - Account Suspended
{
  "success": false,
  "error": "account suspended. please contact support"
}
429 Too Many Requests
{
  "success": false,
  "error": "too many login attempts. try again in 60 seconds"
}
Account Lockout Policy:
  • After 5 failed login attempts, the account is locked for 30 minutes
  • Failed attempts are tracked per email address
  • Lockout is automatic and cannot be manually bypassed

Refresh Token

POST
endpoint
/auth/refresh
Get a new access token using a refresh token. Use this to maintain user sessions without requiring re-login. Request Body
refresh_token
string
required
Valid refresh token from login response
Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'
Response (200 OK)
{
  "success": true,
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.NEW_ACCESS_TOKEN...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.NEW_REFRESH_TOKEN...",
    "token_type": "Bearer",
    "expires_in": 86400
  }
}
401 Unauthorized - Invalid Refresh Token
{
  "success": false,
  "error": "invalid or expired refresh token"
}
401 Unauthorized - Token Revoked
{
  "success": false,
  "error": "refresh token has been revoked"
}
Token Rotation: Each refresh returns a new access token and a new refresh token. The old refresh token is invalidated.

Get Profile

GET
endpoint
/auth/profile
Get the authenticated user’s profile information. Authentication Required: JWT Bearer Token Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/auth/profile \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "user": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "John Merchant",
      "email": "[email protected]",
      "email_verified": false,
      "status": "active",
      "created_at": "2026-01-24T10:00:00Z",
      "last_login_at": "2026-01-24T15:30:00Z",
      "last_login_ip": "192.168.1.100"
    }
  }
}
401 Unauthorized - Missing Token
{
  "success": false,
  "error": "authorization header required"
}
401 Unauthorized - Invalid Token
{
  "success": false,
  "error": "invalid or expired access token"
}

Logout

POST
endpoint
/auth/logout
Revoke the current session and invalidate the access token. Authentication Required: JWT Bearer Token Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/auth/logout \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "message": "logged out successfully"
}
Single Device Logout: This only logs out the current session. To logout from all devices, use the “Logout All” endpoint (coming soon).

Change Password

POST
endpoint
/auth/change-password
Change the user’s password. This action logs out all sessions and requires re-login. Authentication Required: JWT Bearer Token Request Body
old_password
string
required
Current password for verification
new_password
string
required
New password (min 8 characters)
Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/auth/change-password \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "old_password": "SecurePass123!",
    "new_password": "NewSecurePass456!"
  }'
Response (200 OK)
{
  "success": true,
  "message": "password changed successfully. please login again"
}
400 Bad Request - Incorrect Old Password
{
  "success": false,
  "error": "old password is incorrect"
}
400 Bad Request - Weak Password
{
  "success": false,
  "error": "new password must be at least 8 characters"
}
400 Bad Request - Same Password
{
  "success": false,
  "error": "new password must be different from old password"
}
Security Notice: Changing password will revoke all active sessions on all devices. User must login again with the new password.

Get Sessions

GET
endpoint
/auth/sessions
List all active sessions for the authenticated user across all devices. Authentication Required: JWT Bearer Token Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/auth/sessions \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "sessions": [
      {
        "id": "session_abc123def456",
        "ip_address": "192.168.1.100",
        "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
        "created_at": "2026-01-24T10:00:00Z",
        "expires_at": "2026-01-25T10:00:00Z",
        "is_current": true
      },
      {
        "id": "session_xyz789uvw012",
        "ip_address": "10.0.1.50",
        "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)",
        "created_at": "2026-01-23T14:30:00Z",
        "expires_at": "2026-01-24T14:30:00Z",
        "is_current": false
      }
    ]
  }
}
Session Management: The is_current flag indicates the session making this request. All sessions expire automatically after 24 hours.

Role & Permission Endpoints

Get All Roles

GET
endpoint
/roles
Get a list of all available roles in the system. Authentication Required: JWT Bearer Token Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/roles \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "roles": [
      {
        "id": "role_owner_123",
        "name": "Owner",
        "description": "Merchant owner - full access to all features"
      },
      {
        "id": "role_admin_456",
        "name": "Admin",
        "description": "Full access to payments, invoices, team, and settings"
      },
      {
        "id": "role_manager_789",
        "name": "Manager",
        "description": "Can manage payments and invoices"
      },
      {
        "id": "role_staff_012",
        "name": "Staff",
        "description": "Can only view and create transactions"
      }
    ]
  }
}

Role Hierarchy

1

Owner

Full Control
  • All permissions
  • Cannot be removed
  • Automatically assigned on merchant creation
  • Can manage team and assign roles
2

Admin

Administrative Access
  • Manage payments, invoices, reports
  • Manage team members (except owner)
  • Configure settings and webhooks
  • Cannot delete merchant
3

Manager

Operational Access
  • Create and manage payments
  • Issue refunds
  • View reports
  • Cannot manage team or settings
4

Staff

Limited Access
  • View transactions
  • Create payments
  • No refund capability
  • Read-only access to reports

Get Role Details

GET
endpoint
/roles/:id
Get detailed information about a specific role including all its permissions. Authentication Required: JWT Bearer Token Path Parameters
id
string
required
Role ID (e.g., role_admin_456)
Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/roles/role_admin_456 \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "role": {
      "id": "role_admin_456",
      "name": "Admin",
      "description": "Full access to payments, invoices, team, and settings",
      "permissions": [
        {
          "id": "perm_transactions_read",
          "resource": "transactions",
          "action": "read",
          "description": "View transaction details"
        },
        {
          "id": "perm_transactions_create",
          "resource": "transactions",
          "action": "create",
          "description": "Create new transactions"
        },
        {
          "id": "perm_transactions_refund",
          "resource": "transactions",
          "action": "refund",
          "description": "Issue refunds"
        },
        {
          "id": "perm_team_manage",
          "resource": "team",
          "action": "manage",
          "description": "Manage team members"
        },
        {
          "id": "perm_settings_update",
          "resource": "settings",
          "action": "update",
          "description": "Update merchant settings"
        }
      ]
    }
  }
}

Permission Format

All permissions follow the resource:action format:

Resources

  • transactions
  • invoices
  • team
  • settings
  • reports
  • api_keys

Actions

  • read - View data
  • create - Create new records
  • update - Modify existing records
  • delete - Remove records
  • manage - Full CRUD access

Assign Role to User

POST
endpoint
/roles/assign
Assign a role to a user for a specific merchant. Users can have different roles across different merchants. Authentication Required: JWT Bearer Token Required Permission: team:manage in the target merchant Request Body
user_id
string
required
ID of the user receiving the role
role_id
string
required
ID of the role to assign
merchant_id
string
required
ID of the merchant context
Example Request
curl -X POST https://paymentgateway.redahaloubi.com/api/v1/roles/assign \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_abc123",
    "role_id": "role_manager_789",
    "merchant_id": "merchant_xyz456"
  }'
Response (200 OK)
{
  "success": true,
  "message": "role assigned successfully",
  "data": {
    "user_id": "user_abc123",
    "role_id": "role_manager_789",
    "merchant_id": "merchant_xyz456",
    "assigned_at": "2026-01-24T10:00:00Z",
    "assigned_by": "user_def789"
  }
}
403 Forbidden - Insufficient Permissions
{
  "success": false,
  "error": "you do not have permission to manage team members"
}
404 Not Found - User Not Found
{
  "success": false,
  "error": "user not found"
}
409 Conflict - Role Already Assigned
{
  "success": false,
  "error": "user already has this role in this merchant"
}

Remove Role from User

DELETE
endpoint
/roles/assign
Remove a role assignment from a user in a specific merchant. Authentication Required: JWT Bearer Token Required Permission: team:manage in the target merchant Request Body
user_id
string
required
ID of the user
role_id
string
required
ID of the role to remove
merchant_id
string
required
ID of the merchant context
Example Request
curl -X DELETE https://paymentgateway.redahaloubi.com/api/v1/roles/assign \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_abc123",
    "role_id": "role_manager_789",
    "merchant_id": "merchant_xyz456"
  }'
Response (200 OK)
{
  "success": true,
  "message": "role removed successfully"
}
Cannot Remove Owner: The Owner role cannot be removed. Transfer ownership to another user before attempting removal.

Get User Roles

GET
endpoint
/roles/user/:user_id/merchant/:merchant_id
Get all roles assigned to a user in a specific merchant. Authentication Required: JWT Bearer Token Path Parameters
user_id
string
required
User ID
merchant_id
string
required
Merchant ID
Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/roles/user/user_abc123/merchant/merchant_xyz456 \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "roles": [
      {
        "id": "role_admin_456",
        "name": "Admin",
        "description": "Full access to payments, invoices, team, and settings",
        "assigned_at": "2026-01-20T14:00:00Z"
      }
    ]
  }
}

Get User Permissions

GET
endpoint
/roles/user/:user_id/merchant/:merchant_id/permissions
Get all effective permissions for a user in a specific merchant (aggregated from all assigned roles). Authentication Required: JWT Bearer Token Path Parameters
user_id
string
required
User ID
merchant_id
string
required
Merchant ID
Example Request
curl -X GET https://paymentgateway.redahaloubi.com/api/v1/roles/user/user_abc123/merchant/merchant_xyz456/permissions \
  -H "Authorization: Bearer {access_token}"
Response (200 OK)
{
  "success": true,
  "data": {
    "permissions": [
      {
        "resource": "transactions",
        "action": "read"
      },
      {
        "resource": "transactions",
        "action": "create"
      },
      {
        "resource": "transactions",
        "action": "refund"
      },
      {
        "resource": "invoices",
        "action": "read"
      },
      {
        "resource": "team",
        "action": "manage"
      },
      {
        "resource": "settings",
        "action": "update"
      }
    ]
  }
}
Permission Caching: Permissions are cached in Redis for 10 minutes for fast validation. Changes to roles take effect within 10 minutes.

Security Best Practices

Requirements:
  • Minimum 8 characters
  • Use a mix of uppercase, lowercase, numbers, and symbols
  • Avoid common passwords and dictionary words
Storage:
  • Passwords are hashed with bcrypt (cost factor 10)
  • Original passwords are never stored or logged
  • Cannot be retrieved, only reset
Access Tokens:
  • 24-hour expiry
  • Stored hashed in database (SHA-256)
  • Automatically revoked on password change
Refresh Tokens:
  • 7-day expiry
  • Single-use (rotated on each refresh)
  • Revoked on logout
Best Practices:
  • Store tokens securely (e.g., httpOnly cookies, secure storage)
  • Never expose tokens in URLs or logs
  • Implement token refresh before expiry
Generation:
  • Cryptographically secure random generation
  • 64 characters of entropy
  • SHA-256 hashed in database
Usage:
  • Use different keys for production and testing
  • Rotate keys every 90 days
  • Never commit keys to version control
  • Use environment variables or secrets managers
Monitoring:
  • Track last_used_at for each key
  • Alert on unusual usage patterns
  • Deactivate unused keys
Session Tracking:
  • IP address and user agent logged
  • Session duration: 24 hours
  • Concurrent sessions allowed
Session Invalidation:
  • Logout: Current session only
  • Password change: All sessions
  • Manual revocation: Specific session
Redis Storage:
  • Sessions cached for fast validation
  • TTL matches token expiry
  • Automatic cleanup on expiry
Failed Login Protection:
  • 5 attempts = 30-minute lockout
  • Tracked per email address
  • Automatic unlock after timeout
Rate Limiting:
  • Login: 5 requests/minute per IP
  • Register: 3 requests/hour per IP
  • API calls: 100 requests/second per user
Suspicious Activity:
  • Login from new IP/device logs event
  • Multiple failed attempts trigger alert
  • Account suspension for security violations

Error Reference

Common error codes and their meanings:
400
Bad Request
Invalid request format, missing required fields, or validation errorsCommon causes:
  • Missing required fields
  • Invalid email format
  • Password too short
  • Invalid UUID format
401
Unauthorized
Authentication failed or token invalidCommon causes:
  • Missing Authorization header
  • Expired access token
  • Invalid API key
  • Account locked or suspended
403
Forbidden
Authenticated but lacks required permissionsCommon causes:
  • Insufficient role permissions
  • Attempting to access another merchant’s data
  • Trying to perform owner-only actions
404
Not Found
Requested resource doesn’t existCommon causes:
  • Invalid user ID
  • Role ID not found
  • API key doesn’t exist
409
Conflict
Request conflicts with current stateCommon causes:
  • Email already registered
  • Role already assigned
  • API key name already exists
429
Too Many Requests
Rate limit exceededResponse includes:
  • retry_after: Seconds until next allowed request
  • Rate limit headers showing remaining quota
500
Internal Server Error
Unexpected server errorAction:
  • Retry the request
  • Contact support if persistent

Rate Limit Headers

All responses include rate limit information:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1706097600
X-RateLimit-Endpoint: auth
X-RateLimit-Limit
integer
Maximum requests allowed in the current window
X-RateLimit-Remaining
integer
Requests remaining in the current window
X-RateLimit-Reset
integer
Unix timestamp when the rate limit resets
X-RateLimit-Endpoint
string
Endpoint category (e.g., auth, payments, etc.)

Next Steps


Questions? Contact support at [email protected]