From 2209b09a9a41bfcdacee222bc994ba2f83e01bdf Mon Sep 17 00:00:00 2001 From: msramalho <19508417+msramalho@users.noreply.github.com> Date: Tue, 5 Nov 2024 11:41:07 +0000 Subject: [PATCH] missing tests for security --- src/tests/web/test_security.py | 22 ++++++++++++++++++++-- src/web/security.py | 13 +++++-------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/tests/web/test_security.py b/src/tests/web/test_security.py index 64fe4d4..f82874c 100644 --- a/src/tests/web/test_security.py +++ b/src/tests/web/test_security.py @@ -36,8 +36,26 @@ async def test_get_token_or_user_auth_with_user(): @pytest.mark.asyncio async def test_get_user_auth(m1): from web.security import get_user_auth - bad_user = HTTPAuthorizationCredentials(scheme="ipsum", credentials="valid-and-good") - assert await get_user_auth(bad_user) == "summer@example.com" + good_user = HTTPAuthorizationCredentials(scheme="ipsum", credentials="valid-and-good") + assert await get_user_auth(good_user) == "summer@example.com" + + +@patch("web.security.authenticate_user", return_value=(True, "summer@example.com")) +@pytest.mark.asyncio +async def test_get_active_user_auth_inactive(m1, db_session): + from web.security import get_active_user_auth + + # inactive at first + creds = HTTPAuthorizationCredentials(scheme="ipsum", credentials="valid-and-good") + with pytest.raises(HTTPException): + await get_active_user_auth(creds) + + from db import models + db_session.add(models.User(email="summer@example.com", is_active=True)) + db_session.commit() + assert await get_active_user_auth(creds) == "summer@example.com" + + @patch("web.security.secure_compare", return_value=False) diff --git a/src/web/security.py b/src/web/security.py index 141cd1b..224b86a 100644 --- a/src/web/security.py +++ b/src/web/security.py @@ -58,14 +58,11 @@ async def get_user_auth(credentials: HTTPAuthorizationCredentials = Depends(bear async def get_active_user_auth(credentials: HTTPAuthorizationCredentials = Depends(bearer_security)): # validates Bearer token and Active User status - try: - email = await get_user_auth(credentials) - with get_db() as db: - if crud.is_active_user(db, email): - return email - raise HTTPException(status_code=403, detail="User is not active") - except HTTPException as e: - raise e + email = await get_user_auth(credentials) + with get_db() as db: + if crud.is_active_user(db, email): + return email + raise HTTPException(status_code=403, detail="User is not active") def authenticate_user(access_token):