forked from mtusi2026/mtusi2026lab4
feat: port lab3 backend foundation to lab4
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
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
|
||||
@@ -0,0 +1,90 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.db.models import User as UserModel
|
||||
from app.models import Chat as ChatResponse, CreateChat
|
||||
from app.services.chat_service import (
|
||||
ChatService,
|
||||
ChatNotFoundError,
|
||||
InvalidChatDataError,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["Chats"])
|
||||
|
||||
|
||||
def chat_to_response(chat) -> ChatResponse:
|
||||
return ChatResponse(
|
||||
id=str(chat.id),
|
||||
title=chat.title,
|
||||
member_ids=[str(member.user_id) for member in chat.members],
|
||||
created_at=chat.created_at,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_chat(
|
||||
body: CreateChat,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
try:
|
||||
chat = ChatService(db).create_chat(
|
||||
title=body.title,
|
||||
member_ids=body.member_ids,
|
||||
creator_id=user.id,
|
||||
)
|
||||
return chat_to_response(chat)
|
||||
|
||||
except InvalidChatDataError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=str(exc),
|
||||
) from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
if cursor is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Chat cursor pagination is not implemented yet",
|
||||
)
|
||||
|
||||
chats = ChatService(db).list_chats(user.id)
|
||||
chats = chats[:limit]
|
||||
|
||||
return {
|
||||
"items": [chat_to_response(chat) for chat in chats],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{chat_id}", response_model=ChatResponse)
|
||||
def get_chat(
|
||||
chat_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
try:
|
||||
parsed_id = uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
|
||||
|
||||
try:
|
||||
chat = ChatService(db).get_chat(parsed_id, user.id)
|
||||
return chat_to_response(chat)
|
||||
|
||||
except ChatNotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Chat not found",
|
||||
) from None
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import SessionLocal
|
||||
from app.services.auth_service import AuthService, InvalidSessionError
|
||||
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
try:
|
||||
user = AuthService(db).authenticate(credentials.credentials)
|
||||
return user
|
||||
|
||||
except InvalidSessionError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
) from None
|
||||
@@ -0,0 +1,73 @@
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.db.models import User as UserModel
|
||||
from app.models import CreateMessage, Message as MessageResponse
|
||||
from app.services.message_service import (
|
||||
MessageService, MessageNotFoundError, InvalidMessageDataError,
|
||||
IdempotencyConflictError,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["Messages"])
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def message_to_response(message) -> MessageResponse:
|
||||
return MessageResponse(
|
||||
id=str(message.id), chat_id=str(message.chat_id),
|
||||
sender_id=str(message.sender_id), text=message.text,
|
||||
created_at=message.created_at,
|
||||
)
|
||||
|
||||
|
||||
def parse_chat_id(chat_id: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
|
||||
|
||||
|
||||
@router.post("", response_model=MessageResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_message(
|
||||
chat_id: str, body: CreateMessage,
|
||||
idempotency_key: str = Header(..., alias="Idempotency-Key", min_length=1, max_length=128),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise HTTPException(status_code=400, detail="Invalid Idempotency-Key")
|
||||
parsed_id = parse_chat_id(chat_id)
|
||||
try:
|
||||
message = MessageService(db).create_message(
|
||||
chat_id=parsed_id, sender_id=user.id, text=body.text,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
return message_to_response(message)
|
||||
except MessageNotFoundError:
|
||||
raise HTTPException(status_code=404, detail="Chat not found") from None
|
||||
except InvalidMessageDataError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
except IdempotencyConflictError:
|
||||
raise HTTPException(status_code=409, detail="Idempotency-Key was already used with a different request") from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_messages(
|
||||
chat_id: str, limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = None, db: Session = Depends(get_db),
|
||||
user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
parsed_id = parse_chat_id(chat_id)
|
||||
try:
|
||||
messages, next_cursor = MessageService(db).get_history(
|
||||
chat_id=parsed_id, user_id=user.id, limit=limit, cursor=cursor
|
||||
)
|
||||
return {"items": [message_to_response(item) for item in messages], "next_cursor": next_cursor}
|
||||
except MessageNotFoundError:
|
||||
raise HTTPException(status_code=404, detail="Chat not found") from None
|
||||
except InvalidMessageDataError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
@@ -0,0 +1,55 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.db.models import User as UserModel
|
||||
from app.models import CreateUser, User
|
||||
from app.services.user_service import (
|
||||
UserService,
|
||||
UsernameAlreadyExistsError,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["Users"])
|
||||
|
||||
|
||||
def user_to_response(user: UserModel) -> User:
|
||||
return User(
|
||||
id=str(user.id),
|
||||
username=user.username,
|
||||
display_name=user.display_name,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=User, status_code=status.HTTP_201_CREATED)
|
||||
def register_user(
|
||||
body: CreateUser,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
user = UserService(db).register(
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user_to_response(user)
|
||||
|
||||
except UsernameAlreadyExistsError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Username already exists",
|
||||
) from None
|
||||
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(exc),
|
||||
) from None
|
||||
|
||||
|
||||
@router.get("/me", response_model=User)
|
||||
def get_me(
|
||||
current_user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
return user_to_response(current_user)
|
||||
Reference in New Issue
Block a user