Skip to main content

No project description provided

Project description

# app.py

from fastapi_auth.auth import setup_auth, build_auth_router, restrict, protect_router
from services.users import authenticate_user, create_user
from other_router import other_router
from fastapi import FastAPI
import uvicorn, os

# Configure auth library
auth_manager = setup_auth(
    auth_endpoint="/auth/login",
    jwt_secret_key=os.getenv("JWT_SECRET_KEY", "A-Secure-Key"),
    access_token_expire_minutes=int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "1440")),
    token_renewal_minutes=int(os.getenv("TOKEN_RENEWAL_MINUTES", "30")),
    database_path=os.getenv("AUTH_DB_PATH", "auth.db") # Minimal SQLite for Auth/Tokens
)

app = FastAPI()

# Build and Register the Auth Router
app.include_router(
    build_auth_router(
        authenticate_user=authenticate_user,
        create_user=create_user
    )
)

@app.get("/restricted_ep")
@restrict(roles_allowed=["admin"], inject_user=True)
def root(current_user: dict):
    return {"message": f"Welcome {current_user['username']} - ID {current_user['user_id']}, to the API !"}

@app.get("/unrestricted_ep")
def root():
    return {"message": "Welcome to the API!"}

# Protect other routes
protect_router(other_router)
app.include_router(other_router)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
# services/users.py

from fastapi import HTTPException, status
from fastapi_auth.auth import get_auth_manager

def authenticate_user(username: str, password: str):
    # 1 - Get user from database by username, fetch password
    user = {} # dummy just for the example
    
    # 2 - Verify password using the manager helper fn
    if not get_auth_manager().verify_password(password, user["password"]):
        return None
    return {"user_id": username, "role": user["role"]}

def create_user(user_dict: dict):
    # 1 - Validate if username already exists
    user_already_exists = user_dict['username'] in [] # dummy just for the example
    if user_already_exists:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username already exists"
        )
    
    # 2 - Create user in database
    # user_dict contains username, password, role, and any extra metadata
    pass

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simple_fastapi_auth-1.0.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simple_fastapi_auth-1.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file simple_fastapi_auth-1.0.tar.gz.

File metadata

  • Download URL: simple_fastapi_auth-1.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for simple_fastapi_auth-1.0.tar.gz
Algorithm Hash digest
SHA256 b9de17501f69ffc303e7b3476cd973c12aecfda408de4d92a8f08e6ed812a01f
MD5 57227af8f09cc0391f9a9a16c7adfe52
BLAKE2b-256 7a38d3afa7bb25e4b29ec9b4ef65d0ea6823e4c32e7860cc070b9e5494e01c5b

See more details on using hashes here.

File details

Details for the file simple_fastapi_auth-1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_fastapi_auth-1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1e354e7f9046b5bfa5e30883fd1425d41507b12a1393bec0e5ba3760db29596a
MD5 fe1a901a9eff952b57a2d5e3456f3745
BLAKE2b-256 76c28f1a0db96573b7e91ec6b3ef66fafdb82d3cf68dd7e6fe8c59cf029907ad

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page