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 <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-06-04 23:09:38 -07:00
parent aecb649473
commit 228bc8fe7c
2 changed files with 13 additions and 8 deletions

View file

@ -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

View file

@ -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