cuatrolabs-auth-ms / README.md
MukeshKapoor25's picture
chore(config): Update WATI customer OTP template name
a22c439
metadata
title: Cuatrolabs Auth Ms
emoji: 📊
colorFrom: green
colorTo: green
sdk: docker
pinned: false

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

Cuatrolabs Auth Microservice

Authentication and authorization microservice for the Cuatrolabs platform.

Features

System User Authentication

  • JWT-based authentication for system users
  • Role-based access control (RBAC)
  • Password rotation policies
  • Account lockout protection
  • Forgot password functionality
  • Session management

Customer Authentication (Mobile App)

  • WhatsApp OTP Authentication via WATI API
  • Mobile number-based login
  • Automatic customer registration
  • Profile management (name, email, gender, DOB)
  • JWT token generation for customers
  • Secure OTP delivery via WhatsApp

Staff Authentication (Employee/Staff Users)

  • WhatsApp OTP Authentication via WATI API
  • Mobile number-based login for staff
  • Role validation (staff only, excludes admin)
  • Status validation (active users only)
  • JWT token generation with merchant context
  • Secure OTP delivery via WhatsApp
  • Separate OTP storage from customers

Security Features

  • Password hashing with bcrypt
  • JWT token generation and validation
  • Rate limiting for OTP requests
  • Maximum login attempt tracking
  • Account lockout after failed attempts
  • Password expiration policies
  • Secure token storage

Architecture

Technology Stack

  • Framework: FastAPI (Python)
  • Database: MongoDB (NoSQL)
  • Cache: Redis
  • Authentication: JWT (JSON Web Tokens)
  • WhatsApp Integration: WATI API
  • Password Hashing: bcrypt

Key Components

  1. System Users Module (app/system_users/)

    • System user management
    • Role and permission management
    • Password policies
  2. Customer Auth Module (app/auth/)

    • Customer OTP authentication
    • WhatsApp OTP delivery via WATI
    • Customer profile management
    • Token generation
  3. Internal Module (app/internal/)

    • Internal authentication utilities
    • Token validation
    • Permission checking

Quick Start

Prerequisites

  • Python 3.9+
  • MongoDB
  • Redis
  • WATI account (for WhatsApp OTP)

Installation

  1. Clone the repository
git clone <repository-url>
cd cuatrolabs-auth-ms
  1. Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Configure environment variables
cp .env.example .env
# Edit .env with your configuration
  1. Start the service
./start_server.sh

The service will be available at http://localhost:8001

Configuration

Environment Variables

Key configuration in .env:

# MongoDB
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/
MONGODB_DB_NAME=cuatrolabs

# Redis
REDIS_HOST=your-redis-host.com
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password

# JWT
SECRET_KEY=your-secret-key
TOKEN_EXPIRATION_HOURS=8

# WATI WhatsApp API (for Customer OTP)
WATI_API_ENDPOINT=https://live-mt-server.wati.io/YOUR_TENANT_ID
WATI_ACCESS_TOKEN=your-wati-bearer-token
WATI_OTP_TEMPLATE_NAME=cust_otp

See .env.example for complete configuration options.

WhatsApp OTP Integration

Overview

Both customer and staff authentication use WATI WhatsApp API to send OTP codes via WhatsApp messages.

Setup

  1. Create WATI Account

    • Sign up at WATI
    • Choose Growth, Pro, or Business plan
  2. Create Authentication Templates

    Customer Template: cust_otp

    Your OTP for login is: {{otp_code}}
    This code will expire in {{expiry_time}} minutes.
    Do not share this code with anyone.
    

    Staff Template: staff_otp_login

    Your staff login OTP is: {{otp_code}}
    This code will expire in {{expiry_time}} minutes.
    Do not share this code with anyone.
    
    • Add "Copy Code" button
    • Submit for WhatsApp approval
  3. Configure Environment

    • Add WATI credentials to .env
    • Set template names
  4. Test Integration

# Test customer OTP
python test_wati_otp.py

# Test staff OTP
python test_staff_wati_otp.py

Documentation

Customer OTP:

Staff OTP:

API Endpoints

System User Authentication

POST /auth/login

Login with username and password.

Request:

{
  "username": "user@example.com",
  "password": "password123"
}

Response:

{
  "access_token": "eyJhbGci...",
  "token_type": "bearer",
  "expires_in": 28800
}

POST /auth/forgot-password

Request password reset.

POST /auth/reset-password

Reset password with token.

Staff Authentication

POST /staff/send-otp

Send OTP to staff mobile number via WhatsApp.

Request:

{
  "phone": "+919999999999"
}

Response:

{
  "success": true,
  "message": "OTP sent successfully via WhatsApp",
  "expires_in": 300
}

POST /staff/login/mobile-otp

Verify OTP and authenticate staff user.

Request:

{
  "phone": "+919999999999",
  "otp": "123456"
}

Response:

{
  "access_token": "eyJhbGci...",
  "token_type": "bearer",
  "expires_in": 28800,
  "user_info": {
    "user_id": "uuid",
    "username": "staff@example.com",
    "role": "staff",
    "merchant_id": "merchant-uuid"
  }
}

GET /staff/me

Get current staff user profile (requires authentication).

POST /staff/logout

Logout current staff user (requires authentication).

Customer Authentication

POST /customer/auth/send-otp

Send OTP to customer's WhatsApp.

Request:

{
  "mobile": "+919999999999"
}

Response:

{
  "success": true,
  "message": "OTP sent successfully via WhatsApp",
  "expires_in": 300
}

POST /customer/auth/verify-otp

Verify OTP and authenticate customer.

Request:

{
  "mobile": "+919999999999",
  "otp": "123456"
}

Response:

{
  "access_token": "eyJhbGci...",
  "customer_id": "uuid",
  "is_new_customer": false,
  "token_type": "bearer",
  "expires_in": 28800
}

GET /customer/auth/profile

Get customer profile (requires authentication).

PUT /customer/auth/profile

Update customer profile.

Request:

{
  "name": "John Doe",
  "email": "john@example.com",
  "gender": "male",
  "dob": "1990-01-01"
}

System User Management

POST /system-users/create

Create new system user.

GET /system-users/{user_id}

Get system user details.

PUT /system-users/{user_id}

Update system user.

POST /system-users/list

List system users with filters.

Testing

Unit Tests

pytest tests/

Integration Tests

Test Customer OTP Flow:

python test_customer_auth.py
python test_wati_otp.py

Test Staff OTP Flow:

python test_staff_wati_otp.py

Test System User API:

python test_system_users_api.py

Manual Testing

Use the provided test scripts in the root directory:

  • test_customer_auth.py - Customer authentication flow
  • test_forgot_password.py - Password reset flow
  • test_password_rotation.py - Password rotation policies
  • test_system_users_api.py - System user management

Database Schema

Collections

system_users

System user accounts with roles and permissions.

scm_customers

Customer accounts for mobile app users.

customer_otps

OTP codes for customer authentication.

staff_otps

OTP codes for staff authentication (separate from customer OTPs).

password_reset_tokens

Tokens for password reset functionality.

user_sessions

Active user sessions.

Security

Best Practices

  1. Environment Variables: Never commit .env files
  2. Token Security: Rotate JWT secret keys regularly
  3. Password Policies: Enforce strong passwords
  4. Rate Limiting: Implement rate limiting on OTP endpoints
  5. Logging: Monitor authentication attempts
  6. HTTPS: Always use HTTPS in production

Password Requirements

  • Minimum 8 characters
  • At least one uppercase letter
  • At least one lowercase letter
  • At least one number
  • At least one special character

OTP Security

  • 6-digit random codes
  • 5-minute expiration
  • Maximum 3 verification attempts
  • One-time use only
  • Secure delivery via WhatsApp

Logging

Logs are stored in logs/ directory:

  • app.log - All logs
  • app_info.log - Info level logs
  • app_errors.log - Error level logs

Log Levels

  • INFO: Successful operations
  • WARNING: Invalid attempts, expired tokens
  • ERROR: API failures, system errors

Deployment

Docker

Build and run with Docker:

docker build -t cuatrolabs-auth-ms .
docker run -p 8001:8001 --env-file .env cuatrolabs-auth-ms

Kubernetes

Deploy using Helm charts in cuatrolabs-deploy repository.

Monitoring

Health Check

curl http://localhost:8001/health

Metrics to Monitor

  • Authentication success/failure rates
  • OTP delivery success rates
  • Token generation rates
  • Failed login attempts
  • Account lockouts
  • API response times

Troubleshooting

Common Issues

OTP Not Received

  • Verify WATI credentials in .env
  • Check mobile number is WhatsApp-enabled
  • Review logs for API errors
  • Verify template is approved in WATI

Authentication Failures

  • Check MongoDB connection
  • Verify JWT secret key
  • Review user credentials
  • Check account lockout status

Database Connection Issues

  • Verify MongoDB URI
  • Check network connectivity
  • Ensure database exists
  • Review MongoDB logs

Documentation

Customer Authentication

System Features

Testing

Contributing

  1. Create feature branch
  2. Make changes
  3. Add tests
  4. Update documentation
  5. Submit pull request

Support

For issues or questions:

  • Check documentation in this repository
  • Review logs in logs/ directory
  • Contact development team

License

Proprietary - Cuatrolabs


Version: 1.0.0
Last Updated: February 5, 2026