From 9c3bc6b842fa7d94fef1553e835c38a554afae1b Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Aug 2023 22:15:05 -0400 Subject: [PATCH 001/164] Add jwt based auth --- backend/alembic/versions/1.9.2_.py | 93 ++++++++++++++++++++++ backend/endpoints/identity.py | 62 +++++++++++++++ backend/endpoints/platform.py | 2 +- backend/endpoints/rom.py | 10 +-- backend/endpoints/search.py | 2 +- backend/handler/db_handler.py | 48 ++++++++++++ backend/main.py | 3 +- backend/models/__init__.py | 3 + backend/models/platform.py | 2 +- backend/models/rom.py | 2 +- backend/models/user.py | 11 +++ backend/utils/auth.py | 81 +++++++++++++++++++ poetry.lock | 121 ++++++++++++++++++++++++++++- pyproject.toml | 4 +- 14 files changed, 432 insertions(+), 12 deletions(-) create mode 100644 backend/alembic/versions/1.9.2_.py create mode 100644 backend/endpoints/identity.py create mode 100644 backend/models/user.py create mode 100644 backend/utils/auth.py diff --git a/backend/alembic/versions/1.9.2_.py b/backend/alembic/versions/1.9.2_.py new file mode 100644 index 000000000..ca6e89010 --- /dev/null +++ b/backend/alembic/versions/1.9.2_.py @@ -0,0 +1,93 @@ +"""empty message + +Revision ID: 1.9.2 +Revises: 1.8.3 +Create Date: 2023-08-09 21:56:50.289585 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +# 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("disabled", sa.Boolean(), 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 + ) + + with op.batch_alter_table("platforms", schema=None) as batch_op: + batch_op.alter_column( + "slug", existing_type=mysql.VARCHAR(length=50), nullable=True + ) + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.alter_column( + "p_slug", existing_type=mysql.VARCHAR(length=50), nullable=True + ) + batch_op.alter_column( + "file_name_no_tags", existing_type=mysql.VARCHAR(length=450), nullable=True + ) + batch_op.alter_column( + "url_screenshots", + existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"), + nullable=True, + existing_server_default=sa.text("'[]'"), + ) + batch_op.alter_column( + "path_screenshots", + existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"), + nullable=True, + existing_server_default=sa.text("'[]'"), + ) + + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.alter_column( + "path_screenshots", + existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"), + nullable=False, + existing_server_default=sa.text("'[]'"), + ) + batch_op.alter_column( + "url_screenshots", + existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"), + nullable=False, + existing_server_default=sa.text("'[]'"), + ) + batch_op.alter_column( + "file_name_no_tags", existing_type=mysql.VARCHAR(length=450), nullable=False + ) + batch_op.alter_column( + "p_slug", existing_type=mysql.VARCHAR(length=50), nullable=False + ) + + with op.batch_alter_table("platforms", schema=None) as batch_op: + batch_op.alter_column( + "slug", existing_type=mysql.VARCHAR(length=50), nullable=False + ) + + 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/endpoints/identity.py b/backend/endpoints/identity.py new file mode 100644 index 000000000..9fa707a9b --- /dev/null +++ b/backend/endpoints/identity.py @@ -0,0 +1,62 @@ +from typing import Annotated +from datetime import timedelta +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from pydantic import BaseModel, BaseConfig + +from handler import dbh +from models.user import User +from utils.auth import ( + authenticate_user, + create_access_token, + get_current_active_user, + get_password_hash, + ACCESS_TOKEN_EXPIRE_MINUTES, +) + +router = APIRouter() + + +class TokenSchema(BaseModel): + access_token: str + token_type: str + + +class UserSchema(BaseModel): + username: str + disabled: bool + + class Config(BaseConfig): + orm_mode = True + + +@router.post("/token", response_model=TokenSchema) +def login_with_password(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): + user = authenticate_user(form_data.username, form_data.password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + data={"sub": user.username}, expires_delta=access_token_expires + ) + + return {"access_token": access_token, "token_type": "bearer"} + + +@router.get("/users/me/", response_model=UserSchema) +def current_user(current_user: Annotated[User, Depends(get_current_active_user)]): + return current_user + + +@router.post("/users/", response_model=UserSchema) +def create_user(username: str, password: str): + user = User( + username=username, hashed_password=get_password_hash(password), disabled=False + ) + dbh.add_user(user) + return user diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index 850e18cb8..ec1e21506 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -22,7 +22,7 @@ class PlatformSchema(BaseModel): orm_mode = True -@router.get("/platforms", status_code=200) +@router.get("/platforms") def platforms() -> list[PlatformSchema]: """Returns platforms data""" return dbh.get_platforms() diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 76c70e9ad..81ac7cd06 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -63,14 +63,14 @@ class RomSchema(BaseModel): orm_mode = True -@router.get("/platforms/{p_slug}/roms/{id}", status_code=200) +@router.get("/platforms/{p_slug}/roms/{id}") def rom(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) +@router.get("/platforms/{p_slug}/roms/{id}/download") def download_rom(id: int, files: str): rom = dbh.get_rom(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" @@ -103,7 +103,7 @@ def download_rom(id: int, files: str): ) -@router.get("/platforms/{p_slug}/roms", status_code=200) +@router.get("/platforms/{p_slug}/roms") def roms( p_slug: str, size: int = 60, cursor: str = "", search_term: str = "" ) -> CursorPage[RomSchema]: @@ -122,7 +122,7 @@ def roms( return paginate(session, qq, cursor_params) -@router.patch("/platforms/{p_slug}/roms/{id}", status_code=200) +@router.patch("/platforms/{p_slug}/roms/{id}") async def updateRom(req: Request, p_slug: str, id: int) -> dict: """Updates rom details""" @@ -166,7 +166,7 @@ async def updateRom(req: Request, p_slug: str, id: int) -> dict: } -@router.delete("/platforms/{p_slug}/roms/{id}", status_code=200) +@router.delete("/platforms/{p_slug}/roms/{id}") def delete_rom(p_slug: str, id: int, filesystem: bool = False) -> dict: """Detele rom from database [and filesystem]""" diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index b63f3e3ed..809241df5 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -7,7 +7,7 @@ from handler import igdbh router = APIRouter() -@router.put("/search/roms/igdb", status_code=200) +@router.put("/search/roms/igdb") async def search_rom_igdb( req: Request, search_term: str = "", search_by: str = "" ) -> dict: diff --git a/backend/handler/db_handler.py b/backend/handler/db_handler.py index 76b2df462..0c50dc848 100644 --- a/backend/handler/db_handler.py +++ b/backend/handler/db_handler.py @@ -9,6 +9,7 @@ from logger.logger import log from config.config_loader import ConfigLoader from models.platform import Platform from models.rom import Rom +from models.user import User class DBHandler: @@ -136,3 +137,50 @@ 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: + session.merge(user) + except ProgrammingError as e: + self.raise_error(e) + + def get_user(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_by_id(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) diff --git a/backend/main.py b/backend/main.py index f8f9a1151..078083938 100644 --- a/backend/main.py +++ b/backend/main.py @@ -5,7 +5,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi_pagination import add_pagination from config import DEV_PORT, DEV_HOST -from endpoints import search, platform, rom, scan # noqa +from endpoints import search, platform, rom, identity, scan # noqa from utils.socket import socket_app app = FastAPI() @@ -19,6 +19,7 @@ app.add_middleware( app.include_router(search.router) app.include_router(platform.router) app.include_router(rom.router) +app.include_router(identity.router) add_pagination(app) app.mount("/ws", socket_app) diff --git a/backend/models/__init__.py b/backend/models/__init__.py index e69de29bb..c16876add 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 # 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/user.py b/backend/models/user.py new file mode 100644 index 000000000..1c82566b3 --- /dev/null +++ b/backend/models/user.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, String, Boolean, Integer + +from .base import BaseModel + +class User(BaseModel): + __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)) + disabled: bool = Column(Boolean(), default=False) + diff --git a/backend/utils/auth.py b/backend/utils/auth.py new file mode 100644 index 000000000..8a2d877bd --- /dev/null +++ b/backend/utils/auth.py @@ -0,0 +1,81 @@ +from typing import Annotated +from datetime import datetime, timedelta +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from passlib.context import CryptContext + +from handler import dbh +from models.user import User + +# to get a string like this run: +# openssl rand -hex 32 +SECRET_KEY = "9b9da8bfd88822ad708530bb36e61d02c130a74de7a8e84d5f456bf6fee5c518" +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + + +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(username) + if not user: + return False + + if not verify_password(password, user.hashed_password): + return False + + return user + + +def create_access_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=15) + + to_encode.update({"exp": expire}) + + return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + + +async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if username is None: + raise credentials_exception + except JWTError: + raise credentials_exception + + user = dbh.get_user(username) + if user is None: + raise credentials_exception + + return user + + +async def get_current_active_user( + current_user: Annotated[User, Depends(get_current_user)] +): + if current_user.disabled: + raise HTTPException(status_code=400, detail="Inactive user") + + return current_user diff --git a/poetry.lock b/poetry.lock index dffa546dc..5d5268e92 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" @@ -927,6 +979,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 +1078,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" @@ -1214,6 +1297,28 @@ 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-socketio" version = "5.8.0" @@ -1336,6 +1441,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" @@ -1918,4 +2037,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10" -content-hash = "8000e74d2aeed13c72744d23d6075103398d8d255ac3f7317683920f7441015f" +content-hash = "0fe20b7702dd6e98a95cf36aa82f6a46ed1245bc9cf39edc60b1cdacc4d4fe64" diff --git a/pyproject.toml b/pyproject.toml index b13ed9025..e24184324 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "RomM" -version = "" +version = "1.9.2" description = "RomM (Rom Manager) is a web based retro roms manager integrated with IGDB." authors = ["zurdi "] readme = "README.md" @@ -33,6 +33,8 @@ 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"} [build-system] requires = ["poetry-core"] From 32a79ac52d18f181c372618125159a508a608cf1 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Aug 2023 22:47:37 -0400 Subject: [PATCH 002/164] Switch to cookie based auth --- backend/endpoints/identity.py | 38 +++++++++++++++++++++++------------ backend/utils/auth.py | 24 ++++++++++++---------- 2 files changed, 38 insertions(+), 24 deletions(-) diff --git a/backend/endpoints/identity.py b/backend/endpoints/identity.py index 9fa707a9b..fca2cdf58 100644 --- a/backend/endpoints/identity.py +++ b/backend/endpoints/identity.py @@ -1,6 +1,6 @@ from typing import Annotated from datetime import timedelta -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, status, Response from fastapi.security import OAuth2PasswordRequestForm from pydantic import BaseModel, BaseConfig @@ -17,11 +17,6 @@ from utils.auth import ( router = APIRouter() -class TokenSchema(BaseModel): - access_token: str - token_type: str - - class UserSchema(BaseModel): username: str disabled: bool @@ -30,8 +25,10 @@ class UserSchema(BaseModel): orm_mode = True -@router.post("/token", response_model=TokenSchema) -def login_with_password(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): +@router.post("/token", response_model=UserSchema) +def login_with_password( + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], response: Response +): user = authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( @@ -45,16 +42,31 @@ def login_with_password(form_data: Annotated[OAuth2PasswordRequestForm, Depends( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + response.set_cookie("access_token", access_token, httponly=True) + + return user -@router.get("/users/me/", response_model=UserSchema) -def current_user(current_user: Annotated[User, Depends(get_current_active_user)]): +@router.get( + "/users/", + dependencies=[Depends(get_current_active_user)], +) +def users() -> list[UserSchema]: + return dbh.get_users() + + +@router.get("/users/me/") +def current_user( + current_user: Annotated[User, Depends(get_current_active_user)] +) -> UserSchema: return current_user -@router.post("/users/", response_model=UserSchema) -def create_user(username: str, password: str): +@router.post( + "/users/", + dependencies=[Depends(get_current_active_user)], +) +def create_user(username: str, password: str) -> UserSchema: user = User( username=username, hashed_password=get_password_hash(password), disabled=False ) diff --git a/backend/utils/auth.py b/backend/utils/auth.py index 8a2d877bd..3b4d774b1 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -1,7 +1,6 @@ from typing import Annotated from datetime import datetime, timedelta -from fastapi import Depends, HTTPException, status -from fastapi.security import OAuth2PasswordBearer +from fastapi import Depends, HTTPException, status, Request from jose import JWTError, jwt from passlib.context import CryptContext @@ -15,7 +14,6 @@ ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def verify_password(plain_password, hashed_password): @@ -50,24 +48,28 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None): return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, +async def get_current_user(request: Request): + authentication_exception = HTTPException( + status_code=status.HTTP_302_FOUND, + detail="Not authenticated", + headers={"Location": "/login"}, ) + token = request.cookies.get('access_token') + if token is None: + raise authentication_exception + try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: - raise credentials_exception + raise authentication_exception except JWTError: - raise credentials_exception + raise authentication_exception user = dbh.get_user(username) if user is None: - raise credentials_exception + raise authentication_exception return user From 37200aeefcc96c7d090e2a9767119d381e3ca6a2 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Aug 2023 22:52:53 -0400 Subject: [PATCH 003/164] Make cookie safe --- backend/endpoints/identity.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/endpoints/identity.py b/backend/endpoints/identity.py index fca2cdf58..5737f60d6 100644 --- a/backend/endpoints/identity.py +++ b/backend/endpoints/identity.py @@ -42,7 +42,9 @@ def login_with_password( data={"sub": user.username}, expires_delta=access_token_expires ) - response.set_cookie("access_token", access_token, httponly=True) + response.set_cookie( + "access_token", access_token, httponly=True, secure=True, samesite="strict" + ) return user From cb306d3099b062733a761f3aa1de21aae43b6848 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Aug 2023 00:06:25 -0400 Subject: [PATCH 004/164] Working authentication via starlette --- backend/endpoints/identity.py | 57 +++++++++++---------- backend/main.py | 10 +++- backend/models/user.py | 4 +- backend/utils/auth.py | 94 ++++++++++++++++++++++++----------- 4 files changed, 105 insertions(+), 60 deletions(-) diff --git a/backend/endpoints/identity.py b/backend/endpoints/identity.py index 5737f60d6..70776cca6 100644 --- a/backend/endpoints/identity.py +++ b/backend/endpoints/identity.py @@ -1,15 +1,15 @@ from typing import Annotated from datetime import timedelta -from fastapi import APIRouter, Depends, HTTPException, status, Response +from fastapi import APIRouter, Depends, HTTPException, status, Request from fastapi.security import OAuth2PasswordRequestForm from pydantic import BaseModel, BaseConfig +from starlette.authentication import requires from handler import dbh from models.user import User from utils.auth import ( authenticate_user, create_access_token, - get_current_active_user, get_password_hash, ACCESS_TOKEN_EXPIRE_MINUTES, ) @@ -26,49 +26,52 @@ class UserSchema(BaseModel): @router.post("/token", response_model=UserSchema) -def login_with_password( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()], response: Response +def generate_access_token( + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], request: Request ): user = authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, + headers={"WWW-Authenticate": "Authorization"}, ) - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) - - response.set_cookie( - "access_token", access_token, httponly=True, secure=True, samesite="strict" + create_access_token( + data={"sub": user.username}, + expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES), ) return user -@router.get( - "/users/", - dependencies=[Depends(get_current_active_user)], -) -def users() -> list[UserSchema]: +@router.post("/login") +def login(request: Request): + if request.user.is_authenticated: + return {"message": "Successfully logged in"} + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Authorization"}, + ) + + +@router.get("/users") +@requires(["authenticated", "admin"]) +def users(request: Request) -> list[UserSchema]: return dbh.get_users() -@router.get("/users/me/") -def current_user( - current_user: Annotated[User, Depends(get_current_active_user)] -) -> UserSchema: - return current_user +@router.get("/users/me") +@requires("authenticated") +def current_user(request: Request) -> UserSchema: + return request.user -@router.post( - "/users/", - dependencies=[Depends(get_current_active_user)], -) -def create_user(username: str, password: str) -> UserSchema: +@router.post("/users/") +@requires(["authenticated", "admin"]) +def create_user(request: Request, username: str, password: str) -> UserSchema: user = User( username=username, hashed_password=get_password_hash(password), disabled=False ) diff --git a/backend/main.py b/backend/main.py index 078083938..d2f016406 100644 --- a/backend/main.py +++ b/backend/main.py @@ -3,10 +3,12 @@ import alembic.config from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi_pagination import add_pagination +from starlette.middleware.authentication import AuthenticationMiddleware from config import DEV_PORT, DEV_HOST from endpoints import search, platform, rom, identity, scan # noqa from utils.socket import socket_app +from utils.auth import BasicAuthBackend app = FastAPI() app.add_middleware( @@ -16,10 +18,14 @@ app.add_middleware( allow_methods=["*"], allow_headers=["*"], ) -app.include_router(search.router) +app.add_middleware( + AuthenticationMiddleware, + backend=BasicAuthBackend(), +) +app.include_router(identity.router) app.include_router(platform.router) app.include_router(rom.router) -app.include_router(identity.router) +app.include_router(search.router) add_pagination(app) app.mount("/ws", socket_app) diff --git a/backend/models/user.py b/backend/models/user.py index 1c82566b3..309a97ec5 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -1,8 +1,8 @@ from sqlalchemy import Column, String, Boolean, Integer - +from starlette.authentication import SimpleUser from .base import BaseModel -class User(BaseModel): +class User(SimpleUser, BaseModel): __tablename__ = "users" id = Column(Integer(), primary_key=True, autoincrement=True) username: str = Column(String(length=255), unique=True, index=True) diff --git a/backend/utils/auth.py b/backend/utils/auth.py index 3b4d774b1..ab715a26a 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -1,20 +1,21 @@ +import base64 +import binascii from typing import Annotated from datetime import datetime, timedelta -from fastapi import Depends, HTTPException, status, Request +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext +from starlette.authentication import ( + AuthCredentials, + AuthenticationBackend, + AuthenticationError, +) +from starlette.requests import HTTPConnection from handler import dbh from models.user import User -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "9b9da8bfd88822ad708530bb36e61d02c130a74de7a8e84d5f456bf6fee5c518" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) @@ -28,49 +29,55 @@ def authenticate_user(username: str, password: str): user = dbh.get_user(username) if not user: return False - + if not verify_password(password, user.hashed_password): return False - + return user +# 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") + + def create_access_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=15) - + to_encode.update({"exp": expire}) - + return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) -async def get_current_user(request: Request): - authentication_exception = HTTPException( - status_code=status.HTTP_302_FOUND, - detail="Not authenticated", - headers={"Location": "/login"}, +async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, ) - token = request.cookies.get('access_token') - if token is None: - raise authentication_exception - try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: - raise authentication_exception + raise credentials_exception except JWTError: - raise authentication_exception - + raise credentials_exception + user = dbh.get_user(username) if user is None: - raise authentication_exception - + raise credentials_exception + return user @@ -79,5 +86,34 @@ async def get_current_active_user( ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") - + return current_user + + +# Session based authentication + + +class BasicAuthBackend(AuthenticationBackend): + async def authenticate(self, conn: HTTPConnection): + if "Authorization" not in conn.headers: + return + + auth = conn.headers["Authorization"] + try: + scheme, credentials = auth.split() + if scheme.lower() != "basic": + return + decoded = base64.b64decode(credentials).decode("ascii") + except (ValueError, UnicodeDecodeError, binascii.Error): + raise AuthenticationError("Invalid basic auth credentials") + + username, _, password = decoded.partition(":") + user = authenticate_user(username, password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Authorization"}, + ) + + return AuthCredentials(["authenticated"]), user From b2ca819c161e9913a81d13ed5de338b8cb83fd27 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Aug 2023 09:58:51 -0400 Subject: [PATCH 005/164] 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", + } + }) +}