Imagine your favorite app suddenly let anyone access your private messages or game progress. Terrifying, right? Today we're building the digital bouncer that keeps the wrong people out and the right people in - a rock-solid authentication system.
Why Authentication Matters in Distributed Systems
Authentication is like having a secure ID system for a massive concert venue with multiple entrances, VIP areas, and backstage access. In distributed systems, your authentication service becomes a critical shared component that every other microservice depends on. Companies like Netflix and Uber process millions of authentication requests per second across hundreds of services.
The beauty of proper authentication architecture is that once built correctly, it scales effortlessly and provides security guarantees across your entire system ecosystem.
Core Concepts: The Authentication Trinity
Authentication (Who are you?), Authorization (What can you do?), and Session Management (How long can you stay?) form the security foundation. Think of it like airport security: they check your ID, verify your boarding pass permissions, and track how long you're in the secure area.
JWT tokens are like smart wristbands at an amusement park - they contain encrypted information about who you are and what rides you can access, eliminating the need to check with central security every time.
Real-World Context
Every time you log into Discord, TikTok, or GitHub, you're interacting with sophisticated authentication systems handling millions of concurrent users. These systems must be:
Stateless (work across multiple servers)
Secure (resistant to common attacks)
Fast (sub-100ms response times)
Scalable (handle traffic spikes)
Today's Implementation Journey
Source code Repository : https://github.com/sysdr/aie/tree/main/day4
We're building a production-ready authentication microservice that integrates seamlessly with our quiz platform from Day 3. You'll create registration, login, and session management endpoints with proper error handling and security best practices.
Tangible Outcome: By day's end, you'll have a containerized authentication service that can securely manage thousands of users, complete with automated tests and a simple frontend interface.
🧠 AI Quiz Platform - Authentication Service
A production-ready, containerized authentication microservice built with FastAPI, MongoDB, and JWT tokens. This service provides secure user registration, login, and session management for the AI Quiz Platform.
🎯 Learning Objectives
By completing this project, you will learn:
JWT-based authentication with proper token management
Password security with bcrypt hashing and strength validation
API design with FastAPI and async/await patterns
Database integration with MongoDB and proper data modeling
Containerization with Docker and Docker Compose
Testing strategies including unit and integration tests
Security best practices for web applications
🏗️ Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │────│ Auth API │────│ MongoDB │
│ (React/HTML) │ │ (FastAPI) │ │ (Database) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Key Components:
Authentication Service: FastAPI-based REST API
Database Layer: MongoDB with proper indexing
Security Layer: JWT tokens + bcrypt password hashing
Frontend Interface: Simple HTML/CSS/JS client
Container Stack: Docker + Docker Compose
Project Structure Setup
# Clone and enter the project directory
git clone <your-repo> ai-quiz-auth
cd ai-quiz-auth
# Make the deployment script executable
chmod +x deploy.sh
# Run complete deployment (builds, tests, and starts everything)
./deploy.sh
That's it! The script will:
✅ Check prerequisites (Python, Docker, etc.)
🏗️ Install dependencies and build Docker images
🧪 Run comprehensive tests (unit + integration)
🚀 Start all services (API + Database)
🔍 Verify everything is working
🌐 Open the service at
http://localhost:8000
📱 Usage
Web Interface
Open
http://localhost:8000
in your browser
Register a new account with a strong password
Login to receive your JWT token
Test protected endpoints from the dashboard
API Endpoints
Example API Usage
# Register a new user
curl -X POST http://localhost:8000/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"email": "john@example.com",
"password": "SecurePass123!",
"full_name": "John Doe"
}'
# Login to get token
curl -X POST http://localhost:8000/auth/login \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"password": "SecurePass123!"
}'
# Use token to access protected endpoint
curl -X GET http://localhost:8000/auth/me \
-H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"
🧪 Testing
Run All Tests
# Comprehensive test suite
python run_tests.py
# Or use the deployment script
./deploy.sh test
Individual Test Types
# Unit tests only
python -m pytest tests/unit/ -v
# Integration tests only
python -m pytest tests/integration/ -v
# Manual API testing
curl http://localhost:8000/health
Expected Test Results
✅ Unit Tests: Password hashing, JWT creation, data validation
✅ Integration Tests: Full API workflows, database interactions
✅ Security Tests: Token validation, unauthorized access protection
✅ Performance Tests: Response times, concurrent request handling
🔒 Security Features
Password Security
Minimum Requirements: 8+ characters, uppercase, lowercase, numbers, symbols
Bcrypt Hashing: Industry-standard password encryption
Strength Validation: Real-time password strength checking
Token Security
JWT Tokens: Stateless, scalable authentication
30-minute Expiry: Automatic token expiration
Secure Headers: Proper authorization header handling
Token Validation: Comprehensive token verification
API Security
Input Validation: Pydantic models with strict validation
Error Handling: No sensitive information in error responses
CORS Configuration: Controlled cross-origin requests
Rate Limiting Ready: Architecture supports rate limiting
🗄️ Database Schema
Users Collection
{
"_id": ObjectId,
"username": String (unique, indexed),
"email": String (unique, indexed),
"full_name": String,
"hashed_password": String,
"is_active": Boolean,
"created_at": Date (indexed),
"last_login": Date,
"last_activity": Date
}
Indexes
username
(unique)email
(unique)created_at
(for queries)
🐳 Container Management
Service Management
# Start services
./deploy.sh start
# Stop services
./deploy.sh stop
# View service status
./deploy.sh status
# View logs
./deploy.sh logs
# Complete cleanup
./deploy.sh clean
Manual Docker Commands
# Build image
docker build -t ai-quiz-auth -f docker/Dockerfile .
# Start with Docker Compose
docker-compose -f docker/docker-compose.yml up -d
# View logs
docker-compose -f docker/docker-compose.yml logs -f
# Stop services
docker-compose -f docker/docker-compose.yml down
🔧 Development
Project Structure
ai-quiz-auth/
├── src/
│ ├── auth/
│ │ ├── auth_service.py # Business logic
│ │ └── routes.py # API endpoints
│ ├── models/
│ │ └── user_model.py # Data models
│ ├── utils/
│ │ ├── jwt_utils.py # JWT handling
│ │ └── password_utils.py # Password utilities
│ └── main.py # FastAPI application
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── frontend/ # Web interface
├── docker/ # Container configuration
└── deploy.sh # One-click deployment
Environment Variables
# JWT Configuration
JWT_SECRET_KEY=your-super-secret-key-change-in-production
# Database Configuration
MONGODB_URL=mongodb://admin:password123@localhost:27017/quiz_platform?authSource=admin
Local Development
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export PYTHONPATH="$(pwd)"
export MONGODB_URL="mongodb://localhost:27017"
# Run development server
python -m uvicorn src.main:app --reload --host 0.0.0.0 --port 8000
📚 Assignment: Authentication Flow Implementation
Objective
Extend the authentication service to include user profile management and password reset functionality.
Requirements
Add Profile Endpoints:
PUT /auth/profile
- Update user profileDELETE /auth/account
- Delete user account
Password Reset Flow:
POST /auth/forgot-password
- Request password resetPOST /auth/reset-password
- Reset password with token
Enhanced Security:
Add user role management (admin, user)
Implement account lockout after failed attempts
Add audit logging for security events
Implementation Steps
Extend the user model with new fields
Create new service methods for profile operations
Add new API routes with proper validation
Write comprehensive tests for new functionality
Update the frontend to use new endpoints
Success Criteria
All new endpoints working correctly
Proper error handling and validation
Security measures implemented
Tests achieving 90%+ coverage
Frontend integration complete
🎓 Solution
The complete solution with detailed implementation steps is provided in the assignment-solution/
directory, including:
Extended user models with role management
Password reset token system
Account security features
Comprehensive test suite
Updated frontend interface
🔗 Integration with Day 3
This authentication service integrates seamlessly with the database schemas from Day 3:
Uses the same MongoDB connection
Extends user management for quiz platform
Provides authentication for future quiz endpoints
Maintains consistent data modeling patterns
🚀 Next Steps (Day 5)
Tomorrow we'll build the Quiz Management Service that will:
Use this authentication service for user validation
Create and manage AI-generated quizzes
Integrate with the user management system
Build upon the established database patterns
🛠️ Troubleshooting
Common Issues
Port Already in Use
# Kill processes on port 8000
lsof -ti:8000 | xargs kill -9
MongoDB Connection Failed
# Check MongoDB container status
docker-compose -f docker/docker-compose.yml ps
docker-compose -f docker/docker-compose.yml logs mongodb
Tests Failing
# Check service health
curl http://localhost:8000/health
# Run specific test
python -m pytest tests/unit/test_auth.py::TestPasswordUtils::test_password_hashing -v
Performance Optimization
Database: Add appropriate indexes for query patterns
Caching: Implement Redis for session storage (future enhancement)
Load Balancing: Deploy multiple service instances
Monitoring: Add logging and metrics collection
📈 Production Deployment
For production deployment:
Change Default Secrets: Update JWT secret and database passwords
Enable HTTPS: Use reverse proxy with SSL certificates
Database Security: Use MongoDB authentication and encryption
Monitoring: Add health checks, logging, and alerting
Scaling: Deploy with container orchestration (Kubernetes)
🎉 Congratulations! You've built a production-ready authentication service with modern security practices, comprehensive testing, and container deployment. This foundation will support the entire AI Quiz Platform as we continue building in the coming days.
For questions or issues, check the troubleshooting section or review the comprehensive test output for debugging guidance.
Assignment: Extend Authentication with Advanced Features
🎯 Objective
Enhance the authentication service with role-based access control, account security features, and audit logging.
📋 Requirements
1. Role-Based Access Control
Add user roles (admin, moderator, user)
Create role-based middleware for endpoint protection
Implement role assignment and management endpoints
2. Account Security Features
Account lockout after 5 failed login attempts
Password reset via email tokens
Two-factor authentication (TOTP)
Session management with refresh tokens
3. Audit Logging
Log all authentication events
Track user activities with timestamps
Security event monitoring (failed logins, role changes)
🛠️ Implementation Steps
Extend User Model
class UserInDB(UserResponse):
hashed_password: str
role: str = "user"
failed_login_attempts: int = 0
locked_until: Optional[datetime] = None
two_factor_secret: Optional[str] = None
is_2fa_enabled: bool = False
Add Security Middleware
async def require_role(required_role: str):
# Role-based access control decorator
pass
Implement New Endpoints
POST /auth/reset-password-request
POST /auth/reset-password-confirm
POST /auth/setup-2fa
POST /auth/verify-2fa
GET /auth/audit-log
(admin only)
✅ Success Criteria
All new endpoints tested and working
Role-based access properly enforced
Security features prevent common attacks
Comprehensive test coverage (>95%)
Updated frontend with new features
🎁 Solution Provided
The complete solution implementation is available with: