Spaces:
Sleeping
Sleeping
File size: 10,978 Bytes
21b0cca 2ae0e41 a22c439 2ae0e41 a22c439 2ae0e41 e69dea3 2ae0e41 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | ---
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
```bash
git clone <repository-url>
cd cuatrolabs-auth-ms
```
2. Create virtual environment
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies
```bash
pip install -r requirements.txt
```
4. Configure environment variables
```bash
cp .env.example .env
# Edit .env with your configuration
```
5. Start the service
```bash
./start_server.sh
```
The service will be available at `http://localhost:8001`
## Configuration
### Environment Variables
Key configuration in `.env`:
```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](https://www.wati.io)
- 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**
```bash
# Test customer OTP
python test_wati_otp.py
# Test staff OTP
python test_staff_wati_otp.py
```
### Documentation
**Customer OTP:**
- Quick Start: [WATI_QUICKSTART.md](WATI_QUICKSTART.md)
- Full Guide: [WATI_WHATSAPP_OTP_INTEGRATION.md](WATI_WHATSAPP_OTP_INTEGRATION.md)
- Implementation: [WATI_IMPLEMENTATION_SUMMARY.md](WATI_IMPLEMENTATION_SUMMARY.md)
**Staff OTP:**
- Full Guide: [STAFF_WATI_OTP_INTEGRATION.md](STAFF_WATI_OTP_INTEGRATION.md)
- Summary: [STAFF_WATI_OTP_COMPLETE.md](../STAFF_WATI_OTP_COMPLETE.md)
## API Endpoints
### System User Authentication
#### POST /auth/login
Login with username and password.
**Request:**
```json
{
"username": "user@example.com",
"password": "password123"
}
```
**Response:**
```json
{
"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:**
```json
{
"phone": "+919999999999"
}
```
**Response:**
```json
{
"success": true,
"message": "OTP sent successfully via WhatsApp",
"expires_in": 300
}
```
#### POST /staff/login/mobile-otp
Verify OTP and authenticate staff user.
**Request:**
```json
{
"phone": "+919999999999",
"otp": "123456"
}
```
**Response:**
```json
{
"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:**
```json
{
"mobile": "+919999999999"
}
```
**Response:**
```json
{
"success": true,
"message": "OTP sent successfully via WhatsApp",
"expires_in": 300
}
```
#### POST /customer/auth/verify-otp
Verify OTP and authenticate customer.
**Request:**
```json
{
"mobile": "+919999999999",
"otp": "123456"
}
```
**Response:**
```json
{
"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:**
```json
{
"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
```bash
pytest tests/
```
### Integration Tests
**Test Customer OTP Flow:**
```bash
python test_customer_auth.py
python test_wati_otp.py
```
**Test Staff OTP Flow:**
```bash
python test_staff_wati_otp.py
```
**Test System User API:**
```bash
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:
```bash
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
```bash
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
- [WATI Quick Start](WATI_QUICKSTART.md)
- [WATI Integration Guide](WATI_WHATSAPP_OTP_INTEGRATION.md)
- [Implementation Summary](WATI_IMPLEMENTATION_SUMMARY.md)
### System Features
- [Customer Profile Updates](CUSTOMER_PROFILE_UPDATE_ENDPOINTS.md)
- [Password Rotation](PASSWORD_ROTATION_POLICY.md)
- [Forgot Password](FORGOT_PASSWORD_FEATURE.md)
- [Error Handling](ERROR_HANDLING_GUIDE.md)
- [Logging Guide](LOGGING_QUICK_REFERENCE.md)
### Testing
- [System Users API Testing](SYSTEM_USERS_API_TESTING.md)
- [Test Scripts README](TEST_SCRIPTS_README.md)
## 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
|