--- 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 ```bash git clone https://github.com/yourusername/lojiz-auth-api.git cd lojiz-auth-api ``` ### 2. Create Virtual Environment ```bash python3 -m venv venv source venv/bin/activate # On Windows: venv\\Scripts\\activate ``` ### 3. Install Dependencies ```bash pip install -r requirements.txt ``` ### 4. Setup Environment Variables ```bash 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 ```bash 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 `` and `myFirstDatabase` with 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: ```json { "success": false, "message": "Error description", "errors": {} } ``` Common HTTP Status Codes: - `200 OK` - Success - `400 Bad Request` - Validation/business logic error - `401 Unauthorized` - Invalid/missing token - `404 Not Found` - Resource not found - `409 Conflict` - Resource already exists - `500 Internal Server Error` - Server error ## Deployment to Render.com ### 1. Push to GitHub ```bash 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= RESEND_API_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:** ```bash 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:** ```bash curl -X POST http://localhost:8000/api/auth/login \\ -H "Content-Type: application/json" \\ -d '{ "identifier": "john@example.com", "password": "SecurePass123!@" }' ``` **Get Profile:** ```bash curl -X GET http://localhost:8000/api/auth/profile \\ -H "Authorization: Bearer " ``` ## 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 ` - Check token hasn't expired (60 days for login) - Regenerate token if needed ## Performance Tips 1. **MongoDB Indexes**: Already created on startup 2. **Async/Await**: All I/O operations are async 3. **Connection Pooling**: Motor manages connection pool 4. **Caching**: Implement Redis for OTP caching (future) 5. **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