Coverage for opt/mealie/lib/python3.12/site-packages/mealie/routes/users/_helpers.py: 19%

22 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-11-25 17:29 +0000

1from fastapi import HTTPException, status 1a

2from pydantic import UUID4 1a

3 

4from mealie.schema.response.responses import ErrorResponse 1a

5from mealie.schema.user.user import PrivateUser, UserBase 1a

6 

7permission_attrs = ["can_invite", "can_manage", "can_manage_household", "can_organize", "admin"] 1a

8 

9 

10def _assert_non_admin_user_change_allowed(user_id: UUID4, current_user: PrivateUser, new_data: UserBase): 1a

11 if current_user.id != user_id: 

12 # User is trying to edit another user 

13 raise HTTPException(status.HTTP_403_FORBIDDEN, ErrorResponse.respond("User cannot edit other users")) 

14 

15 if any(getattr(current_user, p) != getattr(new_data, p) for p in permission_attrs): 

16 # User is trying to change their own permissions 

17 raise HTTPException( 

18 status.HTTP_403_FORBIDDEN, 

19 ErrorResponse.respond("User cannot change their own permissions"), 

20 ) 

21 

22 if current_user.group != new_data.group: 

23 # prevent a regular user from changing their group 

24 raise HTTPException( 

25 status.HTTP_403_FORBIDDEN, ErrorResponse.respond("User doesn't have permission to change their group") 

26 ) 

27 

28 if current_user.household != new_data.household: 

29 # prevent a regular user from changing their household 

30 raise HTTPException( 

31 status.HTTP_403_FORBIDDEN, 

32 ErrorResponse.respond("User doesn't have permission to change their household"), 

33 ) 

34 

35 

36def assert_user_change_allowed(user_id: UUID4, current_user: PrivateUser, new_data: UserBase): 1a

37 if not current_user.admin: 

38 _assert_non_admin_user_change_allowed(user_id, current_user, new_data) 

39 return 

40 

41 if current_user.id != user_id: 

42 raise HTTPException(status.HTTP_403_FORBIDDEN, ErrorResponse.respond("Use the Admin API to update other users")) 

43 

44 # Admin is trying to edit themselves 

45 if any(getattr(current_user, p) != getattr(new_data, p) for p in permission_attrs): 

46 # prevent an admin from excalating their own permissions 

47 raise HTTPException( 

48 status.HTTP_403_FORBIDDEN, ErrorResponse.respond("Admins can't change their own permissions") 

49 )