75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, status
|
|
from sqlalchemy.orm import Session
|
|
from app.db.session import get_db
|
|
from app.schemas.secret import SecretCreate, SecretResponse, SecretRetrieved
|
|
from app.services.secret_service import create_secret, retrieve_and_delete_secret, cleanup_expired_secrets
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/secrets", response_model=SecretResponse)
|
|
def create_new_secret(
|
|
secret: SecretCreate,
|
|
background_tasks: BackgroundTasks,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Create a new secret.
|
|
|
|
Args:
|
|
secret: The secret data to store
|
|
background_tasks: FastAPI background tasks
|
|
db: Database session
|
|
|
|
Returns:
|
|
The token to access the secret
|
|
"""
|
|
# Add a background task to clean up expired secrets
|
|
background_tasks.add_task(cleanup_expired_secrets, db)
|
|
|
|
# Create the secret
|
|
secret_obj = create_secret(
|
|
db=db,
|
|
content=secret.content,
|
|
ttl_hours=secret.ttl_hours
|
|
)
|
|
|
|
# Return the token
|
|
return {
|
|
"token": secret_obj.id,
|
|
"expires_at": secret_obj.expires_at,
|
|
"message": "Secret stored successfully"
|
|
}
|
|
|
|
|
|
@router.get("/secrets/{token}", response_model=SecretRetrieved)
|
|
def get_secret(token: str, background_tasks: BackgroundTasks, db: Session = Depends(get_db)):
|
|
"""
|
|
Retrieve a secret by its token and delete it.
|
|
|
|
Args:
|
|
token: The secret token
|
|
background_tasks: FastAPI background tasks
|
|
db: Database session
|
|
|
|
Returns:
|
|
The secret content
|
|
"""
|
|
# Add a background task to clean up expired secrets
|
|
background_tasks.add_task(cleanup_expired_secrets, db)
|
|
|
|
# Retrieve and delete the secret
|
|
content, message = retrieve_and_delete_secret(db, token)
|
|
|
|
# Check if retrieval was successful
|
|
if not content:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=message
|
|
)
|
|
|
|
# Return the secret content
|
|
return {
|
|
"content": content,
|
|
"message": message
|
|
} |