добавлена аутентификация и сессии в redis
This commit is contained in:
+1
-1
@@ -7,5 +7,5 @@ SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
SESSION_STORE=redis
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
+34
-1
@@ -16,23 +16,56 @@ services:
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
|
||||
redis:
|
||||
image: redis:8.2.2
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- everysec
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: [ "CMD", "redis-cli", "ping" ]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url}
|
||||
SESSION_STORE: ${SESSION_STORE:-redis}
|
||||
CACHE_URL_FILE: ${CACHE_URL_FILE:-/run/secrets/cache_url}
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8080:8080"
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
@@ -15,3 +15,6 @@ SQLAlchemy==2.1.4
|
||||
asyncpg==0.32.0
|
||||
alembic==1.20.0
|
||||
greenlet==3.5.6
|
||||
|
||||
argon2-cffi==25.1.0
|
||||
redis==7.0.1
|
||||
|
||||
+9
-2
@@ -1,5 +1,12 @@
|
||||
class APIError(Exception):
|
||||
def __init__(self, status_code: int, code: str, message: str):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
):
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.message = message
|
||||
self.headers = headers
|
||||
+142
-110
@@ -1,18 +1,80 @@
|
||||
from uuid import UUID, uuid4
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Request
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security import (
|
||||
HTTPAuthorizationCredentials,
|
||||
HTTPBasic,
|
||||
HTTPBasicCredentials,
|
||||
HTTPBearer,
|
||||
)
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from src.database import get_db_session
|
||||
from src.errors import APIError
|
||||
from src.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Message, MessagePage, User
|
||||
from src.store import Store, UsernameAlreadyExistsError
|
||||
from src.models import CreateUser, SessionResponse, User
|
||||
from src.repositories import (
|
||||
create_user as create_user_in_db,
|
||||
get_user_by_id,
|
||||
get_user_credentials_by_username,
|
||||
)
|
||||
from src.security import verify_password
|
||||
from src.sessions import (
|
||||
create_session,
|
||||
delete_session,
|
||||
get_session_user_id,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
store = Store()
|
||||
basic_security = HTTPBasic(auto_error=False)
|
||||
bearer_security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> User:
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
user_id = await get_session_user_id(credentials.credentials)
|
||||
|
||||
if user_id is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
user = await get_user_by_id(session, user_id)
|
||||
|
||||
if user is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
@@ -80,6 +142,7 @@ async def api_error_handler(request: Request, exc: APIError):
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
@@ -129,37 +192,6 @@ async def unexpected_exception_handler(
|
||||
)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> User:
|
||||
if x_user_id is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
)
|
||||
|
||||
try:
|
||||
user_id = UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
)
|
||||
|
||||
user = await store.get_user(user_id)
|
||||
|
||||
if user is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
@@ -171,15 +203,20 @@ async def health_ready():
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def create_user(data: CreateUser):
|
||||
async def create_user(
|
||||
data: CreateUser,
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
try:
|
||||
return await store.create_user(data)
|
||||
except UsernameAlreadyExistsError:
|
||||
async with session.begin():
|
||||
return await create_user_in_db(session, data)
|
||||
|
||||
except IntegrityError as exc:
|
||||
raise APIError(
|
||||
status_code=409,
|
||||
code="conflict",
|
||||
message="Username already exists",
|
||||
)
|
||||
) from exc
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
@@ -189,83 +226,78 @@ async def get_me(
|
||||
return current_user
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(
|
||||
data: CreateChat,
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
return await store.create_chat(
|
||||
data=data,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
chat_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
return await store.get_chat(
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def get_chats(
|
||||
limit: int = 50,
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Limit must be between 1 and 100",
|
||||
)
|
||||
|
||||
return await store.get_chats(
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=Message,
|
||||
"/api/v1/auth/sessions",
|
||||
response_model=SessionResponse,
|
||||
status_code=201,
|
||||
)
|
||||
async def create_message(
|
||||
chat_id: UUID,
|
||||
data: CreateMessage,
|
||||
current_user: User = Depends(get_current_user),
|
||||
async def create_auth_session(
|
||||
credentials: HTTPBasicCredentials | None = Depends(basic_security),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
return await store.create_message(
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
data=data,
|
||||
if credentials is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
user_credentials = await get_user_credentials_by_username(
|
||||
session,
|
||||
credentials.username,
|
||||
)
|
||||
|
||||
if user_credentials is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
if not verify_password(
|
||||
user_credentials.password_hash,
|
||||
credentials.password,
|
||||
):
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
user = User(
|
||||
id=user_credentials.id,
|
||||
username=user_credentials.username,
|
||||
display_name=user_credentials.display_name,
|
||||
created_at=user_credentials.created_at,
|
||||
)
|
||||
|
||||
token, ttl = await create_session(user.id)
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
|
||||
return SessionResponse(
|
||||
token=token,
|
||||
token_type="bearer",
|
||||
expires_at=expires_at,
|
||||
user=user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=MessagePage,
|
||||
@app.delete(
|
||||
"/api/v1/auth/sessions/current",
|
||||
status_code=204,
|
||||
)
|
||||
async def get_messages(
|
||||
chat_id: UUID,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
async def delete_current_session(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Limit must be between 1 and 100",
|
||||
)
|
||||
|
||||
return await store.get_messages(
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
await delete_session(credentials.credentials)
|
||||
@@ -18,6 +18,11 @@ class CreateUser(BaseModel):
|
||||
max_length=100,
|
||||
)
|
||||
|
||||
password: str = Field(
|
||||
min_length=12,
|
||||
max_length=128,
|
||||
)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, value: str) -> str:
|
||||
@@ -34,6 +39,13 @@ class User(BaseModel):
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.models import CreateUser, User
|
||||
from src.security import hash_password
|
||||
|
||||
|
||||
async def create_user(
|
||||
session: AsyncSession,
|
||||
data: CreateUser,
|
||||
) -> User:
|
||||
user_id = uuid4()
|
||||
password_hash = hash_password(data.password)
|
||||
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES (
|
||||
:id,
|
||||
:username,
|
||||
:display_name,
|
||||
:password_hash
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": user_id,
|
||||
"username": data.username,
|
||||
"display_name": data.display_name,
|
||||
"password_hash": password_hash,
|
||||
},
|
||||
)
|
||||
|
||||
row = result.one()
|
||||
|
||||
return User(
|
||||
id=UUID(str(row.id)),
|
||||
username=row.username,
|
||||
display_name=row.display_name,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
async def get_user_credentials_by_username(
|
||||
session: AsyncSession,
|
||||
username: str,
|
||||
):
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE username = :username
|
||||
"""
|
||||
),
|
||||
{
|
||||
"username": username,
|
||||
},
|
||||
)
|
||||
|
||||
return result.one_or_none()
|
||||
|
||||
|
||||
async def get_user_by_id(
|
||||
session: AsyncSession,
|
||||
user_id: UUID,
|
||||
) -> User | None:
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = :user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"user_id": user_id,
|
||||
},
|
||||
)
|
||||
|
||||
row = result.one_or_none()
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
return User(
|
||||
id=UUID(str(row.id)),
|
||||
username=row.username,
|
||||
display_name=row.display_name,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
@@ -0,0 +1,60 @@
|
||||
import os
|
||||
import secrets
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
|
||||
|
||||
CACHE_URL_FILE = "/run/secrets/cache_url"
|
||||
DEFAULT_SESSION_TTL_SECONDS = 3600
|
||||
|
||||
|
||||
def read_cache_url() -> str:
|
||||
with open(CACHE_URL_FILE, encoding="utf-8") as file:
|
||||
return file.read().strip()
|
||||
|
||||
|
||||
def get_session_ttl_seconds() -> int:
|
||||
return int(
|
||||
os.getenv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
str(DEFAULT_SESSION_TTL_SECONDS),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
redis_client = Redis.from_url(
|
||||
read_cache_url(),
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=5,
|
||||
socket_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
async def create_session(user_id: UUID) -> tuple[str, int]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
ttl = get_session_ttl_seconds()
|
||||
|
||||
await redis_client.set(
|
||||
f"session:{token}",
|
||||
str(user_id),
|
||||
ex=ttl,
|
||||
)
|
||||
|
||||
return token, ttl
|
||||
|
||||
|
||||
async def get_session_user_id(token: str) -> UUID | None:
|
||||
value = await redis_client.get(f"session:{token}")
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
async def delete_session(token: str) -> None:
|
||||
await redis_client.delete(f"session:{token}")
|
||||
Reference in New Issue
Block a user