Spaces:
Running
A newer version of the Gradio SDK is available:
6.1.0
title: AIDA
emoji: π
colorFrom: purple
colorTo: red
sdk: gradio
sdk_version: 6.0.0
app_file: app.py
pinned: false
license: mit
short_description: The ai model for Lojiz
"""
Lojiz Authentication API - Python FastAPI Edition
Modern, secure, and production-ready authentication backend built with FastAPI, MongoDB, and Resend.
Features
β Dual Authentication - Email or phone-based signup & login β OTP Verification - 4-digit OTP with configurable expiry (15 min default) β Password Reset - Secure password reset flow with temporary tokens β JWT Tokens - 60-day login tokens + 10-minute reset tokens β Bcrypt Hashing - Industry-standard password hashing β Email Templates - Beautiful, responsive HTML email templates via Resend β Rate Limiting - OTP attempt limits (5 max attempts) β MongoDB - Async MongoDB with Motor driver β API Documentation - Auto-generated Swagger docs β Production Ready - Error handling, logging, security best practices
Prerequisites
- Python 3.11+
- MongoDB Atlas account (free tier available)
- Resend account (for email sending)
- Git & GitHub account
- Render.com account (for deployment)
Local Development Setup
1. Clone Repository
git clone https://github.com/yourusername/lojiz-auth-api.git
cd lojiz-auth-api
2. Create Virtual Environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\\Scripts\\activate
3. Install Dependencies
pip install -r requirements.txt
4. Setup Environment Variables
cp .env.example .env
Edit .env with:
DEBUG=True
ENVIRONMENT=development
MONGODB_URL=mongodb://localhost:27017
MONGODB_DATABASE=lojiz
JWT_SECRET=your-secret-key-here
RESEND_API_KEY=your-resend-api-key
RESEND_FROM_EMAIL=noreply@yourdomain.com
5. Run Application
uvicorn app.main:app --reload
Visit: http://localhost:8000/docs (Swagger UI)
Project Structure
lojiz-auth-api/
βββ app/
β βββ core/
β β βββ security.py # JWT & password hashing
β β βββ schemas.py # Pydantic models
β βββ database.py # MongoDB connection
β βββ config.py # Configuration
β βββ models/
β β βββ user.py # User model
β β βββ otp.py # OTP model
β βββ routes/
β β βββ auth.py # Auth endpoints
β βββ services/
β β βββ auth_service.py # Auth logic
β β βββ otp_service.py # OTP logic
β β βββ user_service.py # User logic
β βββ schemas/
β β βββ auth.py # Auth DTOs
β β βββ user.py # User DTOs
β βββ guards/
β β βββ jwt_guard.py # JWT auth
β βββ utils/
β β βββ logger.py # Logging
β βββ main.py # App entry point
βββ requirements.txt
βββ .env.example
βββ .gitignore
βββ Dockerfile
βββ render.yaml
βββ README.md
API Endpoints
Authentication
POST /api/auth/signup
- Create new account
- Returns: Confirmation to check email/phone for OTP
POST /api/auth/verify-signup-otp
- Verify signup OTP
- Returns: User data + JWT token
POST /api/auth/login
- Authenticate with email/phone + password
- Returns: User data + JWT token
POST /api/auth/send-password-reset-otp
- Request password reset
- Returns: Generic success (doesn't reveal if email exists)
POST /api/auth/verify-password-reset-otp
- Verify password reset OTP
- Returns: Temporary reset token
POST /api/auth/reset-password
- Reset password with token
- Header:
x-reset-token
POST /api/auth/resend-otp
- Resend OTP for signup or password reset
User Profile
GET /api/auth/profile
- Get current user profile
- Requires: Bearer token
POST /api/auth/logout
- Logout (client removes token)
- Requires: Bearer token
MongoDB Setup
1. Create MongoDB Atlas Account
- Go to https://www.mongodb.com/cloud/atlas
- Sign up for free
- Create a project
2. Create Cluster
- Choose shared cluster (free)
- Select region closest to your users
- Create cluster
3. Get Connection String
- Click "Connect"
- Choose "Drivers"
- Copy connection string
- Replace
<password>andmyFirstDatabasewith actual values
4. Update .env
MONGODB_URL=mongodb+srv://username:password@cluster.mongodb.net/lojiz?retryWrites=true&w=majority
5. Create Database Indexes (Auto-created on startup)
- Email (unique, sparse)
- Phone (unique, sparse)
- Role
- OTP TTL (15 minutes)
Resend Email Setup
1. Create Resend Account
- Go to https://resend.com
- Sign up
- Get API key from dashboard
2. Verify Domain (Optional for Production)
- Add domain to Resend
- Update DNS records
- Verify domain
3. Update .env
RESEND_API_KEY=re_xxxxxxxxxxxxxxxxxxxx
RESEND_FROM_EMAIL=noreply@yourdomain.com
Password Requirements
Passwords must contain:
- 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 (!@#$%^&*(),.?":{}|<>)
Example: SecurePass123!@
Token Details
Login Token (JWT)
- Expiry: 60 days
- Use Case: Long-lived access token for normal users
- Payload: user_id, email, phone, role
Reset Token (JWT)
- Expiry: 10 minutes
- Use Case: Short-lived token for password reset
- Payload: identifier, purpose
Error Handling
All endpoints return structured error responses:
{
"success": false,
"message": "Error description",
"errors": {}
}
Common HTTP Status Codes:
200 OK- Success400 Bad Request- Validation/business logic error401 Unauthorized- Invalid/missing token404 Not Found- Resource not found409 Conflict- Resource already exists500 Internal Server Error- Server error
Deployment to Render.com
1. Push to GitHub
git add .
git commit -m "Initial commit"
git push origin main
2. Deploy on Render
- Go to https://render.com
- Click "New +"
- Select "Web Service"
- Connect GitHub repository
- Choose Python runtime
- Set build command:
pip install -r requirements.txt - Set start command:
uvicorn app.main:app --host 0.0.0.0 --port $PORT
3. Add Environment Variables
Set in Render dashboard:
ENVIRONMENT=production
DEBUG=False
JWT_SECRET=(generate: python -c "import secrets; print(secrets.token_urlsafe(32))")
MONGODB_URL=<your-mongodb-url>
RESEND_API_KEY=<your-resend-key>
RESEND_FROM_EMAIL=noreply@yourdomain.com
4. Monitor
- Check deployment logs
- Test health endpoint: https://your-app.render.com/health
- View real-time logs in Render dashboard
Testing Endpoints
Using cURL
Signup:
curl -X POST http://localhost:8000/api/auth/signup \\
-H "Content-Type: application/json" \\
-d '{
"first_name": "John",
"last_name": "Doe",
"email": "john@example.com",
"password": "SecurePass123!@",
"role": "renter"
}'
Login:
curl -X POST http://localhost:8000/api/auth/login \\
-H "Content-Type: application/json" \\
-d '{
"identifier": "john@example.com",
"password": "SecurePass123!@"
}'
Get Profile:
curl -X GET http://localhost:8000/api/auth/profile \\
-H "Authorization: Bearer <your-jwt-token>"
Security Best Practices
β Passwords hashed with bcrypt (10 rounds) β JWT tokens signed with HS256 β Password reset tokens expire in 10 minutes β OTP expires in 15 minutes β Max 5 OTP attempts before deletion β CORS configured for specific origins β Sensitive data excluded from responses β Non-root user in Docker β HTTPS enforced in production β Environment variables for secrets
Troubleshooting
MongoDB Connection Error
Error: connect ECONNREFUSED
- Ensure MONGODB_URL is correct
- Check MongoDB Atlas network access
- Verify IP whitelist includes your server
Resend Email Not Sending
Failed to send email
- Check RESEND_API_KEY is valid
- Verify RESEND_FROM_EMAIL is correct
- Check Resend dashboard for quota limits
Token Validation Error
Invalid or expired token
- Ensure Bearer token format:
Authorization: Bearer <token> - Check token hasn't expired (60 days for login)
- Regenerate token if needed
Performance Tips
- MongoDB Indexes: Already created on startup
- Async/Await: All I/O operations are async
- Connection Pooling: Motor manages connection pool
- Caching: Implement Redis for OTP caching (future)
- Rate Limiting: Add rate limiter middleware (future)
Future Enhancements
- Refresh token rotation
- Social login (Google, GitHub)
- 2FA support
- Account recovery questions
- Redis caching layer
- Rate limiting middleware
- API key authentication
- Admin dashboard
License
MIT License - see LICENSE file
Support
For issues or questions:
- GitHub Issues: https://github.com/yourusername/lojiz-auth-api/issues
- Email: support@lojiz.com
Built with β€οΈ using FastAPI, MongoDB, and Resend """
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference