+ добавила авторизацию через 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
|
||||
+10
-9
@@ -11,7 +11,7 @@ from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import uvicorn
|
||||
from .api import chats, health, messages, users
|
||||
from .api import auth, chats, health, messages, users
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
@@ -31,8 +31,8 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab1",
|
||||
version="1.2.2",
|
||||
title="MTUCI Messenger — lab2",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
@@ -42,12 +42,6 @@ def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
||||
schema.setdefault("components", {}).setdefault("securitySchemes", {})["devUser"] = {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-User-Id",
|
||||
"description": "Только учебная lab1: существующий UUID. Не является аутентификацией.",
|
||||
}
|
||||
app.openapi_schema = schema
|
||||
return schema
|
||||
|
||||
@@ -93,9 +87,15 @@ _ERROR_CODES = {
|
||||
|
||||
def _error_response(status_code: int, message: str, request_id: str) -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
# Basic — только для /auth/sessions; для остальных endpoint — Bearer.
|
||||
# Клиент получает корректный challenge.
|
||||
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@@ -121,6 +121,7 @@ async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
@@ -14,6 +14,7 @@ class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
@@ -64,6 +65,14 @@ class MessagePage(BaseModel):
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -11,18 +14,60 @@ def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N,
|
||||
r=_SCRYPT_R,
|
||||
p=_SCRYPT_P,
|
||||
dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P,
|
||||
salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов и сообщений. Все данные исчезают при перезапуске процесса"""
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов, сообщений и сессий. Все данные исчезают при перезапуске процесса"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self._users: Dict[UUID, User] = {}
|
||||
self._usernames: Dict[str, UUID] = {}
|
||||
self._passwords: Dict[UUID, str] = {}
|
||||
self._chats: Dict[UUID, Chat] = {}
|
||||
self._messages: Dict[UUID, List[Message]] = {}
|
||||
# token -> (user_id, expires_at)
|
||||
self._sessions: Dict[str, tuple] = {}
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str) -> User:
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._usernames:
|
||||
raise ValueError("username_taken")
|
||||
@@ -34,6 +79,7 @@ class MemoryStorage:
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._usernames[username] = user.id
|
||||
self._passwords[user.id] = _hash_password(password)
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
@@ -45,6 +91,39 @@ class MemoryStorage:
|
||||
uid = self._usernames.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
if uid is None:
|
||||
return None
|
||||
stored = self._passwords.get(uid)
|
||||
if not stored or not _verify_password(password, stored):
|
||||
return None
|
||||
return self._users.get(uid)
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
with self._lock:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
self._sessions[token] = (user_id, expires_at)
|
||||
return token, expires_at
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
entry = self._sessions.get(token)
|
||||
if entry is None:
|
||||
return None
|
||||
user_id, expires_at = entry
|
||||
if expires_at <= now_utc():
|
||||
self._sessions.pop(token, None)
|
||||
return None
|
||||
return self._users.get(user_id)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with self._lock:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock:
|
||||
|
||||
Reference in New Issue
Block a user