diff --git a/training/api/api_v1/certificates.py b/training/api/api_v1/certificates.py index 77bc923e..e1335a52 100644 --- a/training/api/api_v1/certificates.py +++ b/training/api/api_v1/certificates.py @@ -1,4 +1,4 @@ -from typing import List, Any +from typing import List, Any, Dict from fastapi import APIRouter, status, HTTPException, Depends, Response from training.schemas import UserCertificate, CertificateType, CertificateListValue from training.repositories import CertificateRepository @@ -52,7 +52,7 @@ def get_certificate_by_type_and_id( ): pdf_bytes = None filename = '' - is_admin_user = is_admin(user["roles"]) + is_admin_user = is_admin(user) user_id = user["id"] if (certType == CertificateType.QUIZ.value): @@ -97,8 +97,10 @@ def verify_certificate_is_valid(cert: object, user_id: int, is_admin_user: bool) raise HTTPException(status_code=401, detail="Not Authorized") -def is_admin(user_roles: List[str]): - if not user_roles: # Handle None or empty list +def is_admin(user: Dict[str, List[str]]) -> bool: + # Ensure that 'roles' is in the user dictionary and is a list + if 'roles' not in user or not isinstance(user['roles'], list): return False - return 'Admin' in user_roles + # Normalize roles to avoid case sensitivity issues + return 'Admin' in user['roles'] diff --git a/training/tests/test_api_certificates.py b/training/tests/test_api_certificates.py index de7e9fcd..d102d3da 100644 --- a/training/tests/test_api_certificates.py +++ b/training/tests/test_api_certificates.py @@ -258,20 +258,25 @@ def test_verify_certificate_is_valid_admin_user(self): def test_is_admin_with_admin_role(self): """Test when 'Admin' is in the roles list.""" - user_roles = ["User", "Admin", "Editor"] - assert is_admin(user_roles) is True + user = {"roles": ["User", "Admin", "Editor"]} + assert is_admin(user) is True def test_is_admin_without_admin_role(self): """Test when 'Admin' is not in the roles list.""" - user_roles = ["User", "Editor"] - assert is_admin(user_roles) is False + user = {"roles": ["User", "Editor"]} + assert is_admin(user) is False - def test_is_admin_empty_list(self): + def test_is_admin_empty_roles(self): """Test when the roles list is empty.""" - user_roles = [] - assert is_admin(user_roles) is False + user = {"roles": []} + assert is_admin(user) is False - def test_is_admin_none(self): + def test_is_admin_roles_is_none(self): """Test when the roles list is None.""" - user_roles = None - assert is_admin(user_roles) is False + user = {"roles": None} + assert is_admin(user) is False + + def test_is_admin_roles_key_missing(self): + """Test when the roles key is missing from the dictionary.""" + user = {} + assert is_admin(user) is False