mitlist/be/app/api/auth/guest.py
mohamad f49e15c05c
Some checks failed
Deploy to Production, build images and push to Gitea Registry / build_and_push (pull_request) Failing after 1m24s
feat: Introduce FastAPI and Vue.js guidelines, enhance API structure, and add caching support
This commit adds new guidelines for FastAPI and Vue.js development, emphasizing best practices for component structure, API performance, and data handling. It also introduces caching mechanisms using Redis for improved performance and updates the API structure to streamline authentication and user management. Additionally, new endpoints for categories and time entries are implemented, enhancing the overall functionality of the application.
2025-06-09 21:02:51 +02:00

55 lines
2.0 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
import uuid
from app import models
from app.schemas.user import UserCreate, UserClaim, UserPublic
from app.schemas.token import Token
from app.database import get_session
from app.auth import current_active_user
from app.core.security import create_access_token, get_password_hash
from app.crud import user as crud_user
router = APIRouter()
@router.post("/guest", response_model=Token)
async def create_guest_user(db: AsyncSession = Depends(get_session)):
"""
Creates a new guest user.
"""
guest_email = f"guest_{uuid.uuid4()}@guest.mitlist.app"
guest_password = uuid.uuid4().hex
user_in = UserCreate(email=guest_email, password=guest_password)
user = await crud_user.create_user(db, user_in=user_in, is_guest=True)
access_token = create_access_token(data={"sub": user.email})
return {"access_token": access_token, "token_type": "bearer"}
@router.post("/guest/claim", response_model=UserPublic)
async def claim_guest_account(
claim_in: UserClaim,
db: AsyncSession = Depends(get_session),
current_user: models.User = Depends(current_active_user),
):
"""
Claims a guest account, converting it to a full user.
"""
if not current_user.is_guest:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not a guest account.")
existing_user = await crud_user.get_user_by_email(db, email=claim_in.email)
if existing_user:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered.")
hashed_password = get_password_hash(claim_in.password)
current_user.email = claim_in.email
current_user.hashed_password = hashed_password
current_user.is_guest = False
current_user.is_verified = False # Require email verification
db.add(current_user)
await db.commit()
await db.refresh(current_user)
return current_user