first commit
This commit is contained in:
28
backend/app/api/deps.py
Normal file
28
backend/app/api/deps.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from fastapi import Depends, HTTPException, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.db import get_session
|
||||
from app.core.security import read_session_token, SESSION_COOKIE
|
||||
from app.models.user import User
|
||||
|
||||
async def db_session() -> AsyncSession:
|
||||
async for s in get_session():
|
||||
yield s
|
||||
|
||||
async def get_current_user(request: Request, session: AsyncSession = Depends(db_session)) -> User:
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
uid = read_session_token(token)
|
||||
if not uid:
|
||||
raise HTTPException(status_code=401, detail="Invalid session")
|
||||
res = await session.execute(select(User).where(User.id == uid))
|
||||
user = res.scalar_one_or_none()
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(status_code=401, detail="User inactive")
|
||||
return user
|
||||
|
||||
def require_admin(user: User) -> None:
|
||||
if user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="Admin only")
|
||||
Reference in New Issue
Block a user