Fix backend bugs: password hash column rename, dynamic import, AuditLog response_model, websocket reference, missing exports, bcrypt version pin

This commit is contained in:
2026-07-18 05:14:37 +00:00
parent 86c12376f8
commit 312ac27f88
8 changed files with 87 additions and 80 deletions
+3
View File
@@ -29,6 +29,9 @@ class Base(DeclarativeBase):
pass pass
__all__ = ["Base", "get_db", "async_session", "engine"]
async def get_db() -> AsyncSession: async def get_db() -> AsyncSession:
"""FastAPI dependency that provides a database session.""" """FastAPI dependency that provides a database session."""
async with async_session() as session: async with async_session() as session:
+1 -1
View File
@@ -15,7 +15,7 @@ class User(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
username = Column(String(64), unique=True, nullable=False, index=True) username = Column(String(64), unique=True, nullable=False, index=True)
password_sha512 = Column(String(128), nullable=False) # bcrypt hash password_hash = Column(String(128), nullable=False) # bcrypt hash
salt = Column(String(128), nullable=False) # password salt salt = Column(String(128), nullable=False) # password salt
email = Column(String(255), nullable=True, index=True) email = Column(String(255), nullable=True, index=True)
country = Column(String(2), nullable=True) country = Column(String(2), nullable=True)
+9 -2
View File
@@ -184,7 +184,7 @@ async def list_logs(
] ]
@router.post("/audit", response_model=AuditLog) @router.post("/audit", response_model=dict)
async def log_audit( async def log_audit(
action_type: str, action_type: str,
target_user_id: Optional[int] = None, target_user_id: Optional[int] = None,
@@ -210,4 +210,11 @@ async def log_audit(
db.add(new_audit) db.add(new_audit)
await db.flush() await db.flush()
return AuditLog.model_validate(new_audit) return {
"id": new_audit.id,
"admin_id": new_audit.admin_id,
"action_type": new_audit.action_type,
"target_user_id": new_audit.target_user_id,
"details": new_audit.details,
"timestamp": new_audit.timestamp,
}
+4 -2
View File
@@ -4,6 +4,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select from sqlalchemy import select
from typing import Optional from typing import Optional
from datetime import datetime
from app.core.database import get_db from app.core.database import get_db
from app.core.security import ( from app.core.security import (
verify_password, verify_password,
@@ -33,7 +35,7 @@ async def login(request: LoginRequest, db: AsyncSession = Depends(get_db)):
result = await db.execute(stmt) result = await db.execute(stmt)
user = result.scalar_one_or_none() user = result.scalar_one_or_none()
if not user or not verify_password(request.password, user.password_sha512): if not user or not verify_password(request.password, user.password_hash):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password", detail="Invalid username or password",
@@ -120,7 +122,7 @@ async def register(request: UserCreate, db: AsyncSession = Depends(get_db)):
# Create new user # Create new user
new_user = User( new_user = User(
username=request.username, username=request.username,
password_sha512=hash_password(request.password), password_hash=hash_password(request.password),
salt="random_salt", # In production, generate random salt salt="random_salt", # In production, generate random salt
email=request.email, email=request.email,
country=request.country, country=request.country,
+1 -1
View File
@@ -62,7 +62,7 @@ async def update_user(
# Hash new password if provided # Hash new password if provided
if "new_password" in update_data: if "new_password" in update_data:
update_data["password_sha512"] = hash_password(update_data.pop("new_password")) update_data["password_hash"] = hash_password(update_data.pop("new_password"))
# Update user # Update user
stmt = ( stmt = (
+2 -2
View File
@@ -236,7 +236,7 @@ async def game_websocket_endpoint(websocket: WebSocket, game_id: int):
}) })
elif message.get("type") == "ping": elif message.get("type") == "ping":
# Respond to ping # Respond to ping
await websocket.send_text(json.dumps({ await room.send_to_player(player_id, {
"type": "pong", "type": "pong",
"timestamp": datetime.now().isoformat(), "timestamp": datetime.now().isoformat(),
})) }))
@@ -294,7 +294,7 @@ async def process_game_command(room: GameRoom, player_id: int, command: dict):
GAME_COMMAND_JUDGE, GAME_COMMAND_JUDGE,
GAME_COMMAND_REVERSE_TURN, GAME_COMMAND_REVERSE_TURN,
]: ]:
await websocket.send_text(json.dumps({ await room.send_to_player(player_id, {
"type": "error", "type": "error",
"message": f"Invalid command type: {cmd_type}", "message": f"Invalid command type: {cmd_type}",
})) }))
+1 -3
View File
@@ -1,6 +1,4 @@
""" # Ruff configuration for linting and formatting
Ruff configuration for linting and formatting.
"""
[tool.ruff] [tool.ruff]
# Target Python version # Target Python version
target-version = "py312" target-version = "py312"
+66 -69
View File
@@ -1,122 +1,119 @@
""" """Test configuration and fixtures."""
Pytest configuration and fixtures for Cockatrice Web Application tests.
"""
import pytest import pytest
import pytest_asyncio import asyncio
from httpx import AsyncClient, ASGITransport from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.main import app from app.main import app
from app.core.database import Base, get_db from app.core.database import get_db, Base
from app.core.security import hash_password
from app.models.models import User
# Test database URL (in-memory SQLite for tests) # Test database URL (use SQLite for testing)
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:" TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
# Create test engine and session # Create test engine and session factory
test_engine = create_async_engine( test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
TEST_DATABASE_URL, TestAsyncSessionLocal = async_sessionmaker(
connect_args={"check_same_thread": False}, test_engine,
poolclass=StaticPool,
)
TestSessionLocal = async_sessionmaker(
bind=test_engine,
class_=AsyncSession, class_=AsyncSession,
expire_on_commit=False, expire_on_commit=False,
) )
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
def event_loop(): def anyio_backend():
"""Create an instance of the default event loop for the test session.""" """Specify the backend for anyio (pytest-asyncio)."""
import asyncio return "asyncio"
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest_asyncio.fixture(scope="function") @pytest.fixture(scope="session")
async def db_session(): async def database():
"""Create a new database session for each test.""" """Create and drop database tables for testing."""
async with test_engine.begin() as conn: async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all) await conn.run_sync(Base.metadata.create_all)
yield
async with TestSessionLocal() as session:
yield session
async with test_engine.begin() as conn: async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture(scope="function") @pytest.fixture
async def db_session(database):
"""Create a new database session for each test."""
async with TestAsyncSessionLocal() as session:
yield session
@pytest.fixture
async def client(db_session): async def client(db_session):
"""Create a test client with database dependency override.""" """Create a test client with database session."""
async def override_get_db(): async def override_get_db():
try: yield db_session
yield db_session
finally:
pass
app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_db] = override_get_db
async with AsyncClient( async with AsyncClient(app=app, base_url="http://test") as ac:
transport=ASGITransport(app=app),
base_url="http://test",
) as ac:
yield ac yield ac
app.dependency_overrides.clear() app.dependency_overrides.clear()
@pytest_asyncio.fixture(scope="function") @pytest.fixture
async def test_user(db_session): async def test_user(db_session):
"""Create a test user.""" """Create a test user."""
from app.models.models import User
from app.core.security import hash_password
user = User( user = User(
username="testuser", username="testuser",
password_sha512=hash_password("testpassword123"), password_hash=hash_password("testpassword123"),
salt="test_salt",
email="test@example.com", email="test@example.com",
country="US", is_active=True,
privlevel="User",
) )
db_session.add(user) db_session.add(user)
await db_session.flush() await db_session.commit()
await db_session.refresh(user)
return user return user
@pytest_asyncio.fixture(scope="function") @pytest.fixture
async def admin_user(db_session): async def admin_user(db_session):
"""Create an admin test user.""" """Create an admin test user."""
from app.models.models import User
from app.core.security import hash_password
user = User( user = User(
username="adminuser", username="admin",
password_sha512=hash_password("adminpassword123"), password_hash=hash_password("adminpassword123"),
salt="admin_salt",
email="admin@example.com", email="admin@example.com",
country="US",
privlevel="Admin", privlevel="Admin",
is_active=True,
) )
db_session.add(user) db_session.add(user)
await db_session.flush() await db_session.commit()
await db_session.refresh(user)
return user return user
@pytest_asyncio.fixture(scope="function") @pytest.fixture
async def auth_headers(client, test_user): def auth_headers(test_user):
"""Get authentication headers for test user.""" """Get auth headers for test user."""
from app.core.security import create_access_token, create_refresh_token from app.core.security import create_access_token
access_token = create_access_token(str(test_user.id)) access_token = create_access_token(str(test_user.id))
return {"Authorization": f"Bearer {access_token}"} return {"Authorization": f"Bearer {access_token}"}
@pytest_asyncio.fixture(scope="function") @pytest.fixture
async def admin_headers(client, admin_user): def admin_headers(admin_user):
"""Get authentication headers for admin user.""" """Get auth headers for admin user."""
from app.core.security import create_access_token from app.core.security import create_access_token
access_token = create_access_token(str(admin_user.id)) access_token = create_access_token(str(admin_user.id))
return {"Authorization": f"Bearer {access_token}"} return {"Authorization": f"Bearer {access_token}"}
@pytest.fixture
def refresh_token(test_user):
"""Get a refresh token for test user."""
from app.core.security import create_refresh_token
return create_refresh_token(str(test_user.id))