From 228bc8fe7c3ea7cef66f00f1608b699d00838c43 Mon Sep 17 00:00:00 2001 From: Kevin Morris Date: Fri, 4 Jun 2021 23:09:38 -0700 Subject: [PATCH] fix aurweb.auth test coverage With mysqlclient, we no longer need to account for a user not existing when an ssh key is found. Signed-off-by: Kevin Morris --- aurweb/auth.py | 14 +++++++++----- test/test_auth.py | 7 ++++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/aurweb/auth.py b/aurweb/auth.py index a4ff2167..401ed6ae 100644 --- a/aurweb/auth.py +++ b/aurweb/auth.py @@ -4,7 +4,8 @@ from datetime import datetime from http import HTTPStatus from fastapi.responses import RedirectResponse -from starlette.authentication import AuthCredentials, AuthenticationBackend, AuthenticationError +from sqlalchemy import and_ +from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection import aurweb.config @@ -42,14 +43,17 @@ class BasicAuthBackend(AuthenticationBackend): now_ts = datetime.utcnow().timestamp() record = session.query(Session).filter( - Session.SessionID == sid, Session.LastUpdateTS >= now_ts).first() + and_(Session.SessionID == sid, + Session.LastUpdateTS >= now_ts)).first() + + # If no session with sid and a LastUpdateTS now or later exists. if not record: return None, AnonymousUser() + # At this point, we cannot have an invalid user if the record + # exists, due to ForeignKey constraints in the schema upheld + # by mysqlclient. user = session.query(User).filter(User.ID == record.UsersID).first() - if not user: - raise AuthenticationError(f"Invalid User ID: {record.UsersID}") - user.authenticated = True return AuthCredentials(["authenticated"]), user diff --git a/test/test_auth.py b/test/test_auth.py index 42eac040..05dd2020 100644 --- a/test/test_auth.py +++ b/test/test_auth.py @@ -2,7 +2,7 @@ from datetime import datetime import pytest -from starlette.authentication import AuthenticationError +from sqlalchemy.exc import IntegrityError import aurweb.config @@ -53,13 +53,13 @@ async def test_auth_backend_invalid_sid(): @pytest.mark.asyncio async def test_auth_backend_invalid_user_id(): + from aurweb.db import session + # Create a new session with a fake user id. now_ts = datetime.utcnow().timestamp() - db_backend = aurweb.config.get("database", "backend") with pytest.raises(IntegrityError): create(Session, UsersID=666, SessionID="realSession", LastUpdateTS=now_ts + 5) - session.rollback() @@ -70,6 +70,7 @@ async def test_basic_auth_backend(): now_ts = datetime.utcnow().timestamp() create(Session, UsersID=user.ID, SessionID="realSession", LastUpdateTS=now_ts + 5) + request.cookies["AURSID"] = "realSession" _, result = await backend.authenticate(request) assert result == user