forked from mtusi2026/mtusi2026lab6
97 lines
2.9 KiB
Python
97 lines
2.9 KiB
Python
from datetime import timezone
|
|
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.deps import get_db
|
|
from app.api.users import user_to_response
|
|
from app.services.auth_service import (
|
|
AuthService,
|
|
InvalidCredentialsError,
|
|
InvalidSessionError,
|
|
)
|
|
|
|
|
|
router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
|
|
|
|
basic_security = HTTPBasic(auto_error=False)
|
|
|
|
|
|
|
|
@router.post("/sessions", status_code=status.HTTP_201_CREATED)
|
|
def create_session(
|
|
credentials: HTTPBasicCredentials = Depends(basic_security),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
if credentials is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Basic authentication required",
|
|
headers={
|
|
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
|
|
},
|
|
)
|
|
|
|
try:
|
|
result = AuthService(db).create_session(
|
|
username=credentials.username,
|
|
password=credentials.password,
|
|
)
|
|
|
|
expires_at = result["expires_at"]
|
|
|
|
if expires_at.tzinfo is None:
|
|
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
|
else:
|
|
expires_at = expires_at.astimezone(timezone.utc)
|
|
|
|
return {
|
|
"token": result["token"],
|
|
"token_type": result["token_type"],
|
|
"expires_at": expires_at.isoformat(
|
|
timespec="microseconds"
|
|
).replace("+00:00", "Z"),
|
|
"user": user_to_response(result["user"]),
|
|
}
|
|
|
|
except InvalidCredentialsError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid username or password",
|
|
headers={
|
|
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
|
|
},
|
|
) from None
|
|
|
|
|
|
|
|
@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_current_session(
|
|
authorization: str | None = Header(default=None),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
if not authorization or not authorization.startswith("Bearer "):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Bearer token required",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
|
|
token = authorization[7:].strip()
|
|
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Bearer token required",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
|
|
try:
|
|
AuthService(db).delete_session(token)
|
|
except InvalidSessionError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired session",
|
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
) from None
|