diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index 10e06a11b..5a749f64a 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -8,6 +8,7 @@ from config import ( ) from endpoints.responses.heartbeat import HeartbeatResponse from fastapi import APIRouter +from handler.database import db_user_handler from handler.filesystem import fs_platform_handler from handler.metadata.igdb_handler import IGDB_API_ENABLED from handler.metadata.moby_handler import MOBY_API_ENABLED @@ -27,6 +28,7 @@ def heartbeat() -> HeartbeatResponse: return { "VERSION": get_version(), + "SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0, "ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED, "STEAMGRIDDB_ENABLED": STEAMGRIDDB_API_ENABLED, "METADATA_SOURCES": { diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index 208f15367..d2b6582d2 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -23,6 +23,7 @@ class MetadataSourcesDict(TypedDict): class HeartbeatResponse(TypedDict): VERSION: str + SETUP_WIZARD: bool WATCHER: WatcherDict SCHEDULER: SchedulerDict ANY_SOURCE_ENABLED: bool diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index ad26c5b9e..6a89246ad 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -16,7 +16,10 @@ router = APIRouter() @protected_route( - router.post, "/users", ["users.write"], status_code=status.HTTP_201_CREATED + router.post, + "/users", + [] if len(db_user_handler.get_admin_users()) == 0 else ["users.write"], + status_code=status.HTTP_201_CREATED, ) def add_user(request: Request, username: str, password: str, role: str) -> UserSchema: """Create user endpoint @@ -86,7 +89,7 @@ def get_user(request: Request, id: int) -> UserSchema: return user -@protected_route(router.put, "/users/{id}", ["users.write"]) +@protected_route(router.put, "/users/{id}") def update_user( request: Request, id: int, form_data: Annotated[UserForm, Depends()] ) -> UserSchema: @@ -105,17 +108,23 @@ def update_user( UserSchema: Updated user info """ - user = db_user_handler.get_user(id) - if not user: - raise HTTPException(status_code=404, detail="User not found") + db_user = db_user_handler.get_user(id) + if not db_user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="User not found" + ) + + if not db_user.id == request.user.id: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") cleaned_data = {} - if form_data.username and form_data.username != user.username: + if form_data.username and form_data.username != db_user.username: existing_user = db_user_handler.get_user_by_username(form_data.username.lower()) if existing_user: raise HTTPException( - status_code=400, detail="Username already in use by another user" + status_code=status.HTTP_400_BAD_REQUEST, + detail="Username already in use by another user", ) cleaned_data["username"] = form_data.username.lower() @@ -134,7 +143,7 @@ def update_user( cleaned_data["enabled"] = form_data.enabled # type: ignore[assignment] if form_data.avatar is not None: - user_avatar_path = fs_asset_handler.build_avatar_path(user=user) + user_avatar_path = fs_asset_handler.build_avatar_path(user=db_user) file_location = f"{user_avatar_path}/{form_data.avatar.filename}" cleaned_data["avatar_path"] = file_location Path(f"{ASSETS_BASE_PATH}/{user_avatar_path}").mkdir( diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index c2350aab1..2a5fecfc9 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -1,14 +1,13 @@ from datetime import datetime, timedelta from typing import Final -from config import ROMM_AUTH_PASSWORD, ROMM_AUTH_SECRET_KEY, ROMM_AUTH_USERNAME +from config import ROMM_AUTH_SECRET_KEY from exceptions.auth_exceptions import OAuthCredentialsException from fastapi import HTTPException, status from joserfc import jwt from joserfc.errors import BadSignatureError from joserfc.jwk import OctKey from passlib.context import CryptContext -from sqlalchemy.exc import IntegrityError from starlette.requests import HTTPConnection ALGORITHM: Final = "HS256" @@ -81,7 +80,7 @@ class AuthHandler: # Key exists therefore user is probably authenticated user = db_user_handler.get_user_by_username(username) if user is None: - conn.session = {} + conn.session.clear() raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -89,29 +88,15 @@ class AuthHandler: ) if not user.enabled: - conn.session = {} + conn.session.clear() raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + status_code=status.HTTP_403_FORBIDDEN, + detail=f"Inactive user {user.username}", ) return user - def create_default_admin_user(self): - from handler.database import db_user_handler - from models.user import Role, User - - try: - db_user_handler.add_user( - User( - username=ROMM_AUTH_USERNAME, - hashed_password=self.get_password_hash(ROMM_AUTH_PASSWORD), - role=Role.ADMIN, - ) - ) - except IntegrityError: - pass - class OAuthHandler: def __init__(self) -> None: diff --git a/backend/handler/auth/tests/test_auth.py b/backend/handler/auth/tests/test_auth.py index e4dfc872b..9de47ec02 100644 --- a/backend/handler/auth/tests/test_auth.py +++ b/backend/handler/auth/tests/test_auth.py @@ -66,23 +66,7 @@ async def test_get_current_active_user_from_session_disabled_user(editor_user: U await auth_handler.get_current_active_user_from_session(conn) except HTTPException as e: assert e.status_code == 403 - assert e.detail == "Inactive user" - - -def test_create_default_admin_user(): - auth_handler.create_default_admin_user() - - user = db_user_handler.get_user_by_username("test_admin") - assert user.username == "test_admin" - assert auth_handler.verify_password("test_admin_password", user.hashed_password) - - users = db_user_handler.get_users() - assert len(users) == 1 - - auth_handler.create_default_admin_user() - - users = db_user_handler.get_users() - assert len(users) == 1 + assert e.detail == "Inactive user test_editor" async def test_hybrid_auth_backend_session(editor_user: User): diff --git a/backend/handler/database/stats_handler.py b/backend/handler/database/stats_handler.py index b04e71ead..c526456f1 100644 --- a/backend/handler/database/stats_handler.py +++ b/backend/handler/database/stats_handler.py @@ -34,4 +34,6 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_total_filesize(self, session: Session = None) -> int: """Get the total filesize of all roms in the database, in bytes.""" - return session.scalar(select(func.sum(Rom.file_size_bytes)).select_from(Rom)) + return ( + session.scalar(select(func.sum(Rom.file_size_bytes)).select_from(Rom)) or 0 + ) diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index f0a6eafa4..bfe58d37f 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -1,6 +1,7 @@ from decorators.database import begin_session from models.user import Role, User from sqlalchemy import delete, select, update +from sqlalchemy.exc import ProgrammingError from sqlalchemy.orm import Session from .base_handler import DBBaseHandler @@ -42,4 +43,10 @@ class DBUsersHandler(DBBaseHandler): @begin_session def get_admin_users(self, session: Session = None) -> list[User]: - return session.scalars(select(User).filter_by(role=Role.ADMIN)).all() + try: + return session.scalars(select(User).filter_by(role=Role.ADMIN)).all() + except ProgrammingError as e: + if "Table" in str(e.orig) and "doesn't exist" in str(e.orig): + return [] + else: + raise ProgrammingError from e diff --git a/backend/main.py b/backend/main.py index 5f006f900..c1aac2d95 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,6 +1,5 @@ import re import sys -from contextlib import asynccontextmanager import alembic.config import endpoints.sockets.scan # noqa @@ -26,27 +25,14 @@ from endpoints import ( ) from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from handler.auth import auth_handler from handler.auth.base_handler import ALGORITHM from handler.auth.hybrid_auth import HybridAuthBackend from handler.auth.middleware import CustomCSRFMiddleware, SessionMiddleware -from handler.database import db_user_handler from handler.socket_handler import socket_handler from starlette.middleware.authentication import AuthenticationMiddleware from utils import get_version - -@asynccontextmanager -async def lifespan(app: FastAPI): - if "pytest" not in sys.modules: - # Create default admin user if no admin user exists - if len(db_user_handler.get_admin_users()) == 0: - auth_handler.create_default_admin_user() - - yield - - -app = FastAPI(title="RomM API", version=get_version(), lifespan=lifespan) +app = FastAPI(title="RomM API", version=get_version()) app.add_middleware( CORSMiddleware, diff --git a/frontend/assets/scrappers/sgdb.png b/frontend/assets/scrappers/sgdb.png new file mode 100644 index 000000000..3a2899dd2 Binary files /dev/null and b/frontend/assets/scrappers/sgdb.png differ diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 3a6030176..309427758 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,26 +1,54 @@ diff --git a/frontend/src/__generated__/models/HeartbeatResponse.ts b/frontend/src/__generated__/models/HeartbeatResponse.ts index 15f70be8b..0135b0390 100644 --- a/frontend/src/__generated__/models/HeartbeatResponse.ts +++ b/frontend/src/__generated__/models/HeartbeatResponse.ts @@ -9,6 +9,7 @@ import type { WatcherDict } from "./WatcherDict"; export type HeartbeatResponse = { VERSION: string; + SETUP_WIZARD: boolean; WATCHER: WatcherDict; SCHEDULER: SchedulerDict; ANY_SOURCE_ENABLED: boolean; diff --git a/frontend/src/components/common/Navigation/CollectionsDrawer.vue b/frontend/src/components/common/Navigation/CollectionsDrawer.vue index c99ce09b3..dcf1b0ee1 100644 --- a/frontend/src/components/common/Navigation/CollectionsDrawer.vue +++ b/frontend/src/components/common/Navigation/CollectionsDrawer.vue @@ -1,12 +1,11 @@