diff --git a/api/views/views.py b/api/views/views.py index 376d9d7f..cd3a40bd 100644 --- a/api/views/views.py +++ b/api/views/views.py @@ -309,22 +309,36 @@ class AbstractModelShareAPIView(AbstractAPIView): raise ValueError("Shared user list must not be empty!") new_teams = content.get("teams", []) + self.__process_user_sharing(new_users, obj) + self.__process_team_sharing(new_teams, obj) + + return True + + def __process_user_sharing(self, user_list: list, obj): + """ Processes API sharing for user payload + + Args: + user_list (list): A list of users to share the obj with + obj (BaseObject): The shareable object + + Returns: + + """ # Eliminate duplicates - new_users = list(dict.fromkeys(new_users)) - new_teams = list(dict.fromkeys(new_teams)) + new_users = list(dict.fromkeys(user_list)) # Make sure each of these names exist as a user new_users_objs = [] for user in new_users: - new_users_objs.append(User.objects.get(username=user)) - - # Make sure each of these names exist as a user - new_teams_objs = [] - for team_name in new_teams: - new_teams_objs.append(Team.objects.get(name=team_name)) + try: + user_obj = User.objects.get(username=user) + except User.DoesNotExist: + raise AssertionError(f"User with username {user} does not exist") + new_users_objs.append(user_obj) if self.user.is_default_group_only(): # Default only users are not allowed to remove other users from having access. They can only add new ones! + # So we need to keep the ones that already have access from being removed! new_users_to_be_added = User.objects.filter( username__in=new_users ).exclude( @@ -332,6 +346,33 @@ class AbstractModelShareAPIView(AbstractAPIView): ) new_users_objs = obj.shared_users.union(new_users_to_be_added) + obj.share_with_user_list(new_users_objs) + + def __process_team_sharing(self, team_list: list, obj): + """ Processes API sharing for team payload + + Args: + team_list (list): A list of teams to share the obj with + obj (BaseObject): The shareable object + + Returns: + + """ + # Eliminate duplicates + new_teams = list(dict.fromkeys(team_list)) + + # Make sure each of these names exist as a team + new_teams_objs = [] + for team_name in new_teams: + try: + team_obj = Team.objects.get(name=team_name) + except Team.DoesNotExist: + raise AssertionError(f"Team {team_name} does not exist!") + new_teams_objs.append(team_obj) + + if self.user.is_default_group_only(): + # Default only users are not allowed to remove other users from having access. They can only add new ones! + # So we need to keep the ones that already have access from being removed! new_teams_to_be_added = Team.objects.filter( name__in=new_teams ).exclude( @@ -339,10 +380,7 @@ class AbstractModelShareAPIView(AbstractAPIView): ) new_teams_objs = obj.shared_teams.union(new_teams_to_be_added) - obj.share_with_user_list(new_users_objs) obj.share_with_team_list(new_teams_objs) - return True - class InterventionAPIShareView(AbstractModelShareAPIView): model = Intervention