Auth for edit games

This commit is contained in:
2024-05-15 16:29:23 +04:00
parent 090897a11f
commit f768e3bc4c

View File

@@ -1,5 +1,5 @@
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends, HTTPException, status
import database as db import database as db
from file_handler import * from file_handler import *
@@ -33,11 +33,29 @@ async def get_game(game_id: int, db_session: AsyncSession = Depends(db.get_sessi
@games_router.put("/{game_id}", response_model=db.Game) @games_router.put("/{game_id}", response_model=db.Game)
async def edit_game(game_id: int, async def edit_game(game_id: int,
game: db.GameCreate, game: db.GameCreate,
user: db.User = Depends(get_user),
db_session: AsyncSession = Depends(db.get_session)): db_session: AsyncSession = Depends(db.get_session)):
game_db = await db.get_game(db_session, game_id)
if (game_db is None):
raise HTTPException(status.HTTP_404_NOT_FOUND,
detail=f"Game with id={game_id} not found")
if (user.id != game_db.owner_id):
raise HTTPException(status.HTTP_401_UNAUTHORIZED,
detail=f"Game can only be edited "
"by the owner (creator)")
return await db.edit_game(db_session, game_id, game) return await db.edit_game(db_session, game_id, game)
@games_router.delete("/{game_id}", response_model=db.Game) @games_router.delete("/{game_id}", response_model=db.Game)
async def delete_game(game_id: int, async def delete_game(game_id: int,
user: db.User = Depends(get_user),
db_session: AsyncSession = Depends(db.get_session)): db_session: AsyncSession = Depends(db.get_session)):
game_db = await db.get_game(db_session, game_id)
if (game_db is None):
raise HTTPException(status.HTTP_404_NOT_FOUND,
detail=f"Game with id={game_id} not found")
if (user.id != game_db.owner_id):
raise HTTPException(status.HTTP_401_UNAUTHORIZED,
detail=f"Game can only be deleted "
"by the owner (creator)")
return await db.delete_game(db_session, game_id) return await db.delete_game(db_session, game_id)