diff --git a/README.md b/README.md index 53be26278..787dec780 100644 --- a/README.md +++ b/README.md @@ -298,4 +298,5 @@ Games can be tagged with region, revision or other tags using parenthesis in the # 🎖 Credits -* Pc icon support - Keyboard and mouse icons created by Flat Icons - Flaticon +* PC icon support - Keyboard and mouse icons created by Flat Icons - Flaticon +* Default user icon - User Default icon by Icons8 diff --git a/backend/alembic/versions/1.9.2.py b/backend/alembic/versions/1.9.2.py new file mode 100644 index 000000000..08e8fa6fc --- /dev/null +++ b/backend/alembic/versions/1.9.2.py @@ -0,0 +1,47 @@ +"""empty message + +Revision ID: 583453a8a07f +Revises: 1.8.3 +Create Date: 2023-08-10 22:18:24.012779 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "1.9.2" +down_revision = "1.8.3" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "users", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("username", sa.String(length=255), nullable=True), + sa.Column("hashed_password", sa.String(length=255), nullable=True), + sa.Column("enabled", sa.Boolean(), nullable=True), + sa.Column( + "role", sa.Enum("VIEWER", "EDITOR", "ADMIN", name="role"), nullable=True + ), + sa.Column("avatar_path", sa.String(length=255), nullable=True), + sa.PrimaryKeyConstraint("id"), + ) + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.create_index( + batch_op.f("ix_users_username"), ["username"], unique=True + ) + + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.drop_index(batch_op.f("ix_users_username")) + + op.drop_table("users") + # ### end Alembic commands ### diff --git a/backend/config/__init__.py b/backend/config/__init__.py index f24d2c6ee..abe30fcbb 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -1,49 +1,60 @@ import os +import secrets from dotenv import load_dotenv +from typing import Final load_dotenv() -# Uvicorn -DEV_PORT: int = int(os.environ.get("VITE_BACKEND_DEV_PORT", "5000")) -DEV_HOST: str = "0.0.0.0" +# UVICORN +DEV_PORT: Final = int(os.environ.get("VITE_BACKEND_DEV_PORT", "5000")) +DEV_HOST: Final = "0.0.0.0" # PATHS -ROMM_BASE_PATH: str = os.environ.get("ROMM_BASE_PATH", "/romm") -LIBRARY_BASE_PATH: str = f"{ROMM_BASE_PATH}/library" -FRONT_LIBRARY_PATH: str = "/assets/romm/library" -ROMM_USER_CONFIG_PATH: str = f"{ROMM_BASE_PATH}/config.yml" -SQLITE_DB_BASE_PATH: str = f"{ROMM_BASE_PATH}/database" -RESOURCES_BASE_PATH: str = f"{ROMM_BASE_PATH}/resources" -LOGS_BASE_PATH: str = f"{ROMM_BASE_PATH}/logs" -HIGH_PRIO_STRUCTURE_PATH: str = f"{LIBRARY_BASE_PATH}/roms" +ROMM_BASE_PATH: Final = os.environ.get("ROMM_BASE_PATH", "/romm") +LIBRARY_BASE_PATH: Final = f"{ROMM_BASE_PATH}/library" +FRONT_LIBRARY_PATH: Final = "/assets/romm/library" +ROMM_USER_CONFIG_PATH: Final = f"{ROMM_BASE_PATH}/config.yml" +SQLITE_DB_BASE_PATH: Final = f"{ROMM_BASE_PATH}/database" +RESOURCES_BASE_PATH: Final = f"{ROMM_BASE_PATH}/resources" +LOGS_BASE_PATH: Final = f"{ROMM_BASE_PATH}/logs" +HIGH_PRIO_STRUCTURE_PATH: Final = f"{LIBRARY_BASE_PATH}/roms" # DEFAULT RESOURCES -DEFAULT_URL_COVER_L: str = ( +DEFAULT_URL_COVER_L: Final = ( "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png" ) -DEFAULT_PATH_COVER_L: str = "default/default/cover/big.png" -DEFAULT_URL_COVER_S: str = ( +DEFAULT_PATH_COVER_L: Final = "default/default/cover/big.png" +DEFAULT_URL_COVER_S: Final = ( "https://images.igdb.com/igdb/image/upload/t_cover_small/nocover.png" ) -DEFAULT_PATH_COVER_S: str = "default/default/cover/small.png" +DEFAULT_PATH_COVER_S: Final = "default/default/cover/small.png" # MARIADB -DB_HOST = os.environ.get("DB_HOST", "127.0.0.1") -DB_PORT: int = int(os.environ.get("DB_PORT", 3306)) -DB_USER = os.environ.get("DB_USER") -DB_PASSWD = os.environ.get("DB_PASSWD") -DB_NAME = os.environ.get("DB_NAME", "romm") +DB_HOST: Final = os.environ.get("DB_HOST", "127.0.0.1") +DB_PORT: Final = int(os.environ.get("DB_PORT", 3306)) +DB_USER: Final = os.environ.get("DB_USER") +DB_PASSWD: Final = os.environ.get("DB_PASSWD") +DB_NAME: Final = os.environ.get("DB_NAME", "romm") # REDIS -REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost') -REDIS_PORT = os.environ.get('REDIS_PORT', '6379') +ENABLE_EXPERIMENTAL_REDIS: Final = os.environ.get("ENABLE_EXPERIMENTAL_REDIS", "false") == "true" +REDIS_HOST: Final = os.environ.get("REDIS_HOST", "localhost") +REDIS_PORT: Final = os.environ.get("REDIS_PORT", "6379") # IGDB -CLIENT_ID = os.environ.get("CLIENT_ID", "") -CLIENT_SECRET = os.environ.get("CLIENT_SECRET", "") +CLIENT_ID: Final = os.environ.get("CLIENT_ID", "") +CLIENT_SECRET: Final = os.environ.get("CLIENT_SECRET", "") # STEAMGRIDDB -STEAMGRIDDB_API_KEY = os.environ.get("STEAMGRIDDB_API_KEY", "") +STEAMGRIDDB_API_KEY: Final = os.environ.get("STEAMGRIDDB_API_KEY", "") # DB DRIVERS -ROMM_DB_DRIVER = os.environ.get("ROMM_DB_DRIVER", "sqlite") +ROMM_DB_DRIVER: Final = os.environ.get("ROMM_DB_DRIVER", "sqlite") + +# AUTH +ROMM_AUTH_ENABLED: Final = os.environ.get("ROMM_AUTH_ENABLED", "false") == "true" +ROMM_AUTH_USERNAME: Final = os.environ.get("ROMM_AUTH_USERNAME", "admin") +ROMM_AUTH_PASSWORD: Final = os.environ.get("ROMM_AUTH_PASSWORD", "admin") +ROMM_AUTH_SECRET_KEY: Final = os.environ.get( + "ROMM_AUTH_SECRET_KEY", secrets.token_hex(32) +) diff --git a/backend/endpoints/identity.py b/backend/endpoints/identity.py new file mode 100644 index 000000000..c43c6094f --- /dev/null +++ b/backend/endpoints/identity.py @@ -0,0 +1,210 @@ +import secrets +from typing import Optional, Annotated +from fastapi import APIRouter, HTTPException, status, Request, Depends, File, UploadFile +from fastapi.security.http import HTTPBasic +from pydantic import BaseModel, BaseConfig + +from handler import dbh +from models.user import User, Role +from utils.cache import cache +from utils.auth import authenticate_user, get_password_hash, clear_session +from utils.oauth import protected_route +from utils.fs import build_avatar_path +from config import ROMM_AUTH_ENABLED +from exceptions.credentials_exceptions import credentials_exception, disabled_exception + +router = APIRouter() + + +class UserSchema(BaseModel): + id: int + username: str + enabled: bool + role: Role + oauth_scopes: list[str] + avatar_path: str + + class Config(BaseConfig): + orm_mode = True + + +@router.post("/login") +def login(request: Request, credentials=Depends(HTTPBasic())): + """Session login endpoint""" + user = authenticate_user(credentials.username, credentials.password) + if not user: + raise credentials_exception + + if not user.enabled: + raise disabled_exception + + # Generate unique session key and store in cache + request.session["session_id"] = secrets.token_hex(16) + cache.set(f'romm:{request.session["session_id"]}', user.username) # type: ignore[attr-defined] + + return {"message": "Successfully logged in"} + + +@router.post("/logout") +def logout(request: Request): + """Session logout endpoint""" + # Check if session key already stored in cache + session_id = request.session.get("session_id") + if not session_id: + return {"message": "Already logged out"} + + if not request.user.is_authenticated: + return {"message": "Already logged out"} + + clear_session(request) + + return {"message": "Successfully logged out"} + + +@protected_route(router.get, "/users", ["users.read"]) +def users(request: Request) -> list[UserSchema]: + """Get all users""" + return dbh.get_users() + + +@protected_route(router.get, "/users/me", ["me.read"]) +def current_user(request: Request) -> UserSchema | None: + """Get current user""" + return request.user + + +@protected_route(router.get, "/users/{user_id}", ["users.read"]) +def get_user(request: Request, user_id: int) -> UserSchema: + """Get a specific user""" + user = dbh.get_user(user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + return user + + +@protected_route( + router.post, + "/users", + ["users.write"], + status_code=status.HTTP_201_CREATED, +) +def create_user( + request: Request, username: str, password: str, role: str +) -> UserSchema: + """Create a new user""" + if not ROMM_AUTH_ENABLED: + raise HTTPException( + status_code=400, + detail="Cannot create user: ROMM_AUTH_ENABLED is set to False", + ) + + user = User( + username=username, + hashed_password=get_password_hash(password), + role=Role[role.upper()], + ) + + return dbh.add_user(user) + + +class UserUpdateForm: + def __init__( + self, + username: Optional[str] = None, + password: Optional[str] = None, + role: Optional[str] = None, + enabled: Optional[bool] = None, + avatar: Optional[UploadFile] = File(None), + ): + self.username = username + self.password = password + self.role = role + self.enabled = enabled + self.avatar = avatar + + +@protected_route(router.put, "/users/{user_id}", ["users.write"]) +def update_user( + request: Request, user_id: int, form_data: Annotated[UserUpdateForm, Depends()] +) -> UserSchema: + """Update a specific user""" + if not ROMM_AUTH_ENABLED: + raise HTTPException( + status_code=400, + detail="Cannot update user: ROMM_AUTH_ENABLED is set to False", + ) + + user = dbh.get_user(user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + cleaned_data = {} + + if form_data.username and form_data.username != user.username: + existing_user = dbh.get_user_by_username(form_data.username.lower()) + if existing_user: + raise HTTPException( + status_code=400, detail="Username already in use by another user" + ) + + cleaned_data["username"] = form_data.username.lower() + + if form_data.password: + cleaned_data["hashed_password"] = get_password_hash(form_data.password) + + # You can't change your own role + if form_data.role and request.user.id != user_id: + cleaned_data["role"] = Role[form_data.role.upper()] # type: ignore[assignment] + + # You can't disable yourself + if form_data.enabled is not None and request.user.id != user_id: + cleaned_data["enabled"] = form_data.enabled # type: ignore[assignment] + + if form_data.avatar is not None: + cleaned_data["avatar_path"], avatar_user_path = build_avatar_path( + form_data.avatar.filename, form_data.username + ) + file_location = f"{avatar_user_path}/{form_data.avatar.filename}" + with open(file_location, "wb+") as file_object: + file_object.write(form_data.avatar.file.read()) + + if cleaned_data: + dbh.update_user(user_id, cleaned_data) + + # Log out the current user if username or password changed + creds_updated = cleaned_data.get("username") or cleaned_data.get( + "hashed_password" + ) + if request.user.id == user_id and creds_updated: + clear_session(request) + + return dbh.get_user(user_id) + + +@protected_route(router.delete, "/users/{user_id}", ["users.write"]) +def delete_user(request: Request, user_id: int): + """Delete a specific user""" + if not ROMM_AUTH_ENABLED: + raise HTTPException( + status_code=400, + detail="Cannot delete user: ROMM_AUTH_ENABLED is set to False", + ) + + user = dbh.get_user(user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + # You can't delete the user you're logged in as + if request.user.id == user_id: + raise HTTPException(status_code=400, detail="You cannot delete yourself") + + # You can't delete the last admin user + if user.role == Role.ADMIN and len(dbh.get_admin_users()) == 1: + raise HTTPException( + status_code=400, detail="You cannot delete the last admin user" + ) + + dbh.delete_user(user_id) + + return {"message": "User successfully deleted"} diff --git a/backend/endpoints/oauth.py b/backend/endpoints/oauth.py new file mode 100644 index 000000000..a2912a139 --- /dev/null +++ b/backend/endpoints/oauth.py @@ -0,0 +1,112 @@ +from typing import Annotated, Final +from datetime import timedelta +from fastapi import Depends, APIRouter, HTTPException, status + + +from utils.auth import authenticate_user +from utils.oauth import ( + OAuth2RequestForm, + create_oauth_token, + get_current_active_user_from_bearer_token, +) + + +ACCESS_TOKEN_EXPIRE_MINUTES: Final = 30 +REFRESH_TOKEN_EXPIRE_DAYS: Final = 7 + +router = APIRouter() + + +@router.post("/token") +async def token(form_data: Annotated[OAuth2RequestForm, Depends()]): + """OAuth2 token endpoint""" + + # Suppport refreshing access tokens + if form_data.grant_type == "refresh_token": + token = form_data.refresh_token + if not token: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="Missing refresh token" + ) + + user, payload = await get_current_active_user_from_bearer_token(token) + if payload.get("type") != "refresh": + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token" + ) + + access_token = create_oauth_token( + data={ + "sub": user.username, + "scopes": payload.get("scopes"), + "type": "access", + }, + expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES), + ) + + return { + "access_token": access_token, + "token_type": "bearer", + "expires": ACCESS_TOKEN_EXPIRE_MINUTES * 60, + } + + # Authentication via username/password + elif form_data.grant_type == "password": + if not form_data.username or not form_data.password: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Missing username or password", + ) + + user = authenticate_user(form_data.username, form_data.password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid username or password", + ) + + # TODO: Authentication via client_id/client_secret + elif form_data.grant_type == "client_credentials": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Client credentials are not yet supported", + ) + + else: + # All other grant types are unsupported + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid or unsupported grant type", + ) + + # Check if user has access to requested scopes + if not set(form_data.scopes).issubset(user.oauth_scopes): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Insufficient scope", + ) + + access_token = create_oauth_token( + data={ + "sub": user.username, + "scopes": " ".join(form_data.scopes), + "type": "access", + }, + expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES), + ) + + refresh_token = create_oauth_token( + data={ + "sub": user.username, + "scopes": " ".join(form_data.scopes), + "type": "refresh", + }, + expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS), + ) + + return { + "access_token": access_token, + "refresh_token": refresh_token, + "token_type": "bearer", + "expires": ACCESS_TOKEN_EXPIRE_MINUTES * 60, + } diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index 850e18cb8..b131340e6 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -1,7 +1,8 @@ -from fastapi import APIRouter +from fastapi import APIRouter, Request from pydantic import BaseModel, BaseConfig from handler import dbh +from utils.oauth import protected_route router = APIRouter() @@ -22,7 +23,7 @@ class PlatformSchema(BaseModel): orm_mode = True -@router.get("/platforms", status_code=200) -def platforms() -> list[PlatformSchema]: +@protected_route(router.get, "/platforms", ["platforms.read"]) +def platforms(request: Request) -> list[PlatformSchema]: """Returns platforms data""" return dbh.get_platforms() diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 53c1dd2fd..01aa58909 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -6,14 +6,14 @@ from fastapi.responses import FileResponse from pydantic import BaseModel, BaseConfig from stat import S_IFREG -from stream_zip import ZIP_64, stream_zip +from stream_zip import ZIP_64, stream_zip # type: ignore[import] from logger.logger import log from handler import dbh from utils import fs, get_file_name_with_no_tags -from utils.exceptions import RomNotFoundError, RomAlreadyExistsException -from models.rom import Rom -from models.platform import Platform +from exceptions.fs_exceptions import RomNotFoundError, RomAlreadyExistsException +from utils.oauth import protected_route +from models import Rom, Platform from config import LIBRARY_BASE_PATH from .utils import CustomStreamingResponse @@ -66,15 +66,16 @@ class RomSchema(BaseModel): orm_mode = True -@router.get("/platforms/{p_slug}/roms/{id}", status_code=200) -def rom(id: int) -> RomSchema: +@protected_route(router.get, "/platforms/{p_slug}/roms/{id}", ["roms.read"]) +def rom(request: Request, id: int) -> RomSchema: """Returns one rom data of the desired platform""" return dbh.get_rom(id) -@router.get("/platforms/{p_slug}/roms/{id}/download", status_code=200) -def download_rom(id: int, files: str): +@protected_route(router.get, "/platforms/{p_slug}/roms/{id}/download", ["roms.read"]) +def download_rom(request: Request, id: int, files: str): + """Downloads a rom or a zip file with multiple roms""" rom = dbh.get_rom(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" @@ -104,9 +105,13 @@ def download_rom(id: int, files: str): ) -@router.get("/platforms/{p_slug}/roms", status_code=200) +@protected_route(router.get, "/platforms/{p_slug}/roms", ["roms.read"]) def roms( - p_slug: str, size: int = 60, cursor: str = "", search_term: str = "" + request: Request, + p_slug: str, + size: int = 60, + cursor: str = "", + search_term: str = "", ) -> CursorPage[RomSchema]: """Returns all roms of the desired platform""" with dbh.session.begin() as session: @@ -123,11 +128,11 @@ def roms( return paginate(session, qq, cursor_params) -@router.patch("/platforms/{p_slug}/roms/{id}", status_code=200) -async def updateRom(req: Request, p_slug: str, id: int) -> dict: +@protected_route(router.patch, "/platforms/{p_slug}/roms/{id}", ["roms.write"]) +async def update_rom(request: Request, p_slug: str, id: int) -> dict: """Updates rom details""" - data: dict = await req.json() + data: dict = await request.json() updated_rom: dict = data["updatedRom"] db_rom: Rom = dbh.get_rom(id) platform: Platform = dbh.get_platform(p_slug) @@ -149,14 +154,14 @@ async def updateRom(req: Request, p_slug: str, id: int) -> dict: overwrite=True, p_slug=platform.slug, r_name=updated_rom["file_name_no_tags"], - url_cover=updated_rom["url_cover"], + url_cover=updated_rom.get("url_cover", ""), ) ) updated_rom.update( fs.get_screenshots( p_slug=platform.slug, r_name=updated_rom["file_name_no_tags"], - url_screenshots=updated_rom["url_screenshots"], + url_screenshots=updated_rom.get("url_screenshots", ""), ), ) dbh.update_rom(id, updated_rom) @@ -167,14 +172,15 @@ async def updateRom(req: Request, p_slug: str, id: int) -> dict: } -@router.delete("/platforms/{p_slug}/roms/{id}", status_code=200) -def delete_rom(p_slug: str, id: int, filesystem: bool = False) -> dict: - """Detele rom from database [and filesystem]""" +def _delete_single_rom(rom_id: int, p_slug: str, filesystem: bool = False): + rom = dbh.get_rom(rom_id) + if not rom: + error = f"Rom with id {rom_id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) - rom: Rom = dbh.get_rom(id) log.info(f"Deleting {rom.file_name} from database") - dbh.delete_rom(id) - dbh.update_n_roms(p_slug) + dbh.delete_rom(rom_id) if filesystem: log.info(f"Deleting {rom.file_name} from filesystem") @@ -186,4 +192,35 @@ def delete_rom(p_slug: str, id: int, filesystem: bool = False) -> dict: log.error(error) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) + return rom + + +@protected_route(router.delete, "/platforms/{p_slug}/roms/{id}", ["roms.write"]) +def delete_rom( + request: Request, p_slug: str, id: int, filesystem: bool = False +) -> dict: + """Detele rom from database [and filesystem]""" + + rom = _delete_single_rom(id, p_slug, filesystem) + dbh.update_n_roms(p_slug) + return {"msg": f"{rom.file_name} deleted successfully!"} + + +@protected_route(router.post, "/platforms/{p_slug}/roms/delete", ["roms.write"]) +async def mass_delete_roms( + request: Request, + p_slug: str, + filesystem: bool = False, +) -> dict: + """Detele multiple roms from database [and filesystem]""" + + data: dict = await request.json() + roms_ids: list = data["roms"] + + for rom_id in roms_ids: + _delete_single_rom(rom_id, p_slug, filesystem) + + dbh.update_n_roms(p_slug) + + return {"msg": f"{len(roms_ids)} roms deleted successfully!"} diff --git a/backend/endpoints/scan.py b/backend/endpoints/scan.py index ef8ceb051..bd00c6561 100644 --- a/backend/endpoints/scan.py +++ b/backend/endpoints/scan.py @@ -3,16 +3,21 @@ import socketio # type: ignore from rq import Queue from logger.logger import log +from config import ENABLE_EXPERIMENTAL_REDIS from utils import fs, fastapi -from utils.exceptions import PlatformsNotFoundException, RomsNotFoundException +from exceptions.fs_exceptions import PlatformsNotFoundException, RomsNotFoundException from handler import dbh from utils.socket import socket_server from utils.cache import redis_client, redis_url, redis_connectable +from endpoints.platform import PlatformSchema +from endpoints.rom import RomSchema scan_queue = Queue(connection=redis_client) -async def scan_platforms(paltforms: str, complete_rescan: bool): +async def scan_platforms( + platform_slugs: list[str], complete_rescan: bool, selected_roms: list[str] +): # Connect to external socketio server sm = ( socketio.AsyncRedisManager(redis_url, write_only=True) @@ -28,7 +33,8 @@ async def scan_platforms(paltforms: str, complete_rescan: bool): await sm.emit("scan:done_ko", e.message) return - platform_list = paltforms.split(",") if paltforms else fs_platforms + platform_list = [dbh.get_platform(s).fs_slug for s in platform_slugs] + platform_list = platform_list or fs_platforms for p_slug in platform_list: try: # Verify that platform exists @@ -37,36 +43,33 @@ async def scan_platforms(paltforms: str, complete_rescan: bool): log.error(e) continue + new_platform = dbh.add_platform(scanned_platform) await sm.emit( - "scan:scanning_platform", - {"p_name": scanned_platform.name, "p_slug": scanned_platform.slug}, + "scan:scanning_platform", PlatformSchema.from_orm(new_platform).dict() ) dbh.add_platform(scanned_platform) # Scanning roms fs_roms = fs.get_roms(scanned_platform.fs_slug) - for rom in fs_roms: - rom_id = dbh.rom_exists(scanned_platform.slug, rom["file_name"]) - if rom_id and not complete_rescan: + for fs_rom in fs_roms: + rom_id = dbh.rom_exists(scanned_platform.slug, fs_rom["file_name"]) + if rom_id and rom_id not in selected_roms and not complete_rescan: continue - scanned_rom = fastapi.scan_rom(scanned_platform, rom) - await sm.emit( - "scan:scanning_rom", - { - "p_slug": scanned_platform.slug, - "p_name": scanned_platform.name, - "file_name": scanned_rom.file_name, - "r_name": scanned_rom.r_name, - "r_igdb_id": scanned_rom.r_igdb_id, - }, - ) - + scanned_rom = fastapi.scan_rom(scanned_platform, fs_rom) if rom_id: scanned_rom.id = rom_id - dbh.add_rom(scanned_rom) + rom = dbh.add_rom(scanned_rom) + await sm.emit( + "scan:scanning_rom", + { + "p_name": scanned_platform.name, + **RomSchema.from_orm(rom).dict(), + }, + ) + dbh.purge_roms(scanned_platform.slug, [rom["file_name"] for rom in fs_roms]) dbh.update_n_roms(scanned_platform.slug) dbh.purge_platforms(fs_platforms) @@ -75,14 +78,20 @@ async def scan_platforms(paltforms: str, complete_rescan: bool): @socket_server.on("scan") -async def scan_handler(_sid: str, platforms: str, complete_rescan: bool = True): +async def scan_handler(_sid: str, options: dict): """Scan platforms and roms and write them in database.""" log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning ")) fs.store_default_resources() + platform_slugs = options.get("platforms", []) + complete_rescan = options.get("rescan", False) + selected_roms = options.get("roms", []) + # Run in worker if redis is available - if redis_connectable: - return scan_queue.enqueue(scan_platforms, platforms, complete_rescan) + if redis_connectable and ENABLE_EXPERIMENTAL_REDIS: + return scan_queue.enqueue( + scan_platforms, platform_slugs, complete_rescan, selected_roms + ) else: - await scan_platforms(platforms, complete_rescan) + await scan_platforms(platform_slugs, complete_rescan, selected_roms) diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index b63f3e3ed..002d41952 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -1,19 +1,20 @@ -from fastapi import APIRouter, Request import emoji +from fastapi import APIRouter, Request from logger.logger import log from handler import igdbh +from utils.oauth import protected_route router = APIRouter() -@router.put("/search/roms/igdb", status_code=200) +@protected_route(router.put, "/search/roms/igdb", ["roms.read"]) async def search_rom_igdb( - req: Request, search_term: str = "", search_by: str = "" + request: Request, search_term: str = "", search_by: str = "" ) -> dict: - """Get all the roms matched from igdb.""" + """Search IGDB for ROMs""" - data: dict = await req.json() + data: dict = await request.json() rom: dict = data["rom"] log.info(emoji.emojize(":magnifying_glass_tilted_right: IGDB Searching")) matched_roms: list = [] diff --git a/backend/endpoints/tests/__init__.py b/backend/endpoints/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/backend/endpoints/tests/conftest.py b/backend/endpoints/tests/conftest.py new file mode 100644 index 000000000..a2948a35f --- /dev/null +++ b/backend/endpoints/tests/conftest.py @@ -0,0 +1,32 @@ +import pytest + +from utils.oauth import create_oauth_token +from datetime import timedelta +from handler.tests.conftest import setup_database, clear_database, admin_user, editor_user, viewer_user, platform, rom # noqa +from ..oauth import ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS + + +@pytest.fixture() +def access_token(admin_user): # noqa + data = { + "sub": admin_user.username, + "scopes": " ".join(admin_user.oauth_scopes), + "type": "access", + } + + return create_oauth_token( + data=data, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + ) + + +@pytest.fixture() +def refresh_token(admin_user): # noqa + data = { + "sub": admin_user.username, + "scopes": " ".join(admin_user.oauth_scopes), + "type": "refresh", + } + + return create_oauth_token( + data=data, expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) + ) diff --git a/backend/endpoints/tests/test_heartbeat.py b/backend/endpoints/tests/test_heartbeat.py new file mode 100644 index 000000000..3aba4ef3f --- /dev/null +++ b/backend/endpoints/tests/test_heartbeat.py @@ -0,0 +1,11 @@ +from fastapi.testclient import TestClient + +from main import app + +client = TestClient(app) + + +def test_heartbeat(): + response = client.get("/heartbeat") + assert response.status_code == 200 + assert response.json() == {"ROMM_AUTH_ENABLED": True} diff --git a/backend/endpoints/tests/test_identity.py b/backend/endpoints/tests/test_identity.py new file mode 100644 index 000000000..de098f06d --- /dev/null +++ b/backend/endpoints/tests/test_identity.py @@ -0,0 +1,105 @@ +import base64 +import pytest +from fastapi.testclient import TestClient + +from main import app +from utils.cache import cache +from models.user import Role + +client = TestClient(app) + + +@pytest.fixture(autouse=True) +def clear_cache(): + yield + cache.flushall() + + +def test_login_logout(admin_user): + response = client.get("/login") + + assert response.status_code == 405 + + basic_auth = base64.b64encode( + "test_admin:test_admin_password".encode("ascii") + ).decode("ascii") + response = client.post("/login", headers={"Authorization": f"Basic {basic_auth}"}) + + assert response.status_code == 200 + assert response.cookies.get("session") + assert response.json()["message"] == "Successfully logged in" + + response = client.post("/logout") + + assert response.status_code == 200 + assert response.json()["message"] == "Successfully logged out" + + +def test_get_all_users(access_token): + response = client.get("/users", headers={"Authorization": f"Bearer {access_token}"}) + assert response.status_code == 200 + + users = response.json() + assert len(users) == 1 + assert users[0]["username"] == "test_admin" + + +def test_get_current_user(access_token): + response = client.get( + "/users/me", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 200 + + user = response.json() + assert user["username"] == "test_admin" + + +def test_get_user(access_token, editor_user): + response = client.get( + f"/users/{editor_user.id}", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 200 + + user = response.json() + assert user["username"] == "test_editor" + + +def test_create_user(access_token): + response = client.post( + "/users", + params={ + "username": "new_user", + "password": "new_user_password", + "role": "viewer", + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == 201 + + user = response.json() + assert user["username"] == "new_user" + assert user["role"] == "viewer" + + +def test_update_user(access_token, editor_user): + assert editor_user.role == Role.EDITOR + + response = client.put( + f"/users/{editor_user.id}", + params={"username": "editor_user_new_username", "role": "viewer"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == 200 + + user = response.json() + assert user["role"] == "viewer" + + +def test_delete_user(access_token, editor_user): + response = client.delete( + f"/users/{editor_user.id}", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 200 + + body = response.json() + assert body["message"] == "User successfully deleted" diff --git a/backend/endpoints/tests/test_oauth.py b/backend/endpoints/tests/test_oauth.py new file mode 100644 index 000000000..0726585d2 --- /dev/null +++ b/backend/endpoints/tests/test_oauth.py @@ -0,0 +1,113 @@ +from fastapi.testclient import TestClient +from fastapi.exceptions import HTTPException + +from main import app +from endpoints.oauth import ACCESS_TOKEN_EXPIRE_MINUTES +from utils.oauth import WRITE_SCOPES + +client = TestClient(app) + + +def test_refreshing_oauth_token(refresh_token): + response = client.post( + "/token", + data={ + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + assert response.status_code == 200 + + body = response.json() + assert body["access_token"] + assert body["token_type"] == "bearer" + assert body["expires"] == ACCESS_TOKEN_EXPIRE_MINUTES * 60 + + +def test_refreshing_oauth_token_without_refresh_token(): + try: + client.post( + "/token", + data={ + "grant_type": "refresh_token", + }, + ) + except HTTPException as e: + assert e.status_code == 400 + assert e.detail == "Missing refresh token" + + +def test_refreshing_oauth_token_with_invalid_refresh_token(): + try: + client.post( + "/token", + data={ + "grant_type": "refresh_token", + "refresh_token": "invalid_token", + }, + ) + except HTTPException as e: + assert e.status_code == 400 + assert e.detail == "Invalid refresh token" + + +def test_auth_via_upass(admin_user): + response = client.post( + "/token", + data={ + "grant_type": "password", + "username": "test_admin", + "password": "test_admin_password", + }, + ) + assert response.status_code == 200 + + body = response.json() + assert body["access_token"] + assert body["refresh_token"] + assert body["token_type"] == "bearer" + assert body["expires"] == ACCESS_TOKEN_EXPIRE_MINUTES * 60 + + +def test_auth_via_upass_with_invalid_credentials(admin_user): + try: + client.post( + "/token", + data={ + "grant_type": "password", + "username": "test_admin", + "password": "a_bad_password", + }, + ) + except HTTPException as e: + assert e.status_code == 401 + assert e.detail == "Invalid username or password" + + +def test_auth_via_upass_with_excess_scopes(viewer_user): + try: + client.post( + "/token", + data={ + "grant_type": "password", + "username": "test_viewer", + "password": "test_viewer_password", + "scopes": WRITE_SCOPES + }, + ) + except HTTPException as e: + assert e.status_code == 403 + assert e.detail == "Insufficient scope" + + +def test_auth_with_invalid_grant_type(): + try: + client.post( + "/token", + data={ + "grant_type": "invalid_type", + }, + ) + except HTTPException as e: + assert e.status_code == 400 + assert e.detail == "Invalid or unsupported grant type" diff --git a/backend/endpoints/tests/test_platform.py b/backend/endpoints/tests/test_platform.py new file mode 100644 index 000000000..897c2e8a5 --- /dev/null +++ b/backend/endpoints/tests/test_platform.py @@ -0,0 +1,18 @@ +from fastapi.testclient import TestClient + +from main import app + +client = TestClient(app) + + +def test_get_platforms(access_token, platform): + response = client.get("/platforms") + assert response.status_code == 403 + + response = client.get( + "/platforms", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 200 + + platforms = response.json() + assert len(platforms) == 1 diff --git a/backend/endpoints/tests/test_rom.py b/backend/endpoints/tests/test_rom.py new file mode 100644 index 000000000..dea354962 --- /dev/null +++ b/backend/endpoints/tests/test_rom.py @@ -0,0 +1,55 @@ +from fastapi.testclient import TestClient +from unittest.mock import patch + +from main import app + +client = TestClient(app) + + +def test_get_rom(access_token, rom): + response = client.get( + f"/platforms/{rom.p_slug}/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == 200 + + body = response.json() + assert body["id"] == rom.id + + +def test_get_all_roms(access_token, rom): + response = client.get( + f"/platforms/{rom.p_slug}/roms", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == 200 + + body = response.json() + assert len(body["items"]) == 1 + assert body["items"][0]["id"] == rom.id + + +@patch("utils.fs.rename_rom") +def test_update_rom(rename_rom, access_token, rom): + response = client.patch( + f"/platforms/{rom.p_slug}/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + json={"updatedRom": {"file_name": "new_file_name"}}, + ) + assert response.status_code == 200 + + body = response.json() + assert body["rom"]["file_name"] == "new_file_name" + + assert rename_rom.called + + +def test_delete_roms(access_token, rom): + response = client.delete( + f"/platforms/{rom.p_slug}/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == 200 + + body = response.json() + assert body["msg"] == f"{rom.file_name} deleted successfully!" diff --git a/backend/exceptions/__init__.py b/backend/exceptions/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/backend/exceptions/credentials_exceptions.py b/backend/exceptions/credentials_exceptions.py new file mode 100644 index 000000000..08e3d1bf3 --- /dev/null +++ b/backend/exceptions/credentials_exceptions.py @@ -0,0 +1,17 @@ +from fastapi import HTTPException, status + + +credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", +) + +authentication_scheme_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication scheme", +) + +disabled_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Disabled user", +) diff --git a/backend/utils/exceptions.py b/backend/exceptions/fs_exceptions.py similarity index 100% rename from backend/utils/exceptions.py rename to backend/exceptions/fs_exceptions.py diff --git a/backend/handler/db_handler.py b/backend/handler/db_handler.py index 76b2df462..d88dc0ac8 100644 --- a/backend/handler/db_handler.py +++ b/backend/handler/db_handler.py @@ -7,8 +7,7 @@ from sqlalchemy.exc import ProgrammingError from logger.logger import log from config.config_loader import ConfigLoader -from models.platform import Platform -from models.rom import Rom +from models import Platform, Rom, User, Role class DBHandler: @@ -35,7 +34,7 @@ class DBHandler: def add_platform(self, platform: Platform): try: with self.session.begin() as session: - session.merge(platform) + return session.merge(platform) except ProgrammingError as e: self.raise_error(e) @@ -68,7 +67,7 @@ class DBHandler: def add_rom(self, rom: Rom): try: with self.session.begin() as session: - session.merge(rom) + return session.merge(rom) except ProgrammingError as e: self.raise_error(e) @@ -136,3 +135,59 @@ class DBHandler: return rom.id if rom else 0 except ProgrammingError as e: self.raise_error(e) + + # ========= Users ========= + def add_user(self, user: User): + try: + with self.session.begin() as session: + return session.merge(user) + except ProgrammingError as e: + self.raise_error(e) + + def get_user_by_username(self, username: str): + try: + with self.session.begin() as session: + return session.scalars( + select(User).filter_by(username=username) + ).first() + except ProgrammingError as e: + self.raise_error(e) + + def get_user(self, id: int): + try: + with self.session.begin() as session: + return session.get(User, id) + except ProgrammingError as e: + self.raise_error(e) + + def update_user(self, id: int, data: dict): + try: + with self.session.begin() as session: + session.query(User).filter(User.id == id).update( + data, synchronize_session="evaluate" + ) + except ProgrammingError as e: + self.raise_error(e) + + def delete_user(self, id: int): + try: + with self.session.begin() as session: + session.query(User).filter(User.id == id).delete( + synchronize_session="evaluate" + ) + except ProgrammingError as e: + self.raise_error(e) + + def get_users(self): + try: + with self.session.begin() as session: + return session.scalars(select(User)).all() + except ProgrammingError as e: + self.raise_error(e) + + def get_admin_users(self): + try: + with self.session.begin() as session: + return session.scalars(select(User).filter_by(role=Role.ADMIN)).all() + except ProgrammingError as e: + self.raise_error(e) diff --git a/backend/handler/igdb_handler.py b/backend/handler/igdb_handler.py index bff4ee00c..8a8486a03 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -6,7 +6,7 @@ import re import time from unidecode import unidecode as uc from requests.exceptions import HTTPError, Timeout -from typing import Optional +from typing import Final from config import CLIENT_ID, CLIENT_SECRET from utils import get_file_name_with_no_tags as get_search_term @@ -14,13 +14,11 @@ from logger.logger import log from utils.cache import cache from .ps2_opl_index import opl_index -MAIN_GAME_CATEGORY = 0 -EXPANDED_GAME_CATEGORY = 10 - -N_SCREENSHOTS = 5 - -ps2_opl_regex = r"^([A-Z]{4}_\d{3}\.\d{2})\..*$" -PS2_IGDB_ID = 8 +MAIN_GAME_CATEGORY: Final = 0 +EXPANDED_GAME_CATEGORY: Final = 10 +N_SCREENSHOTS: Final = 5 +PS2_IGDB_ID: Final = 8 +PS2_OPL_REGEX: Final = r"^([A-Z]{4}_\d{3}\.\d{2})\..*$" class IGDBHandler: @@ -121,8 +119,8 @@ class IGDBHandler: def get_rom(self, file_name: str, p_igdb_id: int): search_term = get_search_term(file_name) - # Patch support for PS2 OPL filename format - match = re.match(ps2_opl_regex, search_term) + # Patch support for PS2 OPL flename format + match = re.match(PS2_OPL_REGEX, search_term) if p_igdb_id == PS2_IGDB_ID and match: serial_code = match.group(1) index_entry = opl_index.get(serial_code, None) @@ -224,8 +222,8 @@ class TwitchAuth: sys.exit(2) # Set token in redis to expire in seconds - cache.set("twitch_token", token, ex=expires_in - 10) # type: ignore - cache.set("twitch_token_expires_at", time.time() + expires_in - 10) # type: ignore + cache.set("romm:twitch_token", token, ex=expires_in - 10) # type: ignore[attr-defined] + cache.set("romm:twitch_token_expires_at", time.time() + expires_in - 10) # type: ignore[attr-defined] log.info("Twitch token fetched!") @@ -237,8 +235,8 @@ class TwitchAuth: return "test_token" # Fetch the token cache - token = cache.get("twitch_token") # type: ignore - token_expires_at = cache.get("twitch_token_expires_at") # type: ignore + token = cache.get("romm:twitch_token") # type: ignore[attr-defined] + token_expires_at = cache.get("romm:twitch_token_expires_at") # type: ignore[attr-defined] if not token or time.time() > float(token_expires_at or 0): log.warning("Twitch token invalid: fetching a new one...") diff --git a/backend/handler/tests/conftest.py b/backend/handler/tests/conftest.py index 4f0fc4ae9..47a3f992b 100644 --- a/backend/handler/tests/conftest.py +++ b/backend/handler/tests/conftest.py @@ -4,8 +4,10 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from config.config_loader import ConfigLoader -from models.platform import Platform -from models.rom import Rom +from models import Platform, Rom, User +from models.user import Role +from utils.auth import get_password_hash +from .. import dbh engine = create_engine(ConfigLoader.get_db_engine(), pool_pre_ping=True) session = sessionmaker(bind=engine, expire_on_commit=False) @@ -21,6 +23,7 @@ def clear_database(): with session.begin() as s: s.query(Platform).delete(synchronize_session="evaluate") s.query(Rom).delete(synchronize_session="evaluate") + s.query(User).delete(synchronize_session="evaluate") @pytest.fixture @@ -28,9 +31,7 @@ def platform(): platform = Platform( name="test_platform", slug="test_platform_slug", fs_slug="test_platform" ) - with session.begin() as s: - s.merge(platform) - return platform + return dbh.add_platform(platform) @pytest.fixture @@ -44,6 +45,34 @@ def rom(platform): file_name_no_tags="test_rom", file_path="test_platform_slug/roms", ) - with session.begin() as s: - s.merge(rom) - return rom + return dbh.add_rom(rom) + + +@pytest.fixture +def admin_user(): + user = User( + username="test_admin", + hashed_password=get_password_hash("test_admin_password"), + role=Role.ADMIN, + ) + return dbh.add_user(user) + + +@pytest.fixture +def editor_user(): + user = User( + username="test_editor", + hashed_password=get_password_hash("test_editor_password"), + role=Role.EDITOR, + ) + return dbh.add_user(user) + + +@pytest.fixture +def viewer_user(): + user = User( + username="test_viewer", + hashed_password=get_password_hash("test_viewer_password"), + role=Role.VIEWER, + ) + return dbh.add_user(user) diff --git a/backend/handler/tests/test_db_handler.py b/backend/handler/tests/test_db_handler.py index abac2673f..9f210cc9c 100644 --- a/backend/handler/tests/test_db_handler.py +++ b/backend/handler/tests/test_db_handler.py @@ -1,6 +1,9 @@ +from sqlalchemy.exc import IntegrityError + from handler.db_handler import DBHandler -from models.platform import Platform -from models.rom import Rom +from models import Platform, Rom, User +from models.user import Role +from utils.auth import get_password_hash dbh = DBHandler() @@ -62,3 +65,41 @@ def test_utils(rom): with dbh.session.begin() as session: roms = session.scalars(dbh.get_roms("test_platform_slug")).all() assert dbh.rom_exists("test_platform_slug", "test_rom") == roms[0].id + + +def test_users(admin_user): + dbh.add_user( + User( + username="new_user", + hashed_password=get_password_hash("new_password"), + ) + ) + + all_users = dbh.get_users() + assert len(all_users) == 2 + + new_user = dbh.get_user_by_username("new_user") + assert new_user.username == "new_user" + assert new_user.role == Role.VIEWER + assert new_user.enabled + + dbh.update_user(new_user.id, {"role": Role.EDITOR}) + + new_user = dbh.get_user(new_user.id) + assert new_user.role == Role.EDITOR + + dbh.delete_user(new_user.id) + + all_users = dbh.get_users() + assert len(all_users) == 1 + + try: + new_user = dbh.add_user( + User( + username="test_admin", + hashed_password=get_password_hash("new_password"), + role=Role.ADMIN, + ) + ) + except IntegrityError as e: + assert "Duplicate entry 'test_admin' for key" in str(e) diff --git a/backend/main.py b/backend/main.py index f8f9a1151..7cf95527c 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,14 +1,25 @@ import uvicorn import alembic.config +import re +import sys from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi_pagination import add_pagination +from starlette.middleware.authentication import AuthenticationMiddleware +from starlette.middleware.sessions import SessionMiddleware -from config import DEV_PORT, DEV_HOST -from endpoints import search, platform, rom, scan # noqa +from config import DEV_PORT, DEV_HOST, ROMM_AUTH_SECRET_KEY, ROMM_AUTH_ENABLED +from endpoints import search, platform, rom, identity, oauth, scan # noqa +from handler import dbh from utils.socket import socket_app +from utils.auth import ( + HybridAuthBackend, + CustomCSRFMiddleware, + create_default_admin_user, +) + +app = FastAPI(title="RomM API", version="0.1.0") -app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -16,18 +27,52 @@ app.add_middleware( allow_methods=["*"], allow_headers=["*"], ) -app.include_router(search.router) + +if ROMM_AUTH_ENABLED and "pytest" not in sys.modules: + # CSRF protection (except endpoints listed in exempt_urls) + app.add_middleware( + CustomCSRFMiddleware, + secret=ROMM_AUTH_SECRET_KEY, + exempt_urls=[re.compile(r"^/token.*"), re.compile(r"^/ws")], + ) + +# Handles both basic and oauth authentication +app.add_middleware( + AuthenticationMiddleware, + backend=HybridAuthBackend(), +) + +# Enables support for sessions on requests +app.add_middleware( + SessionMiddleware, + secret_key=ROMM_AUTH_SECRET_KEY, + same_site="strict", + https_only=False, +) + +app.include_router(oauth.router) +app.include_router(identity.router) app.include_router(platform.router) app.include_router(rom.router) +app.include_router(search.router) add_pagination(app) app.mount("/ws", socket_app) +# Endpoint to set the CSRF token in cache +@app.get("/heartbeat") +def heartbeat(): + return {"ROMM_AUTH_ENABLED": ROMM_AUTH_ENABLED} + + @app.on_event("startup") def startup() -> None: """Startup application.""" - pass + + # Create default admin user if no admin user exists + if len(dbh.get_admin_users()) == 0: + create_default_admin_user() if __name__ == "__main__": diff --git a/backend/models/__init__.py b/backend/models/__init__.py index e69de29bb..74a9d2cd8 100644 --- a/backend/models/__init__.py +++ b/backend/models/__init__.py @@ -0,0 +1,3 @@ +from .platform import Platform # noqa[401] +from .rom import Rom # noqa[401] +from .user import User, Role # noqa[401] diff --git a/backend/models/platform.py b/backend/models/platform.py index dc03f9ee4..ad5b23483 100644 --- a/backend/models/platform.py +++ b/backend/models/platform.py @@ -1,7 +1,7 @@ from sqlalchemy import Column, String, Integer from config import DEFAULT_PATH_COVER_S -from models.base import BaseModel +from .base import BaseModel class Platform(BaseModel): diff --git a/backend/models/rom.py b/backend/models/rom.py index 794a0360a..b39d4d571 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -1,7 +1,7 @@ from sqlalchemy import Integer, Column, String, Text, Boolean, Float, JSON from config import DEFAULT_PATH_COVER_S, DEFAULT_PATH_COVER_L, FRONT_LIBRARY_PATH -from models.base import BaseModel +from .base import BaseModel class Rom(BaseModel): __tablename__ = "roms" diff --git a/backend/models/tests/conftest.py b/backend/models/tests/conftest.py index b7a8bb5fa..d3edb5312 100644 --- a/backend/models/tests/conftest.py +++ b/backend/models/tests/conftest.py @@ -1 +1 @@ -from handler.tests.conftest import rom, platform +from handler.tests.conftest import setup_database, clear_database, rom, platform, admin_user, editor_user, viewer_user # noqa diff --git a/backend/models/tests/test_rom.py b/backend/models/tests/test_rom.py index 1ca1c031d..a34a23d15 100644 --- a/backend/models/tests/test_rom.py +++ b/backend/models/tests/test_rom.py @@ -1,5 +1,3 @@ -from models.rom import Rom - def test_rom(rom): assert rom.file_path == "test_platform_slug/roms" assert rom.full_path == "test_platform_slug/roms/test_rom" diff --git a/backend/models/tests/test_user.py b/backend/models/tests/test_user.py new file mode 100644 index 000000000..a92f593a9 --- /dev/null +++ b/backend/models/tests/test_user.py @@ -0,0 +1,10 @@ +from utils.oauth import DEFAULT_SCOPES, WRITE_SCOPES, FULL_SCOPES + +def test_admin(admin_user): + admin_user.oauth_scopes == FULL_SCOPES + +def test_editor(editor_user): + editor_user.oauth_scopes == WRITE_SCOPES + +def test_user(viewer_user): + viewer_user.oauth_scopes == DEFAULT_SCOPES diff --git a/backend/models/user.py b/backend/models/user.py new file mode 100644 index 000000000..3d3cdcd55 --- /dev/null +++ b/backend/models/user.py @@ -0,0 +1,32 @@ +import enum +from sqlalchemy import Column, String, Boolean, Integer, Enum +from starlette.authentication import SimpleUser + +from .base import BaseModel +from utils.oauth import DEFAULT_SCOPES, WRITE_SCOPES, FULL_SCOPES + + +class Role(enum.Enum): + VIEWER = "viewer" + EDITOR = "editor" + ADMIN = "admin" + + +class User(BaseModel, SimpleUser): + __tablename__ = "users" + id = Column(Integer(), primary_key=True, autoincrement=True) + username: str = Column(String(length=255), unique=True, index=True) + hashed_password: str = Column(String(length=255)) + enabled: bool = Column(Boolean(), default=True) + role: Role = Column(Enum(Role), default=Role.VIEWER) + avatar_path: str = Column(String(length=255), default="") + + @property + def oauth_scopes(self): + if self.role == Role.ADMIN: + return FULL_SCOPES + + if self.role == Role.EDITOR: + return WRITE_SCOPES + + return DEFAULT_SCOPES diff --git a/backend/utils/auth.py b/backend/utils/auth.py new file mode 100644 index 000000000..8b14e3ede --- /dev/null +++ b/backend/utils/auth.py @@ -0,0 +1,154 @@ +from sqlalchemy.exc import IntegrityError +from fastapi import HTTPException, status, Request +from fastapi.security.http import HTTPBasic +from passlib.context import CryptContext +from starlette.requests import HTTPConnection +from starlette_csrf.middleware import CSRFMiddleware +from starlette.types import Receive, Scope, Send +from starlette.authentication import ( + AuthCredentials, + AuthenticationBackend, +) + +from handler import dbh +from utils.cache import cache +from models.user import User, Role +from config import ( + ROMM_AUTH_ENABLED, + ROMM_AUTH_USERNAME, + ROMM_AUTH_PASSWORD, +) + +from .oauth import ( + FULL_SCOPES, + get_current_active_user_from_bearer_token, +) + + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def verify_password(plain_password, hashed_password): + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password): + return pwd_context.hash(password) + + +def authenticate_user(username: str, password: str): + user = dbh.get_user_by_username(username) + if not user: + return None + + if not verify_password(password, user.hashed_password): + return None + + return user + + +def clear_session(req: HTTPConnection | Request): + session_id = req.session.get("session_id") + if session_id: + cache.delete(f"romm:{session_id}") # type: ignore[attr-defined] + req.session["session_id"] = None + + +async def get_current_active_user_from_session(conn: HTTPConnection): + # Check if session key already stored in cache + session_id = conn.session.get("session_id") + if not session_id: + return None + + username = cache.get(f"romm:{session_id}") # type: ignore[attr-defined] + if not username: + return None + + # Key exists therefore user is probably authenticated + user = dbh.get_user_by_username(username) + if user is None: + clear_session(conn) + + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User not found", + ) + + if not user.enabled: + clear_session(conn) + + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) + + return user + + +def create_default_admin_user(): + if not ROMM_AUTH_ENABLED: + return + + try: + dbh.add_user( + User( + username=ROMM_AUTH_USERNAME, + hashed_password=get_password_hash(ROMM_AUTH_PASSWORD), + role=Role.ADMIN, + ) + ) + except IntegrityError: + pass + + +class HybridAuthBackend(AuthenticationBackend): + async def authenticate(self, conn: HTTPConnection): + if not ROMM_AUTH_ENABLED: + return (AuthCredentials(FULL_SCOPES), None) + + # Check if session key already stored in cache + user = await get_current_active_user_from_session(conn) + if user: + return (AuthCredentials(user.oauth_scopes), user) + + # Check if Authorization header exists + if "Authorization" not in conn.headers: + return (AuthCredentials([]), None) + + scheme, token = conn.headers["Authorization"].split() + + # Check if basic auth header is valid + if scheme.lower() == "basic": + credentials = await HTTPBasic().__call__(conn) # type: ignore[arg-type] + if not credentials: + return (AuthCredentials([]), None) + + user = authenticate_user(credentials.username, credentials.password) + if user is None: + return (AuthCredentials([]), None) + + return (AuthCredentials(user.oauth_scopes), user) + + # Check if bearer auth header is valid + if scheme.lower() == "bearer": + user, payload = await get_current_active_user_from_bearer_token(token) + + # Only access tokens can request resources + if payload.get("type") != "access": + return (AuthCredentials([]), None) + + # Only grant access to resources with overlapping scopes + token_scopes = set(list(payload.get("scopes").split(" "))) + overlapping_scopes = list(token_scopes & set(user.oauth_scopes)) + + return (AuthCredentials(overlapping_scopes), user) + + return (AuthCredentials([]), None) + + +class CustomCSRFMiddleware(CSRFMiddleware): + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + await super().__call__(scope, receive, send) diff --git a/backend/utils/fastapi.py b/backend/utils/fastapi.py index e0ebe19ec..20c79a737 100644 --- a/backend/utils/fastapi.py +++ b/backend/utils/fastapi.py @@ -4,8 +4,7 @@ from typing import Any from handler import igdbh from utils import fs, parse_tags, get_file_extension, get_file_name_with_no_tags from config.config_loader import config -from models.platform import Platform -from models.rom import Rom +from models import Platform, Rom from logger.logger import log diff --git a/backend/utils/fs.py b/backend/utils/fs.py index 7e0e1eec1..4680166b8 100644 --- a/backend/utils/fs.py +++ b/backend/utils/fs.py @@ -14,7 +14,7 @@ from config import ( DEFAULT_PATH_COVER_S, ) from config.config_loader import config -from utils.exceptions import ( +from exceptions.fs_exceptions import ( PlatformsNotFoundException, RomsNotFoundException, RomNotFoundError, @@ -300,3 +300,10 @@ def remove_rom(p_slug: str, file_name: str): shutil.rmtree(f"{LIBRARY_BASE_PATH}/{rom_path}/{file_name}") except FileNotFoundError as exc: raise RomNotFoundError(file_name, p_slug) from exc + + +# ========= Users utils ========= +def build_avatar_path(avatar_path, username): + avatar_user_path = f"{RESOURCES_BASE_PATH}/users/{username}" + Path(avatar_user_path).mkdir(parents=True, exist_ok=True) + return f"users/{username}/{avatar_path}", avatar_user_path diff --git a/backend/utils/oauth.py b/backend/utils/oauth.py new file mode 100644 index 000000000..14cb66b21 --- /dev/null +++ b/backend/utils/oauth.py @@ -0,0 +1,132 @@ +from datetime import datetime, timedelta +from typing import Optional, Final, Any +from jose import JWTError, jwt +from fastapi import HTTPException, status, Security +from fastapi.param_functions import Form +from fastapi.security.oauth2 import OAuth2PasswordBearer +from fastapi.security.http import HTTPBasic +from fastapi.types import DecoratedCallable +from starlette.authentication import requires + +from config import ROMM_AUTH_SECRET_KEY + +ALGORITHM: Final = "HS256" +DEFAULT_OAUTH_TOKEN_EXPIRY: Final = 15 + +DEFAULT_SCOPES_MAP: Final = { + "me.read": "View your profile", + "me.write": "Modify your profile", + "roms.read": "View ROMs", + "platforms.read": "View platforms", +} + +WRITE_SCOPES_MAP: Final = { + "roms.write": "Modify ROMs", + "platforms.write": "Modify platforms", +} + +FULL_SCOPES_MAP: Final = { + "users.read": "View users", + "users.write": "Modify users", +} + +DEFAULT_SCOPES: Final = list(DEFAULT_SCOPES_MAP.keys()) +WRITE_SCOPES: Final = DEFAULT_SCOPES + list(WRITE_SCOPES_MAP.keys()) +FULL_SCOPES: Final = WRITE_SCOPES + list(FULL_SCOPES_MAP.keys()) + +credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, +) + + +def create_oauth_token(data: dict, expires_delta: timedelta | None = None): + to_encode = data.copy() + + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=DEFAULT_OAUTH_TOKEN_EXPIRY) + + to_encode.update({"exp": expire}) + + return jwt.encode(to_encode, ROMM_AUTH_SECRET_KEY, algorithm=ALGORITHM) + + +async def get_current_active_user_from_bearer_token(token: str): + from handler import dbh + + try: + payload = jwt.decode(token, ROMM_AUTH_SECRET_KEY, algorithms=[ALGORITHM]) + except JWTError: + raise credentials_exception + + username = payload.get("sub") + if username is None: + raise credentials_exception + + user = dbh.get_user_by_username(username) + if user is None: + raise credentials_exception + + if not user.enabled: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user" + ) + + return user, payload + + +class OAuth2RequestForm: + def __init__( + self, + grant_type: str = Form(default="password"), + scope: str = Form(default=""), + username: Optional[str] = Form(default=None), + password: Optional[str] = Form(default=None), + client_id: Optional[str] = Form(default=None), + client_secret: Optional[str] = Form(default=None), + refresh_token: Optional[str] = Form(default=None), + ): + self.grant_type = grant_type + self.scopes = scope.split() + self.username = username + self.password = password + self.client_id = client_id + self.client_secret = client_secret + self.refresh_token = refresh_token + + +oauth2_password_bearer = OAuth2PasswordBearer( + tokenUrl="/token", + auto_error=False, + scopes={ + **DEFAULT_SCOPES_MAP, + **WRITE_SCOPES_MAP, + **FULL_SCOPES_MAP, + }, +) + + +def protected_route( + method: Any, + path: str, + scopes: list[str] = [], + **kwargs, +): + def decorator(func: DecoratedCallable): + fn = requires(scopes)(func) + return method( + path, + dependencies=[ + Security( + dependency=oauth2_password_bearer, + scopes=scopes, + ), + Security(dependency=HTTPBasic(auto_error=False)), + ], + **kwargs, + )(fn) + + return decorator diff --git a/backend/utils/tests/conftest.py b/backend/utils/tests/conftest.py new file mode 100644 index 000000000..110624c06 --- /dev/null +++ b/backend/utils/tests/conftest.py @@ -0,0 +1 @@ +from handler.tests.conftest import setup_database, clear_database, admin_user, editor_user, viewer_user, clear_database # noqa diff --git a/backend/utils/tests/test_auth.py b/backend/utils/tests/test_auth.py new file mode 100644 index 000000000..5e4746185 --- /dev/null +++ b/backend/utils/tests/test_auth.py @@ -0,0 +1,275 @@ +import pytest +from base64 import b64encode +from fastapi.exceptions import HTTPException + +from models import User +from handler import dbh +from ..auth import ( + verify_password, + get_password_hash, + authenticate_user, + get_current_active_user_from_session, + create_default_admin_user, + HybridAuthBackend, +) +from ..oauth import WRITE_SCOPES, create_oauth_token +from ..cache import cache + + +def test_verify_password(): + assert verify_password("password", get_password_hash("password")) + assert not verify_password("password", get_password_hash("notpassword")) + + +def test_authenticate_user(admin_user): + current_user = authenticate_user("test_admin", "test_admin_password") + + assert current_user + assert current_user.id == admin_user.id + + +async def test_get_current_active_user_from_session(editor_user): + session_id = "test_session_id" + cache.set(f"romm:{session_id}", editor_user.username) + + class MockConnection: + def __init__(self): + self.session = {"session_id": session_id} + + conn = MockConnection() + current_user = await get_current_active_user_from_session(conn) + + assert current_user + assert isinstance(current_user, User) + assert current_user.id == editor_user.id + + +async def test_get_current_active_user_from_session_bad_session_key(editor_user): + cache.set("romm:test_session_id", editor_user.username) + + class MockConnection: + def __init__(self): + self.session = {"session_id": "not_real_test_session_id"} + self.headers = {} + + conn = MockConnection() + current_user = await get_current_active_user_from_session(conn) + + assert not current_user + + +async def test_get_current_active_user_from_session_bad_username(editor_user): + session_id = "test_session_id" + cache.set(f"romm:{session_id}", "not_real_username") + + class MockConnection: + def __init__(self): + self.session = {"session_id": session_id} + self.headers = {} + + conn = MockConnection() + + try: + await get_current_active_user_from_session(conn) + except HTTPException as e: + assert e.status_code == 403 + assert e.detail == "User not found" + + +async def test_get_current_active_user_from_session_disabled_user(editor_user): + session_id = "test_session_id" + cache.set(f"romm:{session_id}", editor_user.username) + + class MockConnection: + def __init__(self): + self.session = {"session_id": session_id} + self.headers = {} + + conn = MockConnection() + + dbh.update_user(editor_user.id, {"enabled": False}) + + try: + await 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(): + create_default_admin_user() + + user = dbh.get_user_by_username("test_admin") + assert user.username == "test_admin" + assert verify_password("test_admin_password", user.hashed_password) + + users = dbh.get_users() + assert len(users) == 1 + + create_default_admin_user() + + users = dbh.get_users() + assert len(users) == 1 + + +async def test_hybrid_auth_backend_session(editor_user): + session_id = "test_session_id" + cache.set(f"romm:{session_id}", editor_user.username) + + class MockConnection: + def __init__(self): + self.session = {"session_id": session_id} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert user.id == editor_user.id + assert creds.scopes == editor_user.oauth_scopes + assert creds.scopes == WRITE_SCOPES + + +async def test_hybrid_auth_backend_empty_session_and_headers(editor_user): + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert not user + assert creds.scopes == [] + + +async def test_hybrid_auth_backend_bearer_auth_header(editor_user): + access_token = create_oauth_token( + data={ + "sub": editor_user.username, + "scopes": " ".join(editor_user.oauth_scopes), + "type": "access", + }, + ) + + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": f"Bearer {access_token}"} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert user.id == editor_user.id + assert set(creds.scopes).issubset(editor_user.oauth_scopes) + + +async def test_hybrid_auth_backend_bearer_invalid_token(editor_user): + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": "Bearer invalid_token"} + + backend = HybridAuthBackend() + conn = MockConnection() + + with pytest.raises(HTTPException): + await backend.authenticate(conn) + + +async def test_hybrid_auth_backend_basic_auth_header(editor_user): + token = b64encode("test_editor:test_editor_password".encode()).decode() + + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": f"Basic {token}"} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert user.id == editor_user.id + assert creds.scopes == WRITE_SCOPES + assert set(creds.scopes).issubset(editor_user.oauth_scopes) + + +async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user): + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": "Basic test_editor:test_editor_password"} + + backend = HybridAuthBackend() + conn = MockConnection() + + with pytest.raises(HTTPException): + await backend.authenticate(conn) + + +async def test_hybrid_auth_backend_invalid_scheme(): + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": "Some invalid_scheme"} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert not user + assert creds.scopes == [] + + +async def test_hybrid_auth_backend_with_refresh_token(editor_user): + refresh_token = create_oauth_token( + data={ + "sub": editor_user.username, + "scopes": " ".join(editor_user.oauth_scopes), + "type": "refresh", + }, + ) + + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": f"Bearer {refresh_token}"} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert not user + assert creds.scopes == [] + + +async def test_hybrid_auth_backend_scope_subset(editor_user): + scopes = editor_user.oauth_scopes[:3] + access_token = create_oauth_token( + data={ + "sub": editor_user.username, + "scopes": " ".join(scopes), + "type": "access", + }, + ) + + class MockConnection: + def __init__(self): + self.session = {} + self.headers = {"Authorization": f"Bearer {access_token}"} + + backend = HybridAuthBackend() + conn = MockConnection() + + creds, user = await backend.authenticate(conn) + + assert user.id == editor_user.id + assert set(creds.scopes).issubset(editor_user.oauth_scopes) + assert set(creds.scopes).issubset(scopes) diff --git a/backend/utils/tests/test_fastapi.py b/backend/utils/tests/test_fastapi.py index 613c1efd3..1e78d9754 100644 --- a/backend/utils/tests/test_fastapi.py +++ b/backend/utils/tests/test_fastapi.py @@ -1,9 +1,8 @@ import pytest -from utils.fastapi import scan_platform, scan_rom -from utils.exceptions import RomsNotFoundException -from models.platform import Platform -from models.rom import Rom +from ..fastapi import scan_platform, scan_rom +from exceptions.fs_exceptions import RomsNotFoundException +from models import Platform, Rom @pytest.mark.vcr() diff --git a/backend/utils/tests/test_fs.py b/backend/utils/tests/test_fs.py index 2ea0ee261..31ac8c8d3 100644 --- a/backend/utils/tests/test_fs.py +++ b/backend/utils/tests/test_fs.py @@ -1,6 +1,6 @@ import pytest -from utils.fs import ( +from ..fs import ( get_cover, get_platforms, get_roms_structure, diff --git a/backend/utils/tests/test_oauth.py b/backend/utils/tests/test_oauth.py new file mode 100644 index 000000000..593536462 --- /dev/null +++ b/backend/utils/tests/test_oauth.py @@ -0,0 +1,74 @@ +import pytest +from fastapi import APIRouter, Request +from fastapi.exceptions import HTTPException + +from handler import dbh +from ..oauth import ( + create_oauth_token, + get_current_active_user_from_bearer_token, + protected_route, +) + + +def test_create_oauth_token(): + token = create_oauth_token({"sub": "test_user"}) + + assert isinstance(token, str) + + +async def test_get_current_active_user_from_bearer_token(admin_user): + token = create_oauth_token( + { + "sub": admin_user.username, + "scopes": " ".join(admin_user.oauth_scopes), + "type": "access", + }, + ) + user, payload = await get_current_active_user_from_bearer_token(token) + + assert user.id == admin_user.id + assert payload["sub"] == admin_user.username + assert set(payload["scopes"].split()).issubset(admin_user.oauth_scopes) + assert payload["type"] == "access" + + +async def test_get_current_active_user_from_bearer_token_invalid_token(): + with pytest.raises(HTTPException): + await get_current_active_user_from_bearer_token("invalid_token") + + +async def test_get_current_active_user_from_bearer_token_invalid_user(): + token = create_oauth_token({"sub": "invalid_user"}) + + with pytest.raises(HTTPException): + await get_current_active_user_from_bearer_token(token) + + +async def test_get_current_active_user_from_bearer_token_disabled_user(admin_user): + token = create_oauth_token( + { + "sub": admin_user.username, + "scopes": " ".join(admin_user.oauth_scopes), + "type": "access", + }, + ) + + dbh.update_user(admin_user.id, {"enabled": False}) + + try: + await get_current_active_user_from_bearer_token(token) + except HTTPException as e: + assert e.status_code == 401 + assert e.detail == "Inactive user" + + +def test_protected_route(): + router = APIRouter() + + @protected_route(router.get, "/test") + def test_route(request: Request): + return {"test": "test"} + + req = Request({"type": "http", "method": "GET", "url": "/test"}) + + assert test_route(req) == {"test": "test"} diff --git a/backend/worker.py b/backend/worker.py index 5fc4b08c2..a7c6f5a56 100755 --- a/backend/worker.py +++ b/backend/worker.py @@ -1,13 +1,14 @@ import sys from rq import Worker, Queue, Connection +from config import ENABLE_EXPERIMENTAL_REDIS from utils.cache import redis_client, redis_connectable listen = ["high", "default", "low"] if __name__ == "__main__": # Exit if Redis is not connectable - if not redis_connectable: + if not redis_connectable or not ENABLE_EXPERIMENTAL_REDIS: sys.exit(0) with Connection(redis_client): diff --git a/docker-compose.yml b/docker-compose.yml index cf156cea9..fadac7b25 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,9 +12,9 @@ services: ports: - $DB_PORT:3306 - # redis: - # image: redis:alpine - # container_name: redis - # restart: unless-stopped - # ports: - # - ${REDIS_PORT}:6379 + redis: + image: redis:alpine + container_name: redis + restart: unless-stopped + ports: + - ${REDIS_PORT}:6379 diff --git a/docker/Dockerfile b/docker/Dockerfile index 1e8bb70ea..ac18020c6 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -9,6 +9,7 @@ RUN npm run build FROM ubuntu/nginx:1.18-22.04_edge as production-stage ARG WEBSERVER_FOLDER=/var/www/html COPY --from=front-build-stage /front/dist ${WEBSERVER_FOLDER} +COPY ./frontend/assets/default_avatar.png ${WEBSERVER_FOLDER}/assets/ COPY ./frontend/assets/platforms ${WEBSERVER_FOLDER}/assets/platforms RUN mkdir -p ${WEBSERVER_FOLDER}/assets/romm && \ ln -s /romm/library ${WEBSERVER_FOLDER}/assets/romm/library && \ diff --git a/docker/build_local_image.sh b/docker/build_local_image.sh index fb96ec6d4..01febc767 100755 --- a/docker/build_local_image.sh +++ b/docker/build_local_image.sh @@ -1,6 +1,6 @@ #!/bin/bash -VERSION=$(cat .romm-version) +VERSION="2.0.0" branch_name="$(git symbolic-ref HEAD 2>/dev/null)" branch_name=${branch_name##refs/heads/} docker build -t zurdi15/romm:local-${VERSION}-${branch_name} . --file ./docker/Dockerfile diff --git a/docker/init_scripts/init b/docker/init_scripts/init index 1777c7e4c..72ab16956 100755 --- a/docker/init_scripts/init +++ b/docker/init_scripts/init @@ -7,7 +7,7 @@ /init_front & # Start rq worker -# /init_worker & +/init_worker & # Wait for any process to exit wait -n diff --git a/docker/init_scripts/init_worker b/docker/init_scripts/init_worker index 478b86426..e1e967189 100755 --- a/docker/init_scripts/init_worker +++ b/docker/init_scripts/init_worker @@ -1,4 +1,4 @@ #!/bin/bash cd /back -nc -z ${REDIS_HOST:-localhost} ${REDIS_PORT:-6379} && rq worker high default low --logging_level WARN +[[ ${ENABLE_EXPERIMENTAL_REDIS} == "true" ]] && rq worker high default low --logging_level WARN || sleep infinity diff --git a/docker/nginx/default.conf b/docker/nginx/default.conf index 95b3c34e2..ddf072336 100644 --- a/docker/nginx/default.conf +++ b/docker/nginx/default.conf @@ -42,10 +42,15 @@ http { proxy_redirect off; } + # OpenAPI for swagger and redoc + location /openapi.json { + proxy_pass http://localhost:5000; + } + # Backend api calls location /api { rewrite /api/(.*) /$1 break; - proxy_pass http://localhost:5000/; + proxy_pass http://localhost:5000; } location /ws { proxy_pass http://localhost:5000; @@ -54,4 +59,4 @@ http { proxy_set_header Connection "upgrade"; } } -} \ No newline at end of file +} diff --git a/env.template b/env.template index d96c71b7e..11fb92e74 100644 --- a/env.template +++ b/env.template @@ -1,11 +1,11 @@ ROMM_BASE_PATH=/path/to/romm_mock VITE_BACKEND_DEV_PORT=5000 -# IGDB auth +# IGDB credentials CLIENT_ID= CLIENT_SECRET= -# STEAMGRIDDB API KEY +# STEAMGRIDDB API key STEAMGRIDDB_API_KEY= # Database driver (mariadb, sqlite) @@ -22,3 +22,9 @@ DB_ROOT_PASSWD= # Redis config (optional) REDIS_HOST=127.0.0.1 REDIS_PORT=6379 + +# Authentication +ROMM_AUTH_SECRET_KEY= +ROMM_AUTH_ENABLED=true +ROMM_AUTH_USERNAME=admin +ROMM_AUTH_PASSWORD=admin diff --git a/examples/docker-compose.example.yml b/examples/docker-compose.example.yml index 0b26ebf40..28027cc71 100644 --- a/examples/docker-compose.example.yml +++ b/examples/docker-compose.example.yml @@ -1,4 +1,4 @@ -version: '3' +version: "3" volumes: mysql_data: services: @@ -6,30 +6,40 @@ services: image: zurdi15/romm:latest container_name: romm environment: - - ROMM_DB_DRIVER=mariadb # This variable can be set as: mariadb | sqlite. If it is not defined, sqlite will be the database by default - - DB_HOST=mariadb # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - - DB_PORT=3306 # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - - DB_USER=romm-user # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - - DB_NAME=romm # [Optional] Only needed if ROMM_DB_DRIVER=mariadb. Can be optionally changed, and should match the MYSQL_DATABASE value in the mariadb container. - - DB_PASSWD= # [Optional] Only needed if ROMM_DB_DRIVER=mariadb - # - REDIS_HOST=redis # [Optional][Experimental] Redis enables workers to run long tasks, like full library rescans, without having to wait on the main thread. Can be used with an already existent redis container - # - REDIS_PORT=6379 # [Optional][Experimental] + - ROMM_DB_DRIVER=mariadb # mariadb | sqlite (default: sqlite) + # [Optional] Only required if using MariaDB as the database + - DB_HOST=mariadb + - DB_PORT=3306 + - DB_USER=romm-user + - DB_NAME=romm # Should match the MYSQL_DATABASE value in the mariadb container + - DB_PASSWD= + # [Optional] Used to fetch metadata from IGDB - CLIENT_ID= - CLIENT_SECRET= - - STEAMGRIDDB_API_KEY= # [Optional] + # [Optional] Use SteamGridDB as a source for covers + - STEAMGRIDDB_API_KEY= + # [Optional] Will enable user management and require authentication to access the interface (default to false) + - ROMM_AUTH_ENABLED=true # default: false + - ROMM_AUTH_SECRET_KEY= # Generate a key with `openssl rand -hex 32` + - ROMM_AUTH_USERNAME=admin # default: admin + - ROMM_AUTH_PASSWORD= # default: admin + # [Optional] Only required if authentication is enabled + - ENABLE_EXPERIMENTAL_REDIS=true # default: false + - REDIS_HOST=redis # default: localhost + - REDIS_PORT=6379 # default: 6379 volumes: - - '/path/to/library:/romm/library' - - '/path/to/resources:/romm/resources' # [Optional] Path where roms metadata (covers) are stored - - '/path/to/config.yml:/romm/config.yml' # [Optional] Path where config is stored - - '/path/to/database:/romm/database' # [Optional] Only needed if ROMM_DB_DRIVER=sqlite or ROMM_DB_DRIVER not exists - - '/path/to/logs:/romm/logs' # [Optional] Path where RomM logs are stored + - "/path/to/library:/romm/library" + - "/path/to/resources:/romm/resources" # [Optional] Path where roms metadata (covers) are stored + - "/path/to/config.yml:/romm/config.yml" # [Optional] Path where config is stored + - "/path/to/database:/romm/database" # [Optional] Only needed if ROMM_DB_DRIVER=sqlite or not set + - "/path/to/logs:/romm/logs" # [Optional] Path where logs are stored ports: - 80:80 depends_on: - romm_db restart: "unless-stopped" - # [Optional] Only needed if ROMM_DB_DRIVER=mariadb + # [Optional] Only required if using MariaDB as the database mariadb: image: mariadb:latest container_name: mariadb @@ -39,15 +49,15 @@ services: - MYSQL_USER=romm-user - MYSQL_PASSWORD=change-me volumes: - - mysql_data:/var/lib/mysql # Can also be mounted locally if preferred + - mysql_data:/var/lib/mysql # Can also be mounted locally ports: - 3306:3306 restart: "unless-stopped" - # [Optional][Experimental] - # redis: - # image: redis:alpine - # container_name: redis - # restart: unless-stopped - # ports: - # - 6379:6379 + # [Optional] Only required if experimental Redis is enabled + redis: + image: redis:alpine + container_name: redis + restart: unless-stopped + ports: + - 6379:6379 diff --git a/frontend/assets/default_avatar.png b/frontend/assets/default_avatar.png new file mode 100644 index 000000000..9c5790b13 Binary files /dev/null and b/frontend/assets/default_avatar.png differ diff --git a/frontend/assets/login_bg.png b/frontend/assets/login_bg.png new file mode 100644 index 000000000..922b90a6d Binary files /dev/null and b/frontend/assets/login_bg.png differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index cf78cae3c..abda9fdf7 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,17 +1,18 @@ { "name": "romm", - "version": "1.10", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "romm", - "version": "1.9.2", + "version": "2.0.0", "dependencies": { "@mdi/font": "7.0.96", "axios": "^1.3.4", "core-js": "^3.8.3", "file-saver": "^2.0.5", + "js-cookie": "^3.0.5", "jszip": "^3.10.1", "lodash": "^4.17.21", "mitt": "^3.0.0", @@ -4464,6 +4465,14 @@ "node": ">= 10.13.0" } }, + "node_modules/js-cookie": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz", + "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==", + "engines": { + "node": ">=14" + } + }, "node_modules/js-sdsl": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index f1113e27e..b9d84fead 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "romm", - "version": "1.10", + "version": "2.0.0", "private": true, "scripts": { "dev": "vite --host", @@ -13,6 +13,7 @@ "axios": "^1.3.4", "core-js": "^3.8.3", "file-saver": "^2.0.5", + "js-cookie": "^3.0.5", "jszip": "^3.10.1", "lodash": "^4.17.21", "mitt": "^3.0.0", diff --git a/frontend/src/App.vue b/frontend/src/App.vue index c95f21f2c..67de1337b 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,81 +1,35 @@ - - - - - - - - - - - + + diff --git a/frontend/src/components/AdminMenu/Base.vue b/frontend/src/components/AdminMenu/Base.vue index 49bec7d05..6da881c9f 100644 --- a/frontend/src/components/AdminMenu/Base.vue +++ b/frontend/src/components/AdminMenu/Base.vue @@ -8,8 +8,8 @@ const emitter = inject("emitter"); Search @@ -18,8 +18,8 @@ const emitter = inject("emitter"); Edit Delete -import storeScanning from "@/stores/scanning.js"; +import storeScanning from "@/stores/scanning"; import DrawerToggle from "@/components/AppBar/DrawerToggle.vue"; // Props @@ -9,7 +9,7 @@ const scanning = storeScanning(); { - + + + + + diff --git a/frontend/src/components/Dialog/DeleteRom.vue b/frontend/src/components/Dialog/Rom/DeleteRom.vue similarity index 57% rename from frontend/src/components/Dialog/DeleteRom.vue rename to frontend/src/components/Dialog/Rom/DeleteRom.vue index c33096379..b541f1d49 100644 --- a/frontend/src/components/Dialog/DeleteRom.vue +++ b/frontend/src/components/Dialog/Rom/DeleteRom.vue @@ -2,28 +2,31 @@ import { ref, inject } from "vue"; import { useRouter } from "vue-router"; import { useDisplay } from "vuetify"; -import { deleteRomApi } from "@/services/api.js"; +import { deleteRomsApi } from "@/services/api"; +import romsStore from "@/stores/roms"; const { xs, mdAndDown, lgAndUp } = useDisplay(); const router = useRouter(); const show = ref(false); -const rom = ref(); +const storeRoms = romsStore(); +const roms = ref(); const deleteFromFs = ref(false); const emitter = inject("emitter"); -emitter.on("showDeleteDialog", (romToDelete) => { - rom.value = romToDelete; +emitter.on("showDeleteRomDialog", (romsToDelete) => { + roms.value = romsToDelete; show.value = true; }); -async function deleteRom() { - await deleteRomApi(rom.value, deleteFromFs.value) +async function deleteRoms() { + await deleteRomsApi(roms.value, deleteFromFs.value) .then((response) => { emitter.emit("snackbarShow", { msg: response.data.msg, icon: "mdi-check-bold", color: "green", }); + storeRoms.reset(); }) .catch((error) => { console.log(error); @@ -34,9 +37,12 @@ async function deleteRom() { }); return; }); - await router.push(`/platform/${rom.value.p_slug}`); - emitter.emit("refreshGallery"); - emitter.emit("refreshPlatforms"); + await router.push({ + name: "platform", + params: { platform: roms.value[0].p_slug }, + }); + emitter.emit("refreshView"); + emitter.emit("refreshDrawer"); show.value = false; } @@ -58,7 +64,7 @@ async function deleteRom() { 'delete-content-mobile': xs, }" > - + @@ -66,7 +72,7 @@ async function deleteRom() { - - + - Deleting {{ rom.file_name }}. Do you confirm? + Deleting the following + {{ roms.length }} + games. Do you confirm? + + - Cancel - Confirm + + {{ rom.r_name }} - [{{ + rom.file_name + }}] + + + + + + Cancel + Confirm - + .delete-content { width: 900px; + max-height: 600px; } .delete-content-tablet { width: 570px; + max-height: 600px; } .delete-content-mobile { width: 85vw; + max-height: 600px; +} +.scroll { + overflow-y: scroll; } diff --git a/frontend/src/components/Dialog/EditRom.vue b/frontend/src/components/Dialog/Rom/EditRom.vue similarity index 85% rename from frontend/src/components/Dialog/EditRom.vue rename to frontend/src/components/Dialog/Rom/EditRom.vue index 473addd21..813d54ea3 100644 --- a/frontend/src/components/Dialog/EditRom.vue +++ b/frontend/src/components/Dialog/Rom/EditRom.vue @@ -1,7 +1,7 @@ @@ -85,26 +86,57 @@ onBeforeUnmount(() => { }" rounded="0" > - + - + + - IGDB - + + + + + IGDB + + + + + + + + + @@ -113,6 +145,7 @@ onBeforeUnmount(() => { { { { - + { @@ -199,7 +233,8 @@ onBeforeUnmount(() => { - + + +import { ref, inject } from "vue"; + +import { createUserApi } from "@/services/api"; + +const user = ref({ + username: "", + password: "", + role: "viewer", +}); +const show = ref(false); + +const emitter = inject("emitter"); +emitter.on("showCreateUserDialog", () => { + show.value = true; +}); + +async function createUser() { + await createUserApi(user.value).catch(({ response, message }) => { + emitter.emit("snackbarShow", { + msg: `Unable to create user: ${ + response?.data?.detail || response?.statusText || message + }`, + icon: "mdi-close-circle", + color: "red", + }); + }); + show.value = false; + emitter.emit("refreshView"); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cancel + + Create + + + + + + diff --git a/frontend/src/components/Dialog/User/DeleteUser.vue b/frontend/src/components/Dialog/User/DeleteUser.vue new file mode 100644 index 000000000..a328f998f --- /dev/null +++ b/frontend/src/components/Dialog/User/DeleteUser.vue @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + Deleting{{ user.username }}.Do you confirm? + + + Cancel + Confirm + + + + + diff --git a/frontend/src/components/Dialog/User/EditUser.vue b/frontend/src/components/Dialog/User/EditUser.vue new file mode 100644 index 000000000..5304f74b4 --- /dev/null +++ b/frontend/src/components/Dialog/User/EditUser.vue @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cancel + Apply + + + + + diff --git a/frontend/src/components/Drawer/Base.vue b/frontend/src/components/Drawer/Base.vue index d28003fe2..d3b93a246 100644 --- a/frontend/src/components/Drawer/Base.vue +++ b/frontend/src/components/Drawer/Base.vue @@ -1,11 +1,14 @@ + + + + + {{ auth.user?.username }} + {{ auth.user?.role }} + + + + + + + + + + + + diff --git a/frontend/src/components/Drawer/Header.vue b/frontend/src/components/Drawer/Header.vue new file mode 100644 index 000000000..785e1aafe --- /dev/null +++ b/frontend/src/components/Drawer/Header.vue @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/components/Drawer/RailBtn.vue b/frontend/src/components/Drawer/RailBtn.vue index 664059fe9..7a930cea1 100644 --- a/frontend/src/components/Drawer/RailBtn.vue +++ b/frontend/src/components/Drawer/RailBtn.vue @@ -11,8 +11,8 @@ const emitter = inject("emitter"); mdi-arrow-collapse-right diff --git a/frontend/src/components/FabMenu/Base.vue b/frontend/src/components/FabMenu/Base.vue new file mode 100644 index 000000000..49e118eb0 --- /dev/null +++ b/frontend/src/components/FabMenu/Base.vue @@ -0,0 +1,122 @@ + + + + + + + mdi-magnify-scan + + + + mdi-download + + + + mdi-delete + + diff --git a/frontend/src/components/GalleryAppBar/FilterBar.vue b/frontend/src/components/GalleryAppBar/FilterBar.vue index 810865036..f5ddd8e14 100644 --- a/frontend/src/components/GalleryAppBar/FilterBar.vue +++ b/frontend/src/components/GalleryAppBar/FilterBar.vue @@ -1,7 +1,7 @@ @@ -48,6 +50,7 @@ const downloadUrl = `${window.location.origin}${props.rom.download_path}`; +import { ref, inject } from "vue"; +import useRomsStore from "@/stores/roms.js"; import ActionBar from "@/components/Game/Card/ActionBar.vue"; import Cover from "@/components/Game/Card/Cover.vue"; // Props -const props = defineProps(["rom"]); +const props = defineProps(["rom", "index"]); +const emit = defineEmits(["selectRom"]); +const romsStore = useRomsStore(); +const selected = ref(); + +// Functions +function selectRom(event) { + selected.value = !selected.value; + if (selected.value) { + romsStore.addSelectedRoms(props.rom); + } else { + romsStore.removeSelectedRoms(props.rom); + } + emit("selectRom", { event, index: props.index, selected: selected.value }); +} + +const emitter = inject("emitter"); +emitter.on("refreshSelected", () => { + selected.value = romsStore.selected + .map((rom) => rom.id) + .includes(props.rom.id); +}); - - - - + + - diff --git a/frontend/src/components/Game/Card/Cover.vue b/frontend/src/components/Game/Card/Cover.vue index b9b56f5a7..b289e3c26 100644 --- a/frontend/src/components/Game/Card/Cover.vue +++ b/frontend/src/components/Game/Card/Cover.vue @@ -1,63 +1,104 @@ - - - - - - - - + + + + + + + + + {{ rom.file_name }} + + + + + {{ rom.region }} + + + {{ rom.revision }} + + + {{ selected ? "mdi-circle-slice-8" : "mdi-circle-outline" }} - {{ rom.file_name }} - - - - - {{ rom.region }} - - - {{ rom.revision }} - - - + + diff --git a/frontend/src/components/Game/DataTable/Base.vue b/frontend/src/components/Game/DataTable/Base.vue new file mode 100644 index 000000000..994a89c0c --- /dev/null +++ b/frontend/src/components/Game/DataTable/Base.vue @@ -0,0 +1,151 @@ + + + + + + + + + + + + {{ item.selectable.file_size }} + {{ item.selectable.file_size_units }} + + + + mdi-download + + + mdi-download + + mdi-content-save-all + + + mdi-dots-vertical + + + + + + diff --git a/frontend/src/components/Game/ListItem/Header.vue b/frontend/src/components/Game/ListItem/Header.vue deleted file mode 100644 index 61d34b95b..000000000 --- a/frontend/src/components/Game/ListItem/Header.vue +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - Name - File - Platform - Size - Reg - Rev - - - - - - - - - - - - - - diff --git a/frontend/src/components/Game/ListItem/Item.vue b/frontend/src/components/Game/ListItem/Item.vue deleted file mode 100644 index ac2876aca..000000000 --- a/frontend/src/components/Game/ListItem/Item.vue +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - {{ rom.r_name }} - {{ rom.file_name }} - {{ rom.p_slug }} - {{ rom.file_size }} {{ rom.file_size_units }} - {{ rom.region }} - {{ rom.revision }} - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/frontend/src/components/Notification.vue b/frontend/src/components/Notification.vue index e3aa38338..0e641b484 100644 --- a/frontend/src/components/Notification.vue +++ b/frontend/src/components/Notification.vue @@ -16,14 +16,14 @@ emitter.on("snackbarShow", (snackbar) => { {{ snackbarStatus.msg }} diff --git a/frontend/src/components/Platform/PlatformCard.vue b/frontend/src/components/Platform/PlatformCard.vue index ec3aff821..837301ee9 100644 --- a/frontend/src/components/Platform/PlatformCard.vue +++ b/frontend/src/components/Platform/PlatformCard.vue @@ -9,15 +9,16 @@ const props = defineProps(["platform"]); - - {{ platform.slug }} + + {{ platform.slug }} - + - + diff --git a/frontend/src/components/Platform/PlatformListItem.vue b/frontend/src/components/Platform/PlatformListItem.vue index 0f57ddd73..499de0ba2 100644 --- a/frontend/src/components/Platform/PlatformListItem.vue +++ b/frontend/src/components/Platform/PlatformListItem.vue @@ -11,20 +11,16 @@ import PlatformIcon from "./PlatformIcon.vue"; :key="platform" class="pt-4 pb-4 bg-terciary" > - {{ - rail ? "" : platform.name - }} + {{ platform.name }} - {{ + {{ platform.n_roms }} - - diff --git a/frontend/src/main.js b/frontend/src/main.js index 873813120..f9d44ddcc 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,12 +1,20 @@ import { createApp } from "vue"; +import { createVuetify } from "vuetify"; import { registerPlugins } from "@/plugins"; - import App from "./App.vue"; // Event bus import mitt from "mitt"; const emitter = mitt(); +export default createVuetify({ + defaults: { + VBtn: { + rounded: 0, // TODO: Vuetify global configuration not working + }, + }, +}); + const app = createApp(App); registerPlugins(app); diff --git a/frontend/src/plugins/router.js b/frontend/src/plugins/router.js index 521d61cf6..9a8ba5cd9 100644 --- a/frontend/src/plugins/router.js +++ b/frontend/src/plugins/router.js @@ -2,31 +2,51 @@ import { createRouter, createWebHistory } from "vue-router"; const routes = [ + { + path: "/login", + name: "login", + component: () => import("@/views/Login.vue"), + }, { path: "/", + name: "home", component: () => import("@/views/Home.vue"), - }, - { - path: "/platform/:platform", - component: () => import("@/views/Gallery.vue"), - }, - { - path: "/platform/:platform/:rom", - component: () => import("@/views/Details.vue"), - }, - { - path: "/library/scan", - component: () => import("@/views/library/Scan.vue"), - }, - { - path: "/settings/control-panel", - component: () => import("@/views/settings/ControlPanel.vue"), + children: [ + { + path: "/", + name: "dashboard", + component: () => import("@/views/Dashboard/Base.vue"), + }, + { + path: "/platform/:platform", + name: "platform", + component: () => import("@/views/Gallery/Base.vue"), + }, + { + path: "/platform/:platform/:rom", + name: "rom", + component: () => import("@/views/Details/Base.vue"), + }, + { + path: "/library/scan", + name: "scan", + component: () => import("@/views/Library/Scan.vue"), + }, + { + path: "/settings/control-panel", + name: "controlPanel", + component: () => import("@/views/Settings/ControlPanel.vue"), + }, + { + path: "/:pathMatch(.*)*", + name: "noMatch", + component: () => import("@/views/Dashboard/Base.vue"), + }, + ], }, ]; -const router = createRouter({ +export default createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); - -export default router; diff --git a/frontend/src/plugins/vuetify.js b/frontend/src/plugins/vuetify.js index 6aab3642a..94e132ffc 100644 --- a/frontend/src/plugins/vuetify.js +++ b/frontend/src/plugins/vuetify.js @@ -7,7 +7,7 @@ // Styles import "@mdi/font/css/materialdesignicons.css"; import "vuetify/styles"; -import { rommDark, rommLight } from "@/styles/themes.js"; +import { rommDark, rommLight } from "@/styles/themes"; // Composables import { createVuetify } from "vuetify"; diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index 209c87b3a..9467a52ca 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -1,9 +1,22 @@ import axios from "axios"; -import useDownloadStore from "@/stores/download.js"; -import socket from "@/services/socket.js"; +import storeDownload from "@/stores/download"; +import socket from "@/services/socket"; +import router from "@/plugins/router"; + +export const api = axios.create({ baseURL: "/api", timeout: 120000 }); + +api.interceptors.response.use( + (response) => response, + (error) => { + if (error.response.status === 403) { + router.push(`/login?next=${router.currentRoute.value.path}`); + } + return Promise.reject(error); + } +); export async function fetchPlatformsApi() { - return axios.get("/api/platforms"); + return api.get("/platforms"); } export async function fetchRomsApi({ @@ -12,17 +25,17 @@ export async function fetchRomsApi({ size = 60, searchTerm = "", }) { - return axios.get( - `/api/platforms/${platform}/roms?cursor=${cursor}&size=${size}&search_term=${searchTerm}` + return api.get( + `/platforms/${platform}/roms?cursor=${cursor}&size=${size}&search_term=${searchTerm}` ); } export async function fetchRomApi(platform, rom) { - return axios.get(`/api/platforms/${platform}/roms/${rom}`); + return api.get(`/platforms/${platform}/roms/${rom}`); } function clearRomFromDownloads({ id }) { - const downloadStore = useDownloadStore(); + const downloadStore = storeDownload(); downloadStore.remove(id); // Disconnect socket when no more downloads are in progress @@ -46,13 +59,16 @@ export async function downloadRomApi(rom, files) { a.download = `${rom.r_name}.zip`; a.click(); - if (!socket.connected) socket.connect(); - useDownloadStore().add(rom.id); + // Only connect socket if multi-file download + if (rom.multi) { + if (!socket.connected) socket.connect(); + storeDownload().add(rom.id); - // Clear download state after 60 seconds in case error/timeout - setTimeout(() => { - clearRomFromDownloads(rom); - }, 60 * 1000); + // Clear download state after 60 seconds in case error/timeout + setTimeout(() => { + clearRomFromDownloads(rom); + }, 60 * 1000); + } } export async function updateRomApi(rom, updatedData, renameAsIGDB) { @@ -67,20 +83,70 @@ export async function updateRomApi(rom, updatedData, renameAsIGDB) { ? rom.file_name.replace(rom.file_name_no_tags, updatedData.r_name) : updatedData.file_name, }; - return axios.patch(`/api/platforms/${rom.p_slug}/roms/${rom.id}`, { + + return api.patch(`/platforms/${rom.p_slug}/roms/${rom.id}`, { updatedRom, }); } export async function deleteRomApi(rom, deleteFromFs) { - return axios.delete( - `/api/platforms/${rom.p_slug}/roms/${rom.id}?filesystem=${deleteFromFs}` + return api.delete( + `/platforms/${rom.p_slug}/roms/${rom.id}?filesystem=${deleteFromFs}` + ); +} + +export async function deleteRomsApi(roms, deleteFromFs) { + return api.post( + `/platforms/${roms[0].p_slug}/roms/delete?filesystem=${deleteFromFs}`, + { roms: roms.map((r) => r.id) } ); } export async function searchRomIGDBApi(searchTerm, searchBy, rom) { - return axios.put( - `/api/search/roms/igdb?search_term=${searchTerm}&search_by=${searchBy}`, + return api.put( + `/search/roms/igdb?search_term=${searchTerm}&search_by=${searchBy}`, { rom: rom } ); } + +export async function fetchCurrentUserApi() { + return api.get("/users/me"); +} + +export async function fetchUsersApi() { + return api.get("/users"); +} + +export async function fetchUserApi(user) { + return api.get(`/users/${user.id}`); +} + +export async function createUserApi({ username, password, role }) { + return api.post("/users", {}, { params: { username, password, role } }); +} + +export async function updateUserApi({ + id, + username, + password, + role, + enabled, + avatar, +}) { + return api.put( + `/users/${id}`, + { + avatar: avatar ? avatar[0] : null, + }, + { + headers: { + "Content-Type": avatar ? "multipart/form-data" : "text/text", + }, + params: { username, password, role, enabled }, + } + ); +} + +export async function deleteUserApi(user) { + return api.delete(`/users/${user.id}`); +} diff --git a/frontend/src/stores/auth.js b/frontend/src/stores/auth.js new file mode 100644 index 000000000..1aa9f1d93 --- /dev/null +++ b/frontend/src/stores/auth.js @@ -0,0 +1,32 @@ +import { defineStore } from "pinia"; + +const FULL_SCOPES_LIST = [ + "me.read", + "me.write", + "roms.read", + "roms.write", + "platforms.read", + "platforms.write", + "users.read", + "users.write", +]; + +export default defineStore("auth", { + state: () => ({ enabled: false, user: null, oauth_scopes: [] }), + + getters: { + scopes: (state) => { + if (!state.enabled) return FULL_SCOPES_LIST; + return state.user?.oauth_scopes ?? []; + }, + }, + + actions: { + setUser(user) { + this.user = user; + }, + setEnabled(enabled) { + this.enabled = enabled; + }, + }, +}); diff --git a/frontend/src/stores/galleryFilter.js b/frontend/src/stores/galleryFilter.js index b5898ed98..4bfc29ad8 100644 --- a/frontend/src/stores/galleryFilter.js +++ b/frontend/src/stores/galleryFilter.js @@ -1,5 +1,5 @@ import { defineStore } from "pinia"; -import { normalizeString } from "@/utils/utils.js"; +import { normalizeString } from "@/utils/utils"; export default defineStore("galleryFilter", { state: () => ({ value: "" }), diff --git a/frontend/src/stores/roms.js b/frontend/src/stores/roms.js new file mode 100644 index 000000000..3f17d2bbe --- /dev/null +++ b/frontend/src/stores/roms.js @@ -0,0 +1,26 @@ +import { defineStore } from "pinia"; + +export default defineStore("roms", { + state: () => ({ selected: [], lastSelectedIndex: -1 }), + + actions: { + updateSelectedRoms(roms) { + this.selected = roms; + }, + addSelectedRoms(rom) { + this.selected.push(rom); + }, + removeSelectedRoms(rom) { + this.selected = this.selected.filter(function (value) { + return value.id != rom.id; + }); + }, + updateLastSelectedRom(index) { + this.lastSelectedIndex = index; + }, + reset(){ + this.selected = []; + this.lastSelectedIndex = -1; + } + }, +}); diff --git a/frontend/src/styles/scrollbar.css b/frontend/src/styles/scrollbar.css index 4e84e8d46..b782ea358 100644 --- a/frontend/src/styles/scrollbar.css +++ b/frontend/src/styles/scrollbar.css @@ -1,12 +1,12 @@ /* Firefox */ * { scrollbar-width: thin; - scrollbar-color: #6e6e6e rgba(0, 0, 0, 0); + scrollbar-color: #202832 rgba(0, 0, 0, 0); } /* Chrome, Edge, and Safari */ *::-webkit-scrollbar { - width: 3px; + width: 1px; } *::-webkit-scrollbar-track { @@ -15,5 +15,5 @@ *::-webkit-scrollbar-thumb { background-color: #808080; - border-radius: 5px; + border-radius: 1px; } diff --git a/frontend/src/styles/themes.js b/frontend/src/styles/themes.js index 4db433551..22166120e 100644 --- a/frontend/src/styles/themes.js +++ b/frontend/src/styles/themes.js @@ -1,3 +1,15 @@ +const commonColors = { + "romm-accent-1": "#a452fe", + "romm-accent-2": "#c400f7", + "romm-accent-3": "#3808a4", + + "romm-red": "#da3633", + "romm-green": "#3FB950", + "romm-white": "#fefdfe", + "romm-gray": "#5D5D5D", + "romm-black": "#000000", +}; + export const rommDark = { dark: true, colors: { @@ -10,14 +22,7 @@ export const rommDark = { tooltip: "#202832", chip: "#161b22", - rommAccent1: "#a452fe", - rommAccent2: "#c400f7", - rommAccent3: "#3808a4", - - rommRed: "#da3633", - rommGreen: "#3FB950", - rommWhite: "#fefdfe", - rommBlack: "#000000", + ...commonColors, }, }; @@ -33,13 +38,11 @@ export const rommLight = { tooltip: "#fefdfe", chip: "#fefdfe", - rommAccent1: "#a452fe", - rommAccent2: "#c400f7", - rommAccent3: "#3808a4", - - rommRed: "#da3633", - rommGreen: "#3FB950", - rommWhite: "#fefdfe", - rommBlack: "#000000", + ...commonColors, }, }; + +export const themes = { + 0: "rommDark", + 1: "rommLight", +}; diff --git a/frontend/src/utils/utils.js b/frontend/src/utils/utils.js index 203e0034b..926c4da95 100644 --- a/frontend/src/utils/utils.js +++ b/frontend/src/utils/utils.js @@ -34,3 +34,5 @@ export function normalizeString(s) { .normalize("NFD") .replace(/[\u0300-\u036f]/g, ""); } + +export const defaultAvatarPath = "/assets/default_avatar.png"; diff --git a/frontend/src/views/Dashboard/Base.vue b/frontend/src/views/Dashboard/Base.vue new file mode 100644 index 000000000..ac94d87b7 --- /dev/null +++ b/frontend/src/views/Dashboard/Base.vue @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/views/Dashboard/Platforms.vue b/frontend/src/views/Dashboard/Platforms.vue new file mode 100644 index 000000000..af6b4b349 --- /dev/null +++ b/frontend/src/views/Dashboard/Platforms.vue @@ -0,0 +1,34 @@ + + + + mdi-controllerPlatforms + + + + + + + + + + diff --git a/frontend/src/views/Dashboard/Summary.vue b/frontend/src/views/Dashboard/Summary.vue new file mode 100644 index 000000000..bfb249c37 --- /dev/null +++ b/frontend/src/views/Dashboard/Summary.vue @@ -0,0 +1,21 @@ + + + + + + + mdi-controller{{ platforms.value.length }} Platforms + + + mdi-disc{{ platforms.totalGames }} Games + + + + + diff --git a/frontend/src/views/Details.vue b/frontend/src/views/Details/Base.vue similarity index 93% rename from frontend/src/views/Details.vue rename to frontend/src/views/Details/Base.vue index e66347eab..d7536dbd5 100644 --- a/frontend/src/views/Details.vue +++ b/frontend/src/views/Details/Base.vue @@ -2,18 +2,20 @@ import { ref, inject, onBeforeMount } from "vue"; import { useRoute } from "vue-router"; import { useDisplay } from "vuetify"; -import { fetchRomApi, downloadRomApi } from "@/services/api.js"; -import useDownloadStore from "@/stores/download.js"; +import { fetchRomApi, downloadRomApi } from "@/services/api"; +import storeDownload from "@/stores/download"; +import storeAuth from "@/stores/auth"; import BackgroundHeader from "@/components/Game/Details/BackgroundHeader.vue"; import AdminMenu from "@/components/AdminMenu/Base.vue"; -import SearchRomDialog from "@/components/Dialog/SearchRom.vue"; -import EditRomDialog from "@/components/Dialog/EditRom.vue"; -import DeleteRomDialog from "@/components/Dialog/DeleteRom.vue"; +import SearchRomDialog from "@/components/Dialog/Rom/SearchRom.vue"; +import EditRomDialog from "@/components/Dialog/Rom/EditRom.vue"; +import DeleteRomDialog from "@/components/Dialog/Rom/DeleteRom.vue"; import LoadingDialog from "@/components/Dialog/Loading.vue"; // Props const route = useRoute(); -const downloadStore = useDownloadStore(); +const downloadStore = storeDownload(); +const auth = storeAuth(); const rom = ref(); const updatedRom = ref(); const saveFiles = ref(false); @@ -68,7 +70,7 @@ onBeforeMount(async () => { elevation="2" :loading=" downloadStore.value.includes(rom.id) - ? 'rommAccent1' + ? 'romm-accent-1' : null " > @@ -80,7 +82,7 @@ onBeforeMount(async () => { { - + { - + @@ -188,7 +190,7 @@ onBeforeMount(async () => { 'details-content-mobile': xs, }" > - + Details Saves { item-title="file_name" v-model="filesToDownload" :items="rom.files" - class="mt-2 mb-2" + class="my-2" density="compact" variant="outlined" return-object @@ -324,7 +326,7 @@ onBeforeMount(async () => { diff --git a/frontend/src/views/Gallery.vue b/frontend/src/views/Gallery.vue deleted file mode 100644 index eeff6fedc..000000000 --- a/frontend/src/views/Gallery.vue +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Feels empty here... mdi-emoticon-sad - - - - - - - - - - - diff --git a/frontend/src/views/Gallery/Base.vue b/frontend/src/views/Gallery/Base.vue new file mode 100644 index 000000000..2e2ec3340 --- /dev/null +++ b/frontend/src/views/Gallery/Base.vue @@ -0,0 +1,316 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Feels empty here... mdi-emoticon-sad + + + + + + + + + mdi-chevron-up + + + + + {{ romsStore.selected.length }} + + + + + + + + + + + + + + + diff --git a/frontend/src/views/Home.vue b/frontend/src/views/Home.vue index a20638daf..821dd8fa8 100644 --- a/frontend/src/views/Home.vue +++ b/frontend/src/views/Home.vue @@ -1,78 +1,65 @@ - - - - - - - - + - - - - - - - - {{ platforms.value.length }} platforms - - - - {{ totalGames }} games - - - - - + - - - - - mdi-controller - - Platforms - - + - - - - - - - + + + + + diff --git a/frontend/src/views/library/Scan.vue b/frontend/src/views/Library/Scan.vue similarity index 76% rename from frontend/src/views/library/Scan.vue rename to frontend/src/views/Library/Scan.vue index 2b6be5c9d..c174ac2b5 100644 --- a/frontend/src/views/library/Scan.vue +++ b/frontend/src/views/Library/Scan.vue @@ -1,8 +1,8 @@ @@ -117,26 +120,26 @@ async function scan() { - Scan - + :loading="scanning.value" + >Scan + + + diff --git a/frontend/src/views/Login.vue b/frontend/src/views/Login.vue new file mode 100644 index 000000000..f594be00a --- /dev/null +++ b/frontend/src/views/Login.vue @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + Login + + + + + + + + + diff --git a/frontend/src/views/Settings/ControlPanel.vue b/frontend/src/views/Settings/ControlPanel.vue new file mode 100644 index 000000000..c024b0c70 --- /dev/null +++ b/frontend/src/views/Settings/ControlPanel.vue @@ -0,0 +1,54 @@ + + + + + + + Users + + User Interface + + + + + + + + + + + + + + + + + + + + + + + + + + RomM + {{ ROMM_VERSION }} + + + diff --git a/frontend/src/views/Settings/UserInterface/Theme.vue b/frontend/src/views/Settings/UserInterface/Theme.vue new file mode 100644 index 000000000..a475c5599 --- /dev/null +++ b/frontend/src/views/Settings/UserInterface/Theme.vue @@ -0,0 +1,73 @@ + + + + + mdi-theme-light-darkTheme + + + + + + + + + + + + + mdi-moon-waning-crescentDark + Theme + + + + + + + + + + + mdi-weather-sunnyLight Theme + + + + + + + + + + diff --git a/frontend/src/views/Settings/Users/Users.vue b/frontend/src/views/Settings/Users/Users.vue new file mode 100644 index 000000000..f809cef28 --- /dev/null +++ b/frontend/src/views/Settings/Users/Users.vue @@ -0,0 +1,158 @@ + + + + + mdi-account-groupUsers + + Add user + + + + + + + + + + + + + + + + + + + mdi-pencil + + mdi-delete + + + + + + + + + diff --git a/frontend/src/views/settings/ControlPanel.vue b/frontend/src/views/settings/ControlPanel.vue deleted file mode 100644 index 03fb6efc3..000000000 --- a/frontend/src/views/settings/ControlPanel.vue +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - General - [coming soon] - - User Interface - - - - - - - - - - - - - - - RomM - {{ ROMM_VERSION }} - - - diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 50101f4c2..ea1ce367a 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -73,6 +73,11 @@ export default defineConfig(({ mode }) => { changeOrigin: false, ws: true, }, + "/openapi.json": { + target: `http://localhost:${backendPort}`, + changeOrigin: false, + rewrite: (path) => path.replace(/^\/openapi.json/, "/openapi.json"), + }, }, port: 3000, }, diff --git a/poetry.lock b/poetry.lock index 7f6b84184..7a78174a5 100644 --- a/poetry.lock +++ b/poetry.lock @@ -107,6 +107,40 @@ files = [ {file = "backcall-0.2.0.tar.gz", hash = "sha256:5cbdbf27be5e7cfadb448baf0aa95508f91f2bbc6c6437cd9cd06e2a4c215e1e"}, ] +[[package]] +name = "bcrypt" +version = "4.0.1" +description = "Modern password hashing for your software and your servers" +optional = false +python-versions = ">=3.6" +files = [ + {file = "bcrypt-4.0.1-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:b1023030aec778185a6c16cf70f359cbb6e0c289fd564a7cfa29e727a1c38f8f"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:08d2947c490093a11416df18043c27abe3921558d2c03e2076ccb28a116cb6d0"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0eaa47d4661c326bfc9d08d16debbc4edf78778e6aaba29c1bc7ce67214d4410"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae88eca3024bb34bb3430f964beab71226e761f51b912de5133470b649d82344"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:a522427293d77e1c29e303fc282e2d71864579527a04ddcfda6d4f8396c6c36a"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:fbdaec13c5105f0c4e5c52614d04f0bca5f5af007910daa8b6b12095edaa67b3"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ca3204d00d3cb2dfed07f2d74a25f12fc12f73e606fcaa6975d1f7ae69cacbb2"}, + {file = "bcrypt-4.0.1-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:089098effa1bc35dc055366740a067a2fc76987e8ec75349eb9484061c54f535"}, + {file = "bcrypt-4.0.1-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:e9a51bbfe7e9802b5f3508687758b564069ba937748ad7b9e890086290d2f79e"}, + {file = "bcrypt-4.0.1-cp36-abi3-win32.whl", hash = "sha256:2caffdae059e06ac23fce178d31b4a702f2a3264c20bfb5ff541b338194d8fab"}, + {file = "bcrypt-4.0.1-cp36-abi3-win_amd64.whl", hash = "sha256:8a68f4341daf7522fe8d73874de8906f3a339048ba406be6ddc1b3ccb16fc0d9"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf4fa8b2ca74381bb5442c089350f09a3f17797829d958fad058d6e44d9eb83c"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:67a97e1c405b24f19d08890e7ae0c4f7ce1e56a712a016746c8b2d7732d65d4b"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b3b85202d95dd568efcb35b53936c5e3b3600c7cdcc6115ba461df3a8e89f38d"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cbb03eec97496166b704ed663a53680ab57c5084b2fc98ef23291987b525cb7d"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:5ad4d32a28b80c5fa6671ccfb43676e8c1cc232887759d1cd7b6f56ea4355215"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b57adba8a1444faf784394de3436233728a1ecaeb6e07e8c22c8848f179b893c"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:705b2cea8a9ed3d55b4491887ceadb0106acf7c6387699fca771af56b1cdeeda"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:2b3ac11cf45161628f1f3733263e63194f22664bf4d0c0f3ab34099c02134665"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:3100851841186c25f127731b9fa11909ab7b1df6fc4b9f8353f4f1fd952fbf71"}, + {file = "bcrypt-4.0.1.tar.gz", hash = "sha256:27d375903ac8261cfe4047f6709d16f7d18d39b1ec92aaf72af989552a650ebd"}, +] + +[package.extras] +tests = ["pytest (>=3.2.1,!=3.3.0)"] +typecheck = ["mypy"] + [[package]] name = "bidict" version = "0.22.1" @@ -375,6 +409,24 @@ files = [ {file = "decorator-5.1.1.tar.gz", hash = "sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330"}, ] +[[package]] +name = "ecdsa" +version = "0.18.0" +description = "ECDSA cryptographic signature library (pure python)" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +files = [ + {file = "ecdsa-0.18.0-py2.py3-none-any.whl", hash = "sha256:80600258e7ed2f16b9aa1d7c295bd70194109ad5a30fdee0eaeefef1d4c559dd"}, + {file = "ecdsa-0.18.0.tar.gz", hash = "sha256:190348041559e21b22a1d65cee485282ca11a6f81d503fddb84d5017e9ed1e49"}, +] + +[package.dependencies] +six = ">=1.9.0" + +[package.extras] +gmpy = ["gmpy"] +gmpy2 = ["gmpy2"] + [[package]] name = "emoji" version = "2.2.0" @@ -553,6 +605,50 @@ files = [ {file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"}, ] +[[package]] +name = "httpcore" +version = "0.17.3" +description = "A minimal low-level HTTP client." +optional = false +python-versions = ">=3.7" +files = [ + {file = "httpcore-0.17.3-py3-none-any.whl", hash = "sha256:c2789b767ddddfa2a5782e3199b2b7f6894540b17b16ec26b2c4d8e103510b87"}, + {file = "httpcore-0.17.3.tar.gz", hash = "sha256:a6f30213335e34c1ade7be6ec7c47f19f50c56db36abef1a9dfa3815b1cb3888"}, +] + +[package.dependencies] +anyio = ">=3.0,<5.0" +certifi = "*" +h11 = ">=0.13,<0.15" +sniffio = "==1.*" + +[package.extras] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] + +[[package]] +name = "httpx" +version = "0.24.1" +description = "The next generation HTTP client." +optional = false +python-versions = ">=3.7" +files = [ + {file = "httpx-0.24.1-py3-none-any.whl", hash = "sha256:06781eb9ac53cde990577af654bd990a4949de37a28bdb4a230d434f3a30b9bd"}, + {file = "httpx-0.24.1.tar.gz", hash = "sha256:5853a43053df830c20f8110c5e69fe44d035d850b2dfe795e196f00fdb774bdd"}, +] + +[package.dependencies] +certifi = "*" +httpcore = ">=0.15.0,<0.18.0" +idna = "*" +sniffio = "*" + +[package.extras] +brotli = ["brotli", "brotlicffi"] +cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] + [[package]] name = "idna" version = "3.4" @@ -629,6 +725,17 @@ qtconsole = ["qtconsole"] test = ["pytest (<7.1)", "pytest-asyncio", "testpath"] test-extra = ["curio", "matplotlib (!=3.2.0)", "nbformat", "numpy (>=1.21)", "pandas", "pytest (<7.1)", "pytest-asyncio", "testpath", "trio"] +[[package]] +name = "itsdangerous" +version = "2.1.2" +description = "Safely pass data to untrusted environments and back." +optional = false +python-versions = ">=3.7" +files = [ + {file = "itsdangerous-2.1.2-py3-none-any.whl", hash = "sha256:2c2349112351b88699d8d4b6b075022c0808887cb7ad10069318a8b0bc88db44"}, + {file = "itsdangerous-2.1.2.tar.gz", hash = "sha256:5dbbc68b317e5e42f327f9021763545dc3fc3bfe22e6deb96aaf1fc38874156a"}, +] + [[package]] name = "jedi" version = "0.18.2" @@ -927,6 +1034,26 @@ files = [ qa = ["flake8 (==3.8.3)", "mypy (==0.782)"] testing = ["docopt", "pytest (<6.0.0)"] +[[package]] +name = "passlib" +version = "1.7.4" +description = "comprehensive password hashing framework supporting over 30 schemes" +optional = false +python-versions = "*" +files = [ + {file = "passlib-1.7.4-py2.py3-none-any.whl", hash = "sha256:aa6bca462b8d8bda89c70b382f0c298a20b5560af6cbfa2dce410c0a2fb669f1"}, + {file = "passlib-1.7.4.tar.gz", hash = "sha256:defd50f72b65c5402ab2c573830a6978e5f202ad0d984793c8dde2c4152ebe04"}, +] + +[package.dependencies] +bcrypt = {version = ">=3.1.0", optional = true, markers = "extra == \"bcrypt\""} + +[package.extras] +argon2 = ["argon2-cffi (>=18.2.0)"] +bcrypt = ["bcrypt (>=3.1.0)"] +build-docs = ["cloud-sptheme (>=1.10.1)", "sphinx (>=1.6)", "sphinxcontrib-fulltoc (>=1.2.0)"] +totp = ["cryptography"] + [[package]] name = "pexpect" version = "4.8.0" @@ -1006,6 +1133,17 @@ files = [ [package.extras] tests = ["pytest"] +[[package]] +name = "pyasn1" +version = "0.5.0" +description = "Pure-Python implementation of ASN.1 types and DER/BER/CER codecs (X.208)" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7" +files = [ + {file = "pyasn1-0.5.0-py2.py3-none-any.whl", hash = "sha256:87a2121042a1ac9358cabcaf1d07680ff97ee6404333bacca15f76aa8ad01a57"}, + {file = "pyasn1-0.5.0.tar.gz", hash = "sha256:97b7290ca68e62a832558ec3976f15cbf911bf5d7c7039d8b861c2a0ece69fde"}, +] + [[package]] name = "pycparser" version = "2.21" @@ -1122,6 +1260,24 @@ tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} [package.extras] testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] +[[package]] +name = "pytest-asyncio" +version = "0.21.1" +description = "Pytest support for asyncio" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pytest-asyncio-0.21.1.tar.gz", hash = "sha256:40a7eae6dded22c7b604986855ea48400ab15b069ae38116e8c01238e9eeb64d"}, + {file = "pytest_asyncio-0.21.1-py3-none-any.whl", hash = "sha256:8666c1c8ac02631d7c51ba282e0c69a8a452b211ffedf2599099845da5c5c37b"}, +] + +[package.dependencies] +pytest = ">=7.0.0" + +[package.extras] +docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"] +testing = ["coverage (>=6.2)", "flaky (>=3.5.0)", "hypothesis (>=5.7.1)", "mypy (>=0.931)", "pytest-trio (>=0.7.0)"] + [[package]] name = "pytest-env" version = "0.8.2" @@ -1214,6 +1370,42 @@ files = [ asyncio-client = ["aiohttp (>=3.4)"] client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] +[[package]] +name = "python-jose" +version = "3.3.0" +description = "JOSE implementation in Python" +optional = false +python-versions = "*" +files = [ + {file = "python-jose-3.3.0.tar.gz", hash = "sha256:55779b5e6ad599c6336191246e95eb2293a9ddebd555f796a65f838f07e5d78a"}, + {file = "python_jose-3.3.0-py2.py3-none-any.whl", hash = "sha256:9b1376b023f8b298536eedd47ae1089bcdb848f1535ab30555cd92002d78923a"}, +] + +[package.dependencies] +cryptography = {version = ">=3.4.0", optional = true, markers = "extra == \"cryptography\""} +ecdsa = "!=0.15" +pyasn1 = "*" +rsa = "*" + +[package.extras] +cryptography = ["cryptography (>=3.4.0)"] +pycrypto = ["pyasn1", "pycrypto (>=2.6.0,<2.7.0)"] +pycryptodome = ["pyasn1", "pycryptodome (>=3.3.1,<4.0.0)"] + +[[package]] +name = "python-multipart" +version = "0.0.6" +description = "A streaming multipart parser for Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "python_multipart-0.0.6-py3-none-any.whl", hash = "sha256:ee698bab5ef148b0a760751c261902cd096e57e10558e11aca17646b74ee1c18"}, + {file = "python_multipart-0.0.6.tar.gz", hash = "sha256:e9925a80bb668529f1b67c7fdb0a5dacdd7cbfc6fb0bff3ea443fe22bdd62132"}, +] + +[package.extras] +dev = ["atomicwrites (==1.2.1)", "attrs (==19.2.0)", "coverage (==6.5.0)", "hatch", "invoke (==1.7.3)", "more-itertools (==4.3.0)", "pbr (==4.3.0)", "pluggy (==1.0.0)", "py (==1.11.0)", "pytest (==7.2.0)", "pytest-cov (==4.0.0)", "pytest-timeout (==2.1.0)", "pyyaml (==5.1)"] + [[package]] name = "python-socketio" version = "5.8.0" @@ -1336,6 +1528,20 @@ files = [ click = ">=5.0.0" redis = ">=4.0.0" +[[package]] +name = "rsa" +version = "4.9" +description = "Pure-Python RSA implementation" +optional = false +python-versions = ">=3.6,<4" +files = [ + {file = "rsa-4.9-py3-none-any.whl", hash = "sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7"}, + {file = "rsa-4.9.tar.gz", hash = "sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21"}, +] + +[package.dependencies] +pyasn1 = ">=0.1.3" + [[package]] name = "six" version = "1.16.0" @@ -1490,6 +1696,21 @@ anyio = ">=3.4.0,<5" [package.extras] full = ["httpx (>=0.22.0)", "itsdangerous", "jinja2", "python-multipart", "pyyaml"] +[[package]] +name = "starlette-csrf" +version = "3.0.0" +description = "Starlette middleware implementing Double Submit Cookie technique to mitigate CSRF" +optional = false +python-versions = ">=3.8" +files = [ + {file = "starlette_csrf-3.0.0-py3-none-any.whl", hash = "sha256:aac29b366e83621d3fc56be690866e16f3c56df91ab5e184b77950540a4e2761"}, + {file = "starlette_csrf-3.0.0.tar.gz", hash = "sha256:7afaca8c72cc3c726e5942778af53454607ca3e653fd86cd75ee35d8cd1cfa77"}, +] + +[package.dependencies] +itsdangerous = ">=2.0.1,<3.0.0" +starlette = ">=0.14.2" + [[package]] name = "stream-zip" version = "0.0.67" @@ -1531,6 +1752,28 @@ files = [ docs = ["myst-parser", "pydata-sphinx-theme", "sphinx"] test = ["argcomplete (>=2.0)", "pre-commit", "pytest", "pytest-mock"] +[[package]] +name = "types-passlib" +version = "1.7.7.13" +description = "Typing stubs for passlib" +optional = false +python-versions = "*" +files = [ + {file = "types-passlib-1.7.7.13.tar.gz", hash = "sha256:f152639f1f2103d7f59a56e2aec5f9398a75a80830991d0d68aac5c2b9c32a77"}, + {file = "types_passlib-1.7.7.13-py3-none-any.whl", hash = "sha256:414b5ee9c88313357c9261cfcf816509b1e8e4673f0796bd61e9ef249f6fe076"}, +] + +[[package]] +name = "types-pyasn1" +version = "0.4.0.6" +description = "Typing stubs for pyasn1" +optional = false +python-versions = "*" +files = [ + {file = "types-pyasn1-0.4.0.6.tar.gz", hash = "sha256:8f1965d0b79152f9d1efc89f9aa9a8cdda7cd28b2619df6737c095cbedeff98b"}, + {file = "types_pyasn1-0.4.0.6-py3-none-any.whl", hash = "sha256:dd5fc818864e63a66cd714be0a7a59a493f4a81b87ee9ac978c41f1eaa9a0cef"}, +] + [[package]] name = "types-pyopenssl" version = "23.2.0.2" @@ -1545,6 +1788,20 @@ files = [ [package.dependencies] cryptography = ">=35.0.0" +[[package]] +name = "types-python-jose" +version = "3.3.4.8" +description = "Typing stubs for python-jose" +optional = false +python-versions = "*" +files = [ + {file = "types-python-jose-3.3.4.8.tar.gz", hash = "sha256:3c316675c3cee059ccb9aff87358254344915239fa7f19cee2787155a7db14ac"}, + {file = "types_python_jose-3.3.4.8-py3-none-any.whl", hash = "sha256:95592273443b45dc5cc88f7c56aa5a97725428753fb738b794e63ccb4904954e"}, +] + +[package.dependencies] +types-pyasn1 = "*" + [[package]] name = "types-pyyaml" version = "6.0.12.11" @@ -1933,4 +2190,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10" -content-hash = "c973b508a9bf80ff3875173c2c9b505e5c598fba6ef82f432936ce2a270cb292" +content-hash = "f2a475a18c80f489d280727e6db8904299b89c20b14691d77e611863c1a63fe0" diff --git a/pyproject.toml b/pyproject.toml index b0b29b83d..19132cd56 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "RomM" -version = "1.10" +version = "2.0.0" description = "RomM (Rom Manager) is a web based retro roms manager integrated with IGDB." authors = ["zurdi "] readme = "README.md" @@ -33,7 +33,16 @@ types-pyyaml = "^6.0.12.11" types-requests = "^2.31.0.2" mypy = "^1.4.1" types-redis = "^4.6.0.3" +python-jose = {extras = ["cryptography"], version = "^3.3.0"} +passlib = {extras = ["bcrypt"], version = "^1.7.4"} +itsdangerous = "^2.1.2" stream-zip = "^0.0.67" +starlette-csrf = "^3.0.0" +pytest-asyncio = "^0.21.1" +httpx = "^0.24.1" +python-multipart = "^0.0.6" +types-python-jose = "^3.3.4.8" +types-passlib = "^1.7.7.13" [build-system] requires = ["poetry-core"] diff --git a/pytest.ini b/pytest.ini index fc799fc56..8d58abc5b 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,7 +1,12 @@ [pytest] +asyncio_mode = auto env = ROMM_BASE_PATH=romm_test ROMM_DB_DRIVER=mariadb DB_NAME=romm_test DB_USER=romm_test DB_PASSWD=passwd + ROMM_AUTH_ENABLED=true + ROMM_AUTH_USERNAME=test_admin + ROMM_AUTH_PASSWORD=test_admin_password + ROMM_AUTH_SECRET_KEY=843f6cefc5ba1430d54061301c2893be00c2aef11dae39ffec13a2af1a86e867