34 lines
933 B
Python
34 lines
933 B
Python
from typing import Optional
|
|
|
|
from fastapi import Cookie, Depends, Header, HTTPException
|
|
from sqlmodel import Session
|
|
|
|
from .auth import decode_token
|
|
from .database import get_session
|
|
from .models import User
|
|
|
|
|
|
def get_current_user(
|
|
session: Session = Depends(get_session),
|
|
auth_token: Optional[str] = Cookie(default=None),
|
|
authorization: Optional[str] = Header(default=None),
|
|
) -> User:
|
|
token: Optional[str] = None
|
|
if auth_token:
|
|
token = auth_token
|
|
elif authorization and authorization.startswith("Bearer "):
|
|
token = authorization[7:]
|
|
|
|
if not token:
|
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
|
|
payload = decode_token(token)
|
|
if not payload:
|
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
|
|
user = session.get(User, payload["sub"])
|
|
if not user:
|
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
|
|
return user
|