feat: add user and authentication API endpoints
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
from typing import Generator
|
||||
|
||||
from fastapi import Depends, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import SessionLocal
|
||||
from app.db.models import User
|
||||
from app.services.auth_service import AuthService, InvalidSessionError
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
authorization: str | None = Header(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = authorization[7:].strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
try:
|
||||
return AuthService(db).authenticate(token)
|
||||
except InvalidSessionError:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid or expired session",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
) from None
|
||||
Reference in New Issue
Block a user