+ добавила авторизацию через Bearer
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from ..models.schemas import Session
|
||||
from ..storage.memory import storage
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
basic_scheme = HTTPBasic(auto_error=False)
|
||||
|
||||
DEFAULT_TTL_SECONDS = 3600
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
try:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", DEFAULT_TTL_SECONDS))
|
||||
except ValueError:
|
||||
return DEFAULT_TTL_SECONDS
|
||||
|
||||
|
||||
def _parse_basic(credentials: HTTPBasicCredentials | None) -> tuple[str, str] | None:
|
||||
"""HTTPBasic уже разобрал заголовок; сюда попадают username/password.
|
||||
|
||||
Дополнительно валидируем кодировку: username — ASCII, пароль — UTF-8.
|
||||
"""
|
||||
if credentials is None:
|
||||
return None
|
||||
username = credentials.username
|
||||
password = credentials.password
|
||||
if not username or not password:
|
||||
return None
|
||||
try:
|
||||
username.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions",
|
||||
summary="Вход: Basic username:password; выдаёт сессию",
|
||||
response_model=Session,
|
||||
status_code=201,
|
||||
)
|
||||
def create_session(
|
||||
credentials: HTTPBasicCredentials | None = Depends(basic_scheme),
|
||||
) -> Session:
|
||||
parsed = _parse_basic(credentials)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
username, password = parsed
|
||||
user = storage.verify_credentials(username, password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token, expires_at = storage.create_session(user.id, _ttl_seconds())
|
||||
return Session(token=token, token_type="Bearer", expires_at=expires_at, user=user)
|
||||
|
||||
|
||||
@router.delete(
|
||||
path="/sessions/current",
|
||||
summary="Отозвать текущую сессию",
|
||||
status_code=204,
|
||||
)
|
||||
def revoke_session(request: Request) -> None:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token = auth[7:].strip()
|
||||
if not token or storage.get_session_user(token) is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
storage.revoke_session(token)
|
||||
return None
|
||||
+9
-17
@@ -1,24 +1,15 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
@@ -43,10 +34,10 @@ def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
|
||||
user_id = user.id
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
@@ -63,10 +54,11 @@ def create_chat(
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
user_id = user.id
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
||||
@@ -83,9 +75,9 @@ def list_chats(
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
if chat is None or user.id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
+8
-17
@@ -1,24 +1,15 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
@@ -50,12 +41,12 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
user: User = Depends(current_user),
|
||||
) -> Message:
|
||||
_require_member(chat_id, user_id)
|
||||
_require_member(chat_id, user.id)
|
||||
if not payload.text.strip():
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return storage.add_message(chat_id, user_id, payload.text)
|
||||
return storage.add_message(chat_id, user.id, payload.text)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -65,13 +56,13 @@ def create_message(
|
||||
)
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Реализована курсорная пагинация"""
|
||||
|
||||
_require_member(chat_id, user_id)
|
||||
_require_member(chat_id, user.id)
|
||||
messages = storage.list_messages(chat_id)
|
||||
if cursor:
|
||||
mid, mcreated = _decode_cursor(chat_id, cursor)
|
||||
|
||||
+23
-2
@@ -1,3 +1,24 @@
|
||||
from fastapi.security import APIKeyHeader
|
||||
from uuid import UUID
|
||||
|
||||
dev_user = APIKeyHeader(name="X-User-Id", auto_error=False, scheme_name="devUser")
|
||||
from fastapi import HTTPException, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from ..models.schemas import User
|
||||
from ..storage.memory import storage
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth")
|
||||
|
||||
|
||||
def current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Security(bearer_scheme),
|
||||
) -> User:
|
||||
"""Достаёт Bearer-токен и возвращает владельца сессии.
|
||||
|
||||
Basic на бизнес-endpoint не принимается, X-User-Id игнорируется.
|
||||
"""
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
user = storage.get_session_user(credentials.credentials)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user
|
||||
+4
-19
@@ -1,23 +1,11 @@
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from ..models.schemas import CreateUser, User
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
from fastapi import Security
|
||||
from .security import current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
"""Достаёт X-User-Id из заголовков и валидирует."""
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/users",
|
||||
summary="Создать пользователя",
|
||||
@@ -27,7 +15,7 @@ def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
def register_user(payload: CreateUser) -> User:
|
||||
"""Публичная регистрация."""
|
||||
try:
|
||||
return storage.create_user(payload.username, payload.display_name)
|
||||
return storage.create_user(payload.username, payload.display_name, payload.password)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
@@ -37,9 +25,6 @@ def register_user(payload: CreateUser) -> User:
|
||||
summary="Получить текущего пользователя",
|
||||
response_model=User,
|
||||
)
|
||||
def current_user(user_id: UUID = Depends(_current_user_id)) -> User:
|
||||
"""Текущий пользователь по X-User-Id."""
|
||||
user = storage.get_user(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
def current_user_me(user: User = Depends(current_user)) -> User:
|
||||
"""Текущий пользователь по Bearer-сессии."""
|
||||
return user
|
||||
Reference in New Issue
Block a user