From 707bdfc376d232245d320b13dc03f73cdea2cba3 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Aug 2023 09:58:51 -0400 Subject: [PATCH] Add session middlware + redis back auth --- backend/config/__init__.py | 5 ++++- backend/endpoints/identity.py | 2 +- backend/endpoints/platform.py | 6 ++++-- backend/endpoints/rom.py | 24 ++++++++++++++++++------ backend/endpoints/search.py | 8 +++++--- backend/handler/igdb_handler.py | 8 ++++---- backend/main.py | 9 ++++++++- backend/utils/auth.py | 26 +++++++++++++++++++++----- frontend/src/views/Home.vue | 17 +++++++++++++++++ poetry.lock | 13 ++++++++++++- pyproject.toml | 3 ++- 11 files changed, 96 insertions(+), 25 deletions(-) diff --git a/backend/config/__init__.py b/backend/config/__init__.py index f24d2c6ee..0325aebd6 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -3,7 +3,7 @@ from dotenv import load_dotenv load_dotenv() -# Uvicorn +# UVICORN DEV_PORT: int = int(os.environ.get("VITE_BACKEND_DEV_PORT", "5000")) DEV_HOST: str = "0.0.0.0" @@ -47,3 +47,6 @@ STEAMGRIDDB_API_KEY = os.environ.get("STEAMGRIDDB_API_KEY", "") # DB DRIVERS ROMM_DB_DRIVER = os.environ.get("ROMM_DB_DRIVER", "sqlite") + +# SECRETS +SECRET_KEY = "9b9da8bfd88822ad708530bb36e61d02c130a74de7a8e84d5f456bf6fee5c518" diff --git a/backend/endpoints/identity.py b/backend/endpoints/identity.py index 70776cca6..97d532434 100644 --- a/backend/endpoints/identity.py +++ b/backend/endpoints/identity.py @@ -64,7 +64,7 @@ def users(request: Request) -> list[UserSchema]: @router.get("/users/me") -@requires("authenticated") +@requires(["authenticated"]) def current_user(request: Request) -> UserSchema: return request.user diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index ec1e21506..5b6c3a706 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -1,5 +1,6 @@ -from fastapi import APIRouter +from fastapi import APIRouter, Request from pydantic import BaseModel, BaseConfig +from starlette.authentication import requires from handler import dbh @@ -23,6 +24,7 @@ class PlatformSchema(BaseModel): @router.get("/platforms") -def platforms() -> list[PlatformSchema]: +@requires(["authenticated"]) +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 81ac7cd06..e3adf7086 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -6,6 +6,7 @@ from fastapi_pagination.ext.sqlalchemy import paginate from fastapi_pagination.cursor import CursorPage, CursorParams from fastapi.responses import FileResponse from pydantic import BaseModel, BaseConfig +from starlette.authentication import requires from logger.logger import log from handler import dbh @@ -64,14 +65,16 @@ class RomSchema(BaseModel): @router.get("/platforms/{p_slug}/roms/{id}") -def rom(id: int) -> RomSchema: +@requires(["authenticated"]) +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") -def download_rom(id: int, files: str): +@requires(["authenticated"]) +def download_rom(request: Request, id: int, files: str): rom = dbh.get_rom(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" @@ -104,8 +107,13 @@ def download_rom(id: int, files: str): @router.get("/platforms/{p_slug}/roms") +@requires(["authenticated"]) 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,10 +131,11 @@ def roms( @router.patch("/platforms/{p_slug}/roms/{id}") -async def updateRom(req: Request, p_slug: str, id: int) -> dict: +@requires(["authenticated"]) +async def updateRom(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) @@ -167,7 +176,10 @@ async def updateRom(req: Request, p_slug: str, id: int) -> dict: @router.delete("/platforms/{p_slug}/roms/{id}") -def delete_rom(p_slug: str, id: int, filesystem: bool = False) -> dict: +@requires(["authenticated", "admin"]) +def delete_rom( + request: Request, p_slug: str, id: int, filesystem: bool = False +) -> dict: """Detele rom from database [and filesystem]""" rom: Rom = dbh.get_rom(id) diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index 809241df5..637c951a7 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -1,5 +1,6 @@ -from fastapi import APIRouter, Request import emoji +from fastapi import APIRouter, Request +from starlette.authentication import requires from logger.logger import log from handler import igdbh @@ -8,12 +9,13 @@ router = APIRouter() @router.put("/search/roms/igdb") +@requires(["authenticated"]) 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.""" - 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/handler/igdb_handler.py b/backend/handler/igdb_handler.py index bff4ee00c..44e3b3c2a 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -224,8 +224,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 + cache.set("romm:twitch_token_expires_at", time.time() + expires_in - 10) # type: ignore log.info("Twitch token fetched!") @@ -237,8 +237,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 + token_expires_at = cache.get("romm:twitch_token_expires_at") # type: ignore 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/main.py b/backend/main.py index d2f016406..8a951aac7 100644 --- a/backend/main.py +++ b/backend/main.py @@ -4,8 +4,9 @@ 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 config import DEV_PORT, DEV_HOST, SECRET_KEY from endpoints import search, platform, rom, identity, scan # noqa from utils.socket import socket_app from utils.auth import BasicAuthBackend @@ -22,6 +23,12 @@ app.add_middleware( AuthenticationMiddleware, backend=BasicAuthBackend(), ) +app.add_middleware( + SessionMiddleware, + secret_key=SECRET_KEY, + same_site="strict", + https_only=False, +) app.include_router(identity.router) app.include_router(platform.router) app.include_router(rom.router) diff --git a/backend/utils/auth.py b/backend/utils/auth.py index ab715a26a..a76f06679 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -1,5 +1,6 @@ import base64 import binascii +import secrets from typing import Annotated from datetime import datetime, timedelta from fastapi import Depends, HTTPException, status @@ -15,6 +16,11 @@ from starlette.requests import HTTPConnection from handler import dbh from models.user import User +from config import SECRET_KEY +from utils.cache import cache + +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 def verify_password(plain_password, hashed_password): @@ -38,10 +44,6 @@ def authenticate_user(username: str, password: str): # JWT based authentication -SECRET_KEY = "9b9da8bfd88822ad708530bb36e61d02c130a74de7a8e84d5f456bf6fee5c518" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @@ -95,6 +97,16 @@ async def get_current_active_user( class BasicAuthBackend(AuthenticationBackend): async def authenticate(self, conn: HTTPConnection): + # Check if session key already stored in redis + session_id = conn.session.get('session_id') + if session_id: + username = cache.get(f'romm:{session_id}') + if username: + user = dbh.get_user(username) + if user: + # Key exists therefore user is authenticated + return AuthCredentials(["authenticated", "admin"]), user + if "Authorization" not in conn.headers: return @@ -115,5 +127,9 @@ class BasicAuthBackend(AuthenticationBackend): detail="Incorrect username or password", headers={"WWW-Authenticate": "Authorization"}, ) + + # Generate unique session key and store in redis + conn.session['session_id'] = secrets.token_hex(16) + cache.set(f'romm:{conn.session["session_id"]}', user.username) - return AuthCredentials(["authenticated"]), user + return AuthCredentials(["authenticated", "admin"]), user diff --git a/frontend/src/views/Home.vue b/frontend/src/views/Home.vue index a20638daf..5257f87b9 100644 --- a/frontend/src/views/Home.vue +++ b/frontend/src/views/Home.vue @@ -3,11 +3,20 @@ import { useDisplay } from "vuetify"; import { views } from "@/utils/utils.js"; import storePlatforms from "@/stores/platforms.js"; import PlatformCard from "@/components/Platform/PlatformCard.vue"; +import axios from "axios"; // Props const platforms = storePlatforms(); const totalGames = platforms.totalGames; const { lgAndUp } = useDisplay(); + +function login() { + axios.post("/api/login", {}, { + headers: { + Authorization: "Basic Z2Vvcmdlcy1hbnRvaW5lOnBhc3N3b3Jk", + } + }) +}