Skip to content

Commit

Permalink
rework for when user object doesnt have role list.
Browse files Browse the repository at this point in the history
  • Loading branch information
john-labbate committed Aug 29, 2024
1 parent b0e44da commit bdcf8b5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
12 changes: 7 additions & 5 deletions training/api/api_v1/certificates.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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']
25 changes: 15 additions & 10 deletions training/tests/test_api_certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit bdcf8b5

Please sign in to comment.