change(python): rework session timing

Previously, we were just relying on the cookie expiration
for sessions to expire. We were not cleaning up Session
records either.

Rework timing to depend on an AURREMEMBER cookie which is
now emitted on login during BasicAuthBackend processing.

If the SID does still have a session but it's expired,
we now delete the session record before returning.

Otherwise, we update the session's LastUpdateTS to
the current time.

In addition, stored the unauthenticated result value
in a variable to reduce redundancy.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-12-04 02:12:20 -08:00
parent f8bef16d32
commit 8501bba0ac
No known key found for this signature in database
GPG key ID: F7E46DED420788F3
5 changed files with 50 additions and 24 deletions

View file

@ -6,7 +6,7 @@ import pytest
from fastapi import HTTPException
from sqlalchemy.exc import IntegrityError
from aurweb import db
from aurweb import config, db
from aurweb.auth import AnonymousUser, BasicAuthBackend, account_type_required, auth_required
from aurweb.models.account_type import USER, USER_ID
from aurweb.models.session import Session
@ -76,6 +76,28 @@ async def test_basic_auth_backend(user: User, backend: BasicAuthBackend):
assert result == user
@pytest.mark.asyncio
async def test_expired_session(backend: BasicAuthBackend, user: User):
""" Login, expire the session manually, then authenticate. """
# First, build a Request with a logged in user.
request = Request()
request.user = user
sid = request.user.login(Request(), "testPassword")
request.cookies["AURSID"] = sid
# Set Session.LastUpdateTS to 20 seconds expired.
timeout = config.getint("options", "login_timeout")
now_ts = int(datetime.utcnow().timestamp())
with db.begin():
request.user.session.LastUpdateTS = now_ts - timeout - 20
# Run through authentication backend and get the session
# deleted due to its expiration.
await backend.authenticate(request)
session = db.query(Session).filter(Session.SessionID == sid).first()
assert session is None
@pytest.mark.asyncio
async def test_auth_required_redirection_bad_referrer():
# Create a fake route function which can be wrapped by auth_required.