Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /Athroniaeth_keyshield /examples /example_fastapi_scopes.py
| import os | |
| from pathlib import Path | |
| from typing import AsyncIterator | |
| from fastapi import FastAPI, Depends, APIRouter | |
| from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession | |
| from keyshield import ApiKeyService | |
| from keyshield.domain.entities import ApiKey | |
| from keyshield.hasher.argon2 import Argon2ApiKeyHasher | |
| from keyshield.repositories.sql import SqlAlchemyApiKeyRepository | |
| from keyshield.api import create_api_keys_router, create_depends_api_key | |
| # Set env var to override default pepper | |
| # Using a strong, unique pepper is crucial for security | |
| # Default pepper is insecure and should not be used in production | |
| pepper = os.getenv("SECRET_PEPPER") | |
| hasher = Argon2ApiKeyHasher(pepper=pepper) | |
| path = Path(__file__).parent / "db.sqlite3" | |
| database_url = os.environ.get("DATABASE_URL", f"sqlite+aiosqlite:///{path}") | |
| async_engine = create_async_engine(database_url, future=True) | |
| async_session_maker = async_sessionmaker( | |
| async_engine, | |
| class_=AsyncSession, | |
| expire_on_commit=False, | |
| ) | |
| app = FastAPI(title="API with API Key Management") | |
| async def get_async_session() -> AsyncIterator[AsyncSession]: | |
| """Dependency to provide an active SQLAlchemy async session.""" | |
| async with async_session_maker() as session: | |
| async with session.begin(): | |
| yield session | |
| async def get_svc_api_keys(async_session: AsyncSession = Depends(get_async_session)) -> ApiKeyService: | |
| """Dependency to inject the API key service with an active SQLAlchemy async session.""" | |
| repo = SqlAlchemyApiKeyRepository(async_session) | |
| # Necessary if you don't use your own DeclarativeBase | |
| await repo.ensure_table(async_engine=async_engine) | |
| return ApiKeyService(repo=repo, hasher=hasher) | |
| # Create security dependency that requires "write" scope | |
| security = create_depends_api_key(get_svc_api_keys, required_scopes=["write"]) | |
| router_protected = APIRouter(prefix="/protected", tags=["Protected"]) | |
| router = APIRouter(prefix="/api-keys", tags=["API Keys"]) | |
| router_api_keys = create_api_keys_router( | |
| get_svc_api_keys, | |
| router=router, | |
| ) | |
| async def read_protected_data(api_key: ApiKey = Depends(security)): | |
| return { | |
| "message": "This is protected data", | |
| "apiKey": { | |
| "id": api_key.id_, | |
| "name": api_key.name, | |
| "description": api_key.description, | |
| "isActive": api_key.is_active, | |
| "createdAt": api_key.created_at, | |
| "expiresAt": api_key.expires_at, | |
| "lastUsedAt": api_key.last_used_at, | |
| }, | |
| } | |
| app.include_router(router_api_keys) | |
| app.include_router(router_protected) | |
| async def main(): | |
| async with async_session_maker() as async_session: | |
| repo = SqlAlchemyApiKeyRepository(async_session) | |
| # Necessary if you don't use your own DeclarativeBase | |
| await repo.ensure_table(async_engine=async_engine) | |
| svc = ApiKeyService(repo=repo, hasher=hasher) | |
| # Create an API key without the required "write" scope | |
| _, bad_api_key = await svc.create(name="no-scope-key", scopes=["read"]) | |
| _, good_api_key = await svc.create(name="with-scope-key", scopes=["write"]) | |
| print(f"Bad API Key (no required scopes): '{bad_api_key}'") | |
| print(f"Good API Key (with required scopes): '{good_api_key}'") | |
| await async_session.commit() | |
| if __name__ == "__main__": | |
| import asyncio | |
| # Create an invalid and a valid API key for testing | |
| asyncio.run(main()) | |
| import uvicorn | |
| # Run the FastAPI app and test the 2 api keys against the protected endpoint | |
| uvicorn.run(app, host="localhost", port=8000) | |
Xet Storage Details
- Size:
- 3.64 kB
- Xet hash:
- cf48ca7fa156d9c1efc8b552ddbd7c93e0fa4e5d17513efa4ad85457847dc91e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.