Files
securelens-backend/app/routers/apikey.py
2026-04-07 18:13:43 +05:30

77 lines
2.1 KiB
Python

import hashlib
import secrets
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.middleware.auth import get_current_user
from app.models.apikey import ApiKey
from app.models.user import User
from app.schemas.apikey import ApiKeyCreate, ApiKeyCreateResponse, ApiKeyResponse
router = APIRouter(prefix="/api-keys", tags=["apikeys"])
@router.post("", response_model=ApiKeyCreateResponse, status_code=status.HTTP_201_CREATED)
async def create_api_key(
data: ApiKeyCreate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
raw_key = f"sl_{secrets.token_urlsafe(32)}"
key_prefix = raw_key[:10]
hashed_key = hashlib.sha256(raw_key.encode()).hexdigest()
api_key = ApiKey(
user_id=current_user.id,
name=data.name,
key_prefix=key_prefix,
hashed_key=hashed_key,
)
db.add(api_key)
await db.commit()
await db.refresh(api_key)
return ApiKeyCreateResponse(
id=api_key.id,
name=api_key.name,
key_prefix=api_key.key_prefix,
created_at=api_key.created_at,
key=raw_key,
)
@router.get("", response_model=list[ApiKeyResponse])
async def list_api_keys(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(
select(ApiKey)
.where(ApiKey.user_id == current_user.id)
.order_by(ApiKey.created_at.desc())
)
return result.scalars().all()
@router.delete("/{key_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_api_key(
key_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(
select(ApiKey).where(ApiKey.id == key_id, ApiKey.user_id == current_user.id)
)
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="API Key not found"
)
await db.delete(api_key)
await db.commit()