mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
Add session middlware + redis back auth
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 = []
|
||||
|
||||
@@ -224,8 +224,8 @@ class TwitchAuth:
|
||||
sys.exit(2)
|
||||
|
||||
# Set token in redis to expire in <expires_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...")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -24,6 +33,14 @@ const { lgAndUp } = useDisplay();
|
||||
<v-spacer />
|
||||
</v-row>
|
||||
|
||||
<v-row class="pa-2" no-gutters>
|
||||
<v-spacer />
|
||||
<v-col cols="12" xs="12" sm="10" md="10" lg="10">
|
||||
<v-btn @click="login">Login</v-btn>
|
||||
</v-col>
|
||||
<v-spacer />
|
||||
</v-row>
|
||||
|
||||
<!-- Info chips -->
|
||||
<v-row class="pa-2" no-gutters>
|
||||
<v-spacer />
|
||||
|
||||
13
poetry.lock
generated
13
poetry.lock
generated
@@ -681,6 +681,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"
|
||||
@@ -2037,4 +2048,4 @@ multidict = ">=4.0"
|
||||
[metadata]
|
||||
lock-version = "2.0"
|
||||
python-versions = "^3.10"
|
||||
content-hash = "0fe20b7702dd6e98a95cf36aa82f6a46ed1245bc9cf39edc60b1cdacc4d4fe64"
|
||||
content-hash = "5f20ce01db3384449771e0780b7e6ceaa2b3b19925d1936a82ace4f705687a7c"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "RomM"
|
||||
version = "1.9.2"
|
||||
version = "<romm_version>"
|
||||
description = "RomM (Rom Manager) is a web based retro roms manager integrated with IGDB."
|
||||
authors = ["zurdi <zurdizurdo25@gmail.com>"]
|
||||
readme = "README.md"
|
||||
@@ -35,6 +35,7 @@ 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"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
|
||||
Reference in New Issue
Block a user