{"id":30309681,"url":"https://github.com/hu55ain3laa/fastauth","last_synced_at":"2025-08-17T14:02:25.658Z","repository":{"id":290957318,"uuid":"975639825","full_name":"hu55ain3laa/fastauth","owner":"hu55ain3laa","description":"A comprehensive authentication and authorization library for FastAPI applications with JWT-based authentication, role-based authorization, and SQLModel integration.","archived":false,"fork":false,"pushed_at":"2025-05-08T21:37:54.000Z","size":307,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-17T05:52:18.795Z","etag":null,"topics":["authentication","backend","fastapi"],"latest_commit_sha":null,"homepage":"https://hu55ain3laa.github.io/fastauth/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hu55ain3laa.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-30T16:40:36.000Z","updated_at":"2025-07-30T15:01:20.000Z","dependencies_parsed_at":"2025-05-01T15:46:08.967Z","dependency_job_id":null,"html_url":"https://github.com/hu55ain3laa/fastauth","commit_stats":null,"previous_names":["hu55ain3laa/fastauth"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/hu55ain3laa/fastauth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hu55ain3laa%2Ffastauth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hu55ain3laa%2Ffastauth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hu55ain3laa%2Ffastauth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hu55ain3laa%2Ffastauth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hu55ain3laa","download_url":"https://codeload.github.com/hu55ain3laa/fastauth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hu55ain3laa%2Ffastauth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270856775,"owners_count":24657700,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-17T02:00:09.016Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","backend","fastapi"],"created_at":"2025-08-17T14:01:02.522Z","updated_at":"2025-08-17T14:02:25.600Z","avatar_url":"https://github.com/hu55ain3laa.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/hu55ain3laa/fastauth/main/FastAuth.svg\" alt=\"FastAuth Logo\" width=\"350\"\u003e\n\n  \u003cp\u003eA comprehensive authentication and authorization library for FastAPI applications\u003cbr\u003ewith JWT-based authentication, role-based authorization, and SQLModel integration.\u003c/p\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://badge.fury.io/py/fastauth-iq\"\u003e\u003cimg src=\"https://badge.fury.io/py/fastauth-iq.svg?v=0.3.4\" alt=\"PyPI version\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://opensource.org/licenses/MIT\"\u003e\u003cimg src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" alt=\"License: MIT\"\u003e\u003c/a\u003e\n\n  \u003ch3\u003e📖 \u003ca href=\"https://hu55ain3laa.github.io/fastauth/\"\u003eFull Documentation Available Here\u003c/a\u003e\u003c/h3\u003e\n\u003c/div\u003e\n\n## Documentation\n\nThis README provides a quick overview of FastAuth. For a more complete, interactive documentation with live examples and responsive design, visit our **[GitHub Pages Documentation](https://hu55ain3laa.github.io/fastauth/)**.\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Authentication](#authentication)\n  - [Login and Token Management](#login-and-token-management)\n  - [Protected Routes](#protected-routes)\n  - [Cookie-Based Authentication](#cookie-based-authentication)\n- [Database Initialization](#database-initialization)\n  - [CLI Initialization](#cli-initialization-new-in-v030)\n  - [Programmatic Initialization](#programmatic-initialization)\n- [Role-Based Authorization](#role-based-authorization)\n  - [Standard Roles](#standard-roles)\n  - [Role Requirements](#role-requirements)\n  - [Role Management API](#role-management-api)\n- [API Reference](#api-reference)\n  - [Authentication Endpoints](#authentication-endpoints)\n  - [Role Management Endpoints](#role-management-endpoints)\n- [Error Handling](#error-handling)\n  - [Custom Exceptions](#custom-exceptions)\n  - [Standardized Error Responses](#standardized-error-responses)\n- [Advanced Usage](#advanced-usage)\n  - [Custom User Models](#custom-user-models)\n  - [Custom Authentication Logic](#custom-authentication-logic)\n- [Security Best Practices](#security-best-practices)\n- [Project Structure](#project-structure)\n- [License](#license)\n\n## Features\n\n- **OAuth2 and JWT authentication** built-in\n- **Role-based authorization** system\n- **Cookie-based authentication** option\n- **Token refresh mechanism** for extended sessions\n- **SQLModel integration** for easy database operations\n- **CLI utilities** for database initialization and management (new in v0.3.0)\n- **Ready-to-use authentication routes** with minimal setup\n- **Comprehensive error handling** with standardized error responses (new in v0.3.4)\n- **Password hashing** with bcrypt\n- **Modular architecture** for better code organization and extensibility\n\n## Installation\n\n```bash\npip install fastauth_iq\n```\n\nOr install from source:\n\n```bash\ngit clone https://github.com/hu55ain3laa/fastauth.git\ncd fastauth\npip install -e .\n```\n\n## Quick Start\n\n### 1. Create a User Model\n\nFastAuth works with SQLModel's user model. You can use the built-in User model or create your own:\n\n```python\nfrom sqlmodel import SQLModel, Field\n\nclass User(SQLModel, table=True):\n    id: int = Field(primary_key=True)\n    username: str = Field(unique=True)\n    email: str = Field(unique=True)\n    hashed_password: str\n    disabled: bool = Field(default=False)\n```\n\n### 2. Initialize FastAuth in Your Application\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom sqlmodel import create_engine, Session, SQLModel\n\nfrom fastauth import FastAuth, User\n\n# Create FastAPI app\napp = FastAPI()\n\n# Setup database\nengine = create_engine(\"sqlite:///./app.db\")\n\n# Session dependency\ndef get_session():\n    with Session(engine) as session:\n        yield session\n\n# Initialize FastAuth with your configuration\nauth = FastAuth(\n    secret_key=\"your-secure-secret-key\",  # Use strong secret in production\n    algorithm=\"HS256\",\n    user_model=User,\n    engine=engine,\n    use_cookie=True,  # Enable cookie-based auth (optional)\n    token_url=\"/token\",\n    access_token_expires_in=30,  # minutes\n    refresh_token_expires_in=7   # days\n)\n\n# Initialize database (choose ONE of these approaches):\n# Option 1: Using the CLI tool before starting the application (new in v0.3.0)\n#   fastauth app.py                   # Auto-detect settings from your app file\n#   # Or use explicit parameters\n#   fastauth --db-url=\"sqlite:///./app.db\" --secret-key=\"your-secret-key\"\n#\n# Option 2: Initializing during application startup\nINIT_DB_ON_STARTUP = True  # Set to False to disable\n\n@app.on_event(\"startup\")\ndef on_startup():\n    if INIT_DB_ON_STARTUP:\n        auth.initialize_db(\n            create_tables=True,         # Create database tables\n            init_roles=True,            # Initialize standard roles\n            create_admin=True,          # Create superadmin if needed\n            admin_username=\"superadmin\", # Default username\n            admin_password=\"admin123\"    # Default password\n        )\n\n# Add all authentication routes automatically\nauth_router = auth.get_auth_router(get_session)\napp.include_router(auth_router, tags=[\"authentication\"])\n\n# Add role management routes (new in v0.2.2)\nrole_router = auth.get_role_router()\napp.include_router(role_router, tags=[\"roles\"])\n\n# Set up standardized error handling (new in v0.3.4)\nauth.setup_exception_handlers(app)\n```\n\n### 3. Protect Your Routes\n\n```python\n# Require authentication only\n@app.get(\"/protected\")\ndef protected_route(current_user = Depends(auth.get_current_active_user_dependency())):\n    return {\"message\": f\"Hello, {current_user.username}!\"}\n\n# Require specific roles (any of the listed roles)\n@app.get(\"/admin-or-moderator\")\ndef admin_or_mod_route(current_user = Depends(auth.require_roles([\"admin\", \"moderator\"]))):\n    return {\"message\": f\"Hello privileged user, {current_user.username}!\"}\n\n# Require all listed roles\n@app.get(\"/admin-and-verified\")\ndef admin_and_verified_route(current_user = Depends(auth.require_all_roles([\"admin\", \"verified\"]))):\n    return {\"message\": f\"Hello admin with verification, {current_user.username}!\"}\n\n# Shortcut for admin-only routes\n@app.get(\"/admin-only\")\ndef admin_only_route(current_user = Depends(auth.is_admin())):\n    return {\"message\": f\"Hello admin, {current_user.username}!\"}\n```\n\n## Authentication\n\n### Login and Token Management\n\nFastAuth implements JWT-based authentication with both access tokens and refresh tokens:\n\n- **Access tokens** are short-lived (default: 30 minutes) and used for regular API access\n- **Refresh tokens** are long-lived (default: 7 days) and used to obtain new access tokens\n\nUser authentication flow:\n\n1. User submits credentials to `/token` endpoint\n2. Server validates credentials and returns access + refresh tokens\n3. Client uses access token for API requests (via header or cookie)\n4. When access token expires, client uses refresh token to get a new one from `/token/refresh`\n\n### Protected Routes\n\nTo protect a route, use FastAuth's dependencies:\n\n```python\n# Basic authentication - any valid user\n@app.get(\"/protected\")\ndef protected_route(user = Depends(auth.get_current_active_user_dependency())):\n    return {\"message\": \"Protected content\", \"user\": user.username}\n```\n\n### Cookie-Based Authentication\n\nFastAuth supports both header-based and cookie-based authentication:\n\n```python\n# Enable cookie-based auth when creating FastAuth instance\nauth = FastAuth(\n    # ... other parameters ...\n    use_cookie=True\n)\n```\n\nWith cookie-based auth enabled:\n- The `/token` endpoint will set HTTP-only cookies with the tokens\n- Protected routes will check for tokens in cookies if not found in headers\n- The cookie approach is more secure for browser-based applications\n\n## Database Initialization\n\n### CLI Initialization (new in v0.3.0)\n\nFastAuth provides a convenient CLI tool for database initialization, which is ideal for production environments.\n\n```bash\n# Just provide your app file - FastAuth will extract settings automatically\nfastauth example.py\n\n# Or use the traditional approach\nfastauth --db-url=\"sqlite:///./app.db\" --secret-key=\"your-secret-key\"\n\n# Customize the superadmin credentials\nfastauth example.py --username=\"admin\" --password=\"secure_password\"\n\n# Run specific initialization steps\nfastauth example.py --init-db --init-roles --create-superadmin\n```\n\nThe CLI tool will prompt for credentials if not provided, with defaults:\n- Username: `superadmin`\n- Password: `admin123`\n\n#### Setting up your Application File for Auto-Detection\n\nWhen using the `fastauth example.py` syntax, FastAuth auto-detects database URL and secret key settings from multiple sources (new in v0.3.3):\n\n**1. Environment Variables:**\n```bash\n# Set these environment variables before running FastAuth CLI\nexport DATABASE_URL=\"sqlite:///./app.db\"\nexport SECRET_KEY=\"your-secret-key-here\"\n```\n\n**2. .env Files:**\nCreate a `.env` file in your project directory:\n```\nDATABASE_URL=sqlite:///./app.db\nSECRET_KEY=your-secret-key-here\n```\n\n**3. Python Module Variables:**\n```python\n# Database URL - any of these formats will be detected\nDATABASE_URL = \"sqlite:///./app.db\"\ndatabase_url = \"sqlite:///./app.db\"\ndb_url = \"sqlite:///./app.db\"\nengine = create_engine(\"sqlite:///./app.db\")\n\n# Secret Key - any of these formats will be detected\nSECRET_KEY = \"your-secret-key-here\"\nsecret_key = \"your-secret-key-here\"\n```\n\n**4. Imported Modules and Engine Objects:**\n```python\n# FastAuth will detect imported engine objects\nfrom database import engine  # Where database.py contains an engine definition\n\n# And imported configuration variables\nfrom config import DATABASE_URL, SECRET_KEY\n```\n\nFastAuth will search for these variables in:\n- The specified app file\n- Common configuration files (config.py, settings.py, db.py, etc.)\n- Imported modules\n\nIf FastAuth cannot detect your settings, you can still provide them with the `--db-url` and `--secret-key` flags.\n\n### Programmatic Initialization\n\nYou can also initialize the database programmatically during application startup, which is simpler for development environments:\n\n```python\n# Initialize during application startup\n@app.on_event(\"startup\")\ndef on_startup():\n    auth.initialize_db(\n        create_tables=True,         # Create database tables\n        init_roles=True,            # Initialize standard roles\n        create_admin=True,          # Create superadmin if needed\n        admin_username=\"superadmin\", # Default username\n        admin_password=\"admin123\"    # Default password\n    )\n```\n\nYou can also create a superadmin user programmatically at any time:\n\n```python\n# Create a superadmin user with default credentials\nauth.create_superadmin()\n\n# Or with custom credentials\nauth.create_superadmin(username=\"admin\", password=\"secure_password\")\n```\n\n## Role-Based Authorization\n\nFastAuth includes a robust role-based authorization system:\n\n### Standard Roles\n\nThe initialization creates these standard roles:\n- `superadmin`: Super administrator with all privileges\n- `admin`: Administrator with management privileges\n- `moderator`: User with content moderation privileges \n- `premium`: Premium tier user\n- `verified`: Verified user\n- `user`: Standard user with basic privileges\n\n### Role Requirements\n\nFastAuth provides flexible role-based access control:\n\n```python\n# Require any of these roles (OR condition)\n@app.get(\"/admin-or-moderator\")\ndef admin_route(user = Depends(auth.require_roles([\"admin\", \"moderator\"]))):\n    return {\"message\": \"Admin or moderator area\"}\n\n# Require all of these roles (AND condition)\n@app.get(\"/premium-and-verified\")\ndef premium_verified_route(user = Depends(auth.require_all_roles([\"premium\", \"verified\"]))):\n    return {\"message\": \"Premium and verified area\"}\n\n# Shortcut for admin-only routes\n@app.get(\"/admin-only\")\ndef admin_only(user = Depends(auth.is_admin())):\n    return {\"message\": \"Admin only area\"}\n```\n\n### Role Management API\n\nFastAuth provides a complete API for role management:\n\n```python\n# Get the role router and include it in your app\nrole_router = auth.get_role_router()\napp.include_router(role_router, tags=[\"roles\"])\n```\n\nThis adds these role management endpoints:\n- **POST /roles/** - Create a new role (admin only)\n- **GET /roles/** - Get all roles \n- **GET /roles/{role_id}** - Get a role by ID\n- **PUT /roles/{role_id}** - Update a role (admin only)\n- **DELETE /roles/{role_id}** - Delete a role (admin only)\n- **POST /roles/assign/{user_id}/{role_id}** - Assign a role to a user (admin only)\n- **DELETE /roles/assign/{user_id}/{role_id}** - Remove a role from a user (admin only)\n- **GET /roles/user/{user_id}** - Get all roles for a user\n\n## API Reference\n\n### Authentication Endpoints\n\nFastAuth provides the following authentication endpoints:\n\n- `POST /token` - Login and get access + refresh tokens\n- `POST /token/refresh` - Use refresh token to get a new access token\n- `POST /users` - Register a new user\n- `GET /users/me` - Get current user information\n\n### Role Management Endpoints\n\nFastAuth provides these role management endpoints (all under `/roles` by default):\n\n- `POST /roles/` - Create a new role (admin only)\n- `GET /roles/` - Get all roles (authenticated users)\n- `GET /roles/{role_id}` - Get a specific role (authenticated users)\n- `PUT /roles/{role_id}` - Update a role (admin only)\n- `DELETE /roles/{role_id}` - Delete a role (admin only)\n- `POST /roles/assign/{user_id}/{role_id}` - Assign role to user (admin only)\n- `DELETE /roles/assign/{user_id}/{role_id}` - Remove role from user (admin only)\n\n## Error Handling\n\nFastAuth provides a comprehensive error handling system that delivers consistent, informative error responses across all endpoints (new in v0.3.4).\n\n### Custom Exceptions\n\nThe library includes specialized exception classes for different error scenarios:\n\n```python\nfrom fastauth import (\n    CredentialsException,    # Authentication failures\n    TokenException,          # Token verification issues\n    RefreshTokenException,   # Refresh token problems\n    InactiveUserException,   # User account is disabled\n    UserNotFoundException,   # User doesn't exist\n    UserExistsException,     # Username already taken\n    RoleNotFoundException,    # Role doesn't exist\n    RoleExistsException,     # Role already exists\n    PermissionDeniedException # Insufficient permissions\n)\n```\n\n### Standardized Error Responses\n\nAll FastAuth exceptions return a consistent JSON structure:\n\n```json\n{\n  \"error\": {\n    \"code\": \"FASTAUTH_ERROR_CODE\",\n    \"message\": \"Human-readable error description\",\n    \"status_code\": 401  // HTTP status code\n  }\n}\n```\n\nEnabling error handling is simple:\n\n```python\napp = FastAPI()\nauth = FastAuth(...)\n\n# Register exception handlers with your FastAPI app\nauth.setup_exception_handlers(app)\n```\n\nThis makes debugging easier and allows clients to handle errors in a consistent way. Each exception type has its own specific error code, making it straightforward to identify and respond to different error scenarios.\n\n## Advanced Usage\n\n### Custom User Models\n\nYou can use a custom user model with FastAuth:\n\n```python\nclass CustomUser(SQLModel, table=True):\n    id: int = Field(primary_key=True)\n    username: str = Field(unique=True)\n    email: str = Field(unique=True)\n    hashed_password: str\n    disabled: bool = Field(default=False)\n    # Additional fields...\n    first_name: str = Field(default=\"\")\n    last_name: str = Field(default=\"\")\n\n# Pass your custom model to FastAuth\nauth = FastAuth(\n    # ... other parameters ...\n    user_model=CustomUser\n)\n```\n\n### Custom Authentication Logic\n\nYou can customize the authentication logic:\n\n```python\n# Custom authentication routes\n@app.post(\"/custom-login\")\nasync def custom_login(\n    username: str, \n    password: str, \n    session: Session = Depends(get_session)\n):\n    user = auth.authenticate_user(username, password)\n    if not user:\n        raise HTTPException(status_code=401, detail=\"Invalid credentials\")\n    \n    access_token = auth.create_access_token(data={\"sub\": user.username})\n    return {\"access_token\": access_token, \"token_type\": \"bearer\"}\n```\n\n## Security Best Practices\n\nWhen using FastAuth in your applications, consider these security recommendations:\n\n1. **Deploy your FastAPI app with HTTPS** in production environments\n2. **Use a strong secret key** for FastAuth and store it securely (e.g., environment variables)\n3. **Configure appropriate token expiration times** based on your security requirements\n4. **Keep secure cookie settings** when using cookie-based authentication (FastAuth sets `httpOnly=True` which prevents JavaScript from accessing cookies, protecting against XSS attacks)\n5. **Consider implementing rate limiting** on your authentication endpoints to prevent brute force attacks\n\n## Project Structure\n\nFastAuth follows a modular architecture for better maintainability:\n\n```\nfastauth/\n├── core/           # Core functionality\n│   ├── auth.py     # The main FastAuth class\n│   ├── password.py # Password management\n│   └── tokens.py   # Token generation and validation\n├── models/         # Data models\n│   ├── user.py     # User models and schemas\n│   ├── role.py     # Role models for authorization\n│   └── tokens.py   # Token data models\n├── routers/        # Route handlers for auth and roles\n├── dependencies/   # FastAPI dependencies for auth and roles\n└── utils/          # Utility functions and helpers\n```\n\nThis modular structure makes it easier to:\n- Understand the codebase\n- Extend or customize functionality\n- Test individual components\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhu55ain3laa%2Ffastauth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhu55ain3laa%2Ffastauth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhu55ain3laa%2Ffastauth/lists"}