Example #1
0
def assign_permissions_to_user(user, permissions=None):
    """
    Assign a specified user a given set of permissions.

    :param user: The user to assign the permissions
    :param permissions: A dictionary of permissions, with the permission name <app_label>.<action>_<model> as the key and constraints as values
    """
    if permissions is None:
        permissions = {}
    permissions_list = []
    for permission_name, constraints in permissions.items():
        try:
            object_type, action = resolve_permission_ct(permission_name)
            # TODO: Merge multiple actions into a single ObjectPermission per content type
            obj_perm = ObjectPermission(name=permission_name,
                                        actions=[action],
                                        constraints=constraints)
            obj_perm.save()
            obj_perm.users.add(user)
            obj_perm.object_types.add(object_type)
            permissions_list.append(permission_name)
        except ValueError:
            logging.error(
                f"Invalid permission name: '{permission_name}'. Permissions must be in the form "
                "<app>.<action>_<model>. (Example: dcim.add_site)")
    if permissions_list:
        logger.debug(
            f"Assigned permissions to remotely-authenticated user {user}: {permissions_list}"
        )
Example #2
0
 def add_permissions(self, *names):
     """
     Assign a set of permissions to the test user. Accepts permission names in the form <app>.<action>_<model>.
     """
     for name in names:
         ct, action = resolve_permission_ct(name)
         obj_perm = ObjectPermission(name=name, actions=[action])
         obj_perm.save()
         obj_perm.users.add(self.user)
         obj_perm.object_types.add(ct)