fix: 500 error when sending unauthorized requests (#2639)

* fixed uncaught null token

* added tests
This commit is contained in:
Michael Genson 2023-10-15 19:48:15 -05:00 committed by GitHub
parent 5f0a9981f3
commit eba9ff00ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 2 deletions

View File

@ -76,7 +76,7 @@ async def try_get_current_user(
async def get_current_user(
request: Request, token: str = Depends(oauth2_scheme_soft_fail), session=Depends(generate_session)
request: Request, token: str | None = Depends(oauth2_scheme_soft_fail), session=Depends(generate_session)
) -> PrivateUser:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@ -86,6 +86,8 @@ async def get_current_user(
if token is None and "mealie.access_token" in request.cookies:
# Try extract from cookie
token = request.cookies.get("mealie.access_token", "")
else:
token = token or ""
try:
payload = jwt.decode(token, settings.SECRET, algorithms=[ALGORITHM])

View File

@ -1,12 +1,13 @@
import os
from fastapi.testclient import TestClient
import pytest
from fastapi.testclient import TestClient
from mealie.core.config import get_app_settings
from mealie.repos.repository_factory import AllRepositories
from mealie.services.user_services.user_service import UserService
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
@ -37,6 +38,13 @@ def test_user_token_refresh(api_client: TestClient, admin_user: TestUser):
assert response.status_code == 200
@pytest.mark.parametrize("use_token", [True, False], ids=["with token", "without token"])
def test_get_logged_in_user_invalid_token(api_client: TestClient, use_token: bool):
headers = {"Authorization": f"Bearer {random_string()}"} if use_token else {}
response = api_client.get(api_routes.users_self, headers=headers)
assert response.status_code == 401
def test_user_lockout_after_bad_attemps(api_client: TestClient, unique_user: TestUser, database: AllRepositories):
"""
if the user has more than 5 bad login attempts the user will be locked out for 4 hours