Skip to content

A robust, scalable, and secure user authentication and authorization system built with modern best practices. This project provides a comprehensive solution for handling user identity, protecting sensitive data, and managing access control in a production environment.

Notifications You must be signed in to change notification settings

oar06g/User-Authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” User Authentication System

A comprehensive, production-ready authentication system built with FastAPI, featuring advanced security measures, email verification, password management, and audit logging.

✨ Features

Core Authentication

  • πŸ”‘ 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

Security Features

  • πŸ›‘οΈ 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

πŸš€ Quick Start

Prerequisites

  • Python 3.8 or higher
  • MySQL or SQLite database
  • SMTP email account (Gmail recommended)

Installation

  1. Clone the repository:
cd User-Authentication
  1. Create virtual environment:
python -m venv venv
  1. Activate virtual environment:

Windows:

venv\Scripts\activate

Linux/Mac:

source venv/bin/activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure environment:
copy .env.example .env

Edit .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
  1. Run migrations:
python -m alembic upgrade head
  1. Start the application:
python UserAuthentication.py
  1. Access the application:
http://localhost:8000/api/v1/login

πŸ“ Project Structure

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

πŸ”§ Configuration

Environment Variables

# 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

Gmail App Password Setup

  1. Enable 2-Factor Authentication in your Google Account
  2. Go to Security β†’ App passwords
  3. Generate password for "Mail"
  4. Use generated password in .env file

πŸ›£οΈ API Endpoints

Public Endpoints

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

Protected Endpoints

Method Endpoint Description
GET /api/v1/profile User profile page
POST /api/v1/delete-account Delete user account

πŸ§ͺ Testing

Run the test suite:

pytest test/test_auth.py -v

Run with coverage:

pytest test/test_auth.py --cov=src --cov-report=html

πŸ“Š Database

SQLite (Default)

The system uses SQLite by default. Database file: db_user_auth.db

MySQL (Production)

Update src/settings.py:

DB_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB_USER_AUTHDB}"

Database Models

  • Users - User accounts and credentials
  • EmailVerifications - Email verification tokens
  • PasswordReset - Password reset tokens
  • AuditLog - Security event tracking

πŸ“ Logging

Logs are stored in the logs/ directory:

  • app.log - General application logs
  • error.log - Error logs only
  • security.log - Security audit trail

πŸ”’ Security Best Practices

Implemented

βœ… 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

Production Deployment

  1. Set production environment:
ENVIRONMENT=production
COOKIE_SECURE=True
  1. Use strong secret key:
python -c "import secrets; print(secrets.token_urlsafe(32))"
  1. Enable HTTPS/SSL

  2. Use production database (MySQL/PostgreSQL)

  3. Deploy with Gunicorn:

pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker src:create_app
  1. Set up reverse proxy (Nginx)

  2. Configure firewall

  3. Set up automated backups

πŸ› Troubleshooting

Database Issues

# Reset migrations
python -m alembic downgrade base
python -m alembic upgrade head

Email Not Sending

  • Verify Gmail App Password is correct
  • Check 2FA is enabled
  • Ensure SENDER_EMAIL and SENDER_PASSWORD are set

Port Already in Use

Change port in src/__init__.py:

uvicorn.run(app, host="0.0.0.0", port=8001)

πŸ“ˆ Performance

  • Efficient database connection pooling
  • In-memory rate limiting
  • Rotating log files
  • Optimized queries
  • Middleware ordering for performance

🀝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open Pull Request

πŸ“„ License

This project is open source and available under the MIT License.

πŸ™ Acknowledgments

Built with:

πŸ“ž Support

For issues or questions:

  • Check the logs in logs/ directory
  • Review security logs for authentication issues
  • Verify environment configuration

🎯 Future Enhancements

  • 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

About

A robust, scalable, and secure user authentication and authorization system built with modern best practices. This project provides a comprehensive solution for handling user identity, protecting sensitive data, and managing access control in a production environment.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published