A comprehensive, production-ready authentication system built with FastAPI, featuring advanced security measures, email verification, password management, and audit logging.
- π User Registration & Login - Secure account creation with email verification
- π§ Email Verification - Token-based email confirmation system
- π Password Reset - Secure password recovery via email
- π€ User Profile Management - View and manage account information
- ποΈ Account Deletion - Self-service account removal with confirmation
-
π‘οΈ Password Security
- Argon2 & Bcrypt hashing
- Comprehensive strength validation (uppercase, lowercase, digits, special characters)
- Minimum 8 characters requirement
- Common password detection
-
π Account Protection
- Account lockout after 5 failed login attempts
- 15-minute automatic lockout duration
- JWT token-based authentication
- HTTP-only secure cookies
-
β‘ Rate Limiting
- 60 requests per minute per IP
- 300 requests per hour per IP
- Automatic IP blocking for violations
- 5-minute cooldown for excessive requests
-
π Security Headers
- Content Security Policy (CSP)
- X-Frame-Options: DENY
- X-XSS-Protection
- Strict-Transport-Security (HSTS)
- X-Content-Type-Options: nosniff
-
π Audit Logging
- Complete tracking of security events
- Login/logout tracking
- Password changes
- Account deletions
- IP address and user-agent logging
- Python 3.8 or higher
- MySQL or SQLite database
- SMTP email account (Gmail recommended)
- Clone the repository:
cd User-Authentication- Create virtual environment:
python -m venv venv- Activate virtual environment:
Windows:
venv\Scripts\activateLinux/Mac:
source venv/bin/activate- Install dependencies:
pip install -r requirements.txt- Configure environment:
copy .env.example .envEdit .env with your configuration:
SECRET_KEY_JWT=your-super-secret-key-here
SENDER_EMAIL=your-email@gmail.com
SENDER_PASSWORD=your-gmail-app-password
ENVIRONMENT=development- Run migrations:
python -m alembic upgrade head- Start the application:
python UserAuthentication.py- Access the application:
http://localhost:8000/api/v1/login
User-Authentication/
βββ src/
β βββ __init__.py # Application initialization
β βββ api.py # API routes and endpoints
β βββ auth.py # JWT authentication
β βββ config.py # Database configuration
β βββ dependencies.py # Dependency injection & helpers
β βββ encryption.py # Password hashing
β βββ exceptions.py # Custom exception handlers
β βββ logger.py # Logging configuration
β βββ middleware.py # Security middleware
β βββ models.py # Database models
β βββ schemas.py # Pydantic schemas
β βββ settings.py # Application settings
β βββ utils.py # Utility functions
β βββ validators.py # Input validation
βββ templates/ # HTML templates
βββ migrations/ # Alembic database migrations
βββ test/ # Unit tests
βββ logs/ # Application logs
βββ requirements.txt # Python dependencies
βββ UserAuthentication.py # Application entry point
# JWT Secret (Required - Change in production!)
SECRET_KEY_JWT=your-secret-key
# Email Configuration
SENDER_EMAIL=your-email@gmail.com
SENDER_PASSWORD=your-app-password
# Database (Optional - defaults to SQLite)
MYSQL_USER=root
MYSQL_PASSWORD=password
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_DB_USER_AUTHDB=auth_db
# Application
ENVIRONMENT=development # or production
COOKIE_SECURE=False # Set True in production with HTTPS- Enable 2-Factor Authentication in your Google Account
- Go to Security β App passwords
- Generate password for "Mail"
- Use generated password in
.envfile
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/login |
Login page |
| POST | /api/v1/login |
Authenticate user |
| GET | /api/v1/register |
Registration page |
| POST | /api/v1/register |
Create new account |
| GET | /api/v1/logout |
Logout user |
| GET | /api/v1/password-reset |
Password reset request page |
| POST | /api/v1/password-reset |
Request password reset |
| GET | /api/v1/password-reset/{token} |
Password reset form |
| POST | /api/v1/password-reset/{token} |
Submit new password |
| GET | /api/v1/verify-email/{token} |
Verify email address |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/profile |
User profile page |
| POST | /api/v1/delete-account |
Delete user account |
Run the test suite:
pytest test/test_auth.py -vRun with coverage:
pytest test/test_auth.py --cov=src --cov-report=htmlThe system uses SQLite by default. Database file: db_user_auth.db
Update src/settings.py:
DB_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB_USER_AUTHDB}"- Users - User accounts and credentials
- EmailVerifications - Email verification tokens
- PasswordReset - Password reset tokens
- AuditLog - Security event tracking
Logs are stored in the logs/ directory:
app.log- General application logserror.log- Error logs onlysecurity.log- Security audit trail
β
No user enumeration (same error messages)
β
Password hashing with Argon2/Bcrypt
β
JWT with secure cookies
β
Account lockout protection
β
Rate limiting
β
Security headers
β
Input validation
β
CSRF protection (available)
β
Audit logging
β
Token expiration
- Set production environment:
ENVIRONMENT=production
COOKIE_SECURE=True- Use strong secret key:
python -c "import secrets; print(secrets.token_urlsafe(32))"-
Enable HTTPS/SSL
-
Use production database (MySQL/PostgreSQL)
-
Deploy with Gunicorn:
pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker src:create_app-
Set up reverse proxy (Nginx)
-
Configure firewall
-
Set up automated backups
# Reset migrations
python -m alembic downgrade base
python -m alembic upgrade head- Verify Gmail App Password is correct
- Check 2FA is enabled
- Ensure
SENDER_EMAILandSENDER_PASSWORDare set
Change port in src/__init__.py:
uvicorn.run(app, host="0.0.0.0", port=8001)- Efficient database connection pooling
- In-memory rate limiting
- Rotating log files
- Optimized queries
- Middleware ordering for performance
- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open Pull Request
This project is open source and available under the MIT License.
Built with:
- FastAPI - Modern web framework
- SQLAlchemy - Database ORM
- Alembic - Database migrations
- Passlib - Password hashing
- Python-JOSE - JWT implementation
For issues or questions:
- Check the logs in
logs/directory - Review security logs for authentication issues
- Verify environment configuration
- Multi-Factor Authentication (2FA/MFA)
- OAuth2 Social Login (Google, Facebook, GitHub)
- Enhanced Role-Based Access Control (RBAC)
- Refresh Token implementation
- API rate limiting per user
- Advanced password policies
- Session management
- Device tracking
Built with β€οΈ using FastAPI