prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  500 error returned when permission does not exist
  We should return 400 Bad request response.
  
  Failing unit test: https://github.com/genialis/resolwe/pull/309
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `resolwe/permissions/utils.py`
  Content:
  ```
  1 """.. Ignore pydocstyle D400.
  2 
  3 =================
  4 Permissions utils
  5 =================
  6 
  7 .. autofunction:: copy_permissions
  8 
  9 """
  10 from __future__ import absolute_import, division, print_function, unicode_literals
  11 
  12 import copy
  13 
  14 from django.contrib.auth import get_user_model
  15 from django.contrib.auth.models import AnonymousUser, Group
  16 from django.contrib.contenttypes.models import ContentType
  17 
  18 from guardian.models import GroupObjectPermission, UserObjectPermission
  19 from guardian.shortcuts import assign_perm, remove_perm
  20 from rest_framework import exceptions
  21 
  22 
  23 def copy_permissions(src_obj, dest_obj):
  24     """Copy permissions form ``src_obj`` to ``dest_obj``."""
  25     src_obj_ctype = ContentType.objects.get_for_model(src_obj)
  26     dest_obj_ctype = ContentType.objects.get_for_model(dest_obj)
  27 
  28     if src_obj_ctype != dest_obj_ctype:
  29         raise AssertionError('Content types of source and destination objects are not equal.')
  30 
  31     for perm in UserObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
  32         assign_perm(perm.permission.codename, perm.user, dest_obj)
  33     for perm in GroupObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
  34         assign_perm(perm.permission.codename, perm.group, dest_obj)
  35 
  36 
  37 def fetch_user(query):
  38     """Get user by ``pk`` or ``username``. Return ``None`` if doesn't exist."""
  39     user_filter = {'pk': query} if query.isdigit() else {'username': query}
  40     return get_user_model().objects.get(**user_filter)
  41 
  42 
  43 def fetch_group(query):
  44     """Get group by ``pk`` or ``name``. Return ``None`` if doesn't exist."""
  45     group_filter = {'pk': query} if query.isdigit() else {'name': query}
  46     return Group.objects.get(**group_filter)
  47 
  48 
  49 def check_owner_permission(payload, allow_user_owner):
  50     """Raise ``PermissionDenied``if ``owner`` found in ``data``."""
  51     for entity_type in ['users', 'groups']:
  52         for perm_type in ['add', 'remove']:
  53             for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
  54                 if 'owner' in perms:
  55                     if entity_type == 'users' and allow_user_owner:
  56                         continue
  57 
  58                     if entity_type == 'groups':
  59                         raise exceptions.ParseError("Owner permission cannot be assigned to a group")
  60 
  61                     raise exceptions.PermissionDenied("Only owners can grant/revoke owner permission")
  62 
  63 
  64 def check_public_permissions(payload):
  65     """Raise ``PermissionDenied`` if public permissions are too open."""
  66     allowed_public_permissions = ['view', 'add', 'download']
  67     for perm_type in ['add', 'remove']:
  68         for perm in payload.get('public', {}).get(perm_type, []):
  69             if perm not in allowed_public_permissions:
  70                 raise exceptions.PermissionDenied("Permissions for public users are too open")
  71 
  72 
  73 def check_user_permissions(payload, user_pk):
  74     """Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."""
  75     for perm_type in ['add', 'remove']:
  76         user_pks = payload.get('users', {}).get(perm_type, {}).keys()
  77         if user_pk in user_pks:
  78             raise exceptions.PermissionDenied("You cannot change your own permissions")
  79 
  80 
  81 def remove_permission(payload, permission):
  82     """Remove all occurrences of ``permission`` from ``payload``."""
  83     payload = copy.deepcopy(payload)
  84 
  85     for entity_type in ['users', 'groups']:
  86         for perm_type in ['add', 'remove']:
  87             for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
  88                 if permission in perms:
  89                     perms.remove(permission)
  90 
  91     for perm_type in ['add', 'remove']:
  92         perms = payload.get('public', {}).get(perm_type, [])
  93         if permission in perms:
  94             perms.remove(permission)
  95 
  96     return payload
  97 
  98 
  99 def update_permission(obj, data):
  100     """Update object permissions."""
  101     content_type = ContentType.objects.get_for_model(obj)
  102     full_permissions = list(zip(*obj._meta.permissions))[0]  # pylint: disable=protected-access
  103 
  104     def set_permissions(entity_type, perm_type):
  105         """Set object permissions."""
  106         perm_func = assign_perm if perm_type == 'add' else remove_perm
  107         fetch_fn = fetch_user if entity_type == 'users' else fetch_group
  108 
  109         for entity_id in data.get(entity_type, {}).get(perm_type, []):
  110             entity = fetch_fn(entity_id)
  111             if entity:
  112                 perms = data[entity_type][perm_type][entity_id]
  113                 if perms == u'ALL':
  114                     perms = full_permissions
  115                 for perm in perms:
  116                     perm_func('{}_{}'.format(perm.lower(), content_type), entity, obj)
  117 
  118     set_permissions('users', 'add')
  119     set_permissions('users', 'remove')
  120     set_permissions('groups', 'add')
  121     set_permissions('groups', 'remove')
  122 
  123     def set_public_permissions(perm_type):
  124         """Set public permissions."""
  125         perm_func = assign_perm if perm_type == 'add' else remove_perm
  126         user = AnonymousUser()
  127         perms = data.get('public', {}).get(perm_type, [])
  128         if perms == u'ALL':
  129             perms = full_permissions
  130         for perm in perms:
  131             perm_func('{}_{}'.format(perm.lower(), content_type), user, obj)
  132 
  133     set_public_permissions('add')
  134     set_public_permissions('remove')
  135 
  136 
  137 def assign_contributor_permissions(obj):
  138     """Assign all permissions to object's contributor."""
  139     for permission in list(zip(*obj._meta.permissions))[0]:  # pylint: disable=protected-access
  140         assign_perm(permission, obj.contributor, obj)
  141
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/resolwe/permissions/utils.py b/resolwe/permissions/utils.py
  --- a/resolwe/permissions/utils.py
  +++ b/resolwe/permissions/utils.py
  @@ -14,6 +14,7 @@
   from django.contrib.auth import get_user_model
   from django.contrib.auth.models import AnonymousUser, Group
   from django.contrib.contenttypes.models import ContentType
  +from django.db import transaction
   
   from guardian.models import GroupObjectPermission, UserObjectPermission
   from guardian.shortcuts import assign_perm, remove_perm
  @@ -101,6 +102,35 @@
       content_type = ContentType.objects.get_for_model(obj)
       full_permissions = list(zip(*obj._meta.permissions))[0]  # pylint: disable=protected-access
   
  +    def apply_perm(perm_func, perms, entity):
  +        """Apply permissions using given ``perm_func``.
  +
  +        ``perm_func`` is intended to be ``assign_perms`` or
  +        ``remove_perms`` shortcut function from ``django-guardian``, but
  +        can be any function that accepts permission codename,
  +        user/group and object parameters (in this order).
  +
  +        If given permission does not exist, ``exceptions.ParseError`` is
  +        raised.
  +
  +        "ALL" passed as ``perms`` parameter, will call ``perm_function``
  +        with ``full_permissions`` list.
  +
  +        :param func perm_func: Permissions function to be applied
  +        :param list params: list of params to be allpied
  +        :param entity: user or group to be passed to ``perm_func``
  +        :type entity: `~django.contrib.auth.models.User` or
  +            `~django.contrib.auth.models.Group`
  +
  +        """
  +        if perms == u'ALL':
  +            perms = full_permissions
  +        for perm in perms:
  +            perm_codename = '{}_{}'.format(perm.lower(), content_type)
  +            if perm_codename not in full_permissions:
  +                raise exceptions.ParseError("Unknown permission: {}".format(perm))
  +            perm_func(perm_codename, entity, obj)
  +
       def set_permissions(entity_type, perm_type):
           """Set object permissions."""
           perm_func = assign_perm if perm_type == 'add' else remove_perm
  @@ -110,28 +140,22 @@
               entity = fetch_fn(entity_id)
               if entity:
                   perms = data[entity_type][perm_type][entity_id]
  -                if perms == u'ALL':
  -                    perms = full_permissions
  -                for perm in perms:
  -                    perm_func('{}_{}'.format(perm.lower(), content_type), entity, obj)
  -
  -    set_permissions('users', 'add')
  -    set_permissions('users', 'remove')
  -    set_permissions('groups', 'add')
  -    set_permissions('groups', 'remove')
  +                apply_perm(perm_func, perms, entity)
   
       def set_public_permissions(perm_type):
           """Set public permissions."""
           perm_func = assign_perm if perm_type == 'add' else remove_perm
           user = AnonymousUser()
           perms = data.get('public', {}).get(perm_type, [])
  -        if perms == u'ALL':
  -            perms = full_permissions
  -        for perm in perms:
  -            perm_func('{}_{}'.format(perm.lower(), content_type), user, obj)
  -
  -    set_public_permissions('add')
  -    set_public_permissions('remove')
  +        apply_perm(perm_func, perms, user)
  +
  +    with transaction.atomic():
  +        set_permissions('users', 'add')
  +        set_permissions('users', 'remove')
  +        set_permissions('groups', 'add')
  +        set_permissions('groups', 'remove')
  +        set_public_permissions('add')
  +        set_public_permissions('remove')
   
   
   def assign_contributor_permissions(obj):
  
verification_info: {"golden_diff": "diff --git a/resolwe/permissions/utils.py b/resolwe/permissions/utils.py\n--- a/resolwe/permissions/utils.py\n+++ b/resolwe/permissions/utils.py\n@@ -14,6 +14,7 @@\n from django.contrib.auth import get_user_model\n from django.contrib.auth.models import AnonymousUser, Group\n from django.contrib.contenttypes.models import ContentType\n+from django.db import transaction\n \n from guardian.models import GroupObjectPermission, UserObjectPermission\n from guardian.shortcuts import assign_perm, remove_perm\n@@ -101,6 +102,35 @@\n     content_type = ContentType.objects.get_for_model(obj)\n     full_permissions = list(zip(*obj._meta.permissions))[0]  # pylint: disable=protected-access\n \n+    def apply_perm(perm_func, perms, entity):\n+        \"\"\"Apply permissions using given ``perm_func``.\n+\n+        ``perm_func`` is intended to be ``assign_perms`` or\n+        ``remove_perms`` shortcut function from ``django-guardian``, but\n+        can be any function that accepts permission codename,\n+        user/group and object parameters (in this order).\n+\n+        If given permission does not exist, ``exceptions.ParseError`` is\n+        raised.\n+\n+        \"ALL\" passed as ``perms`` parameter, will call ``perm_function``\n+        with ``full_permissions`` list.\n+\n+        :param func perm_func: Permissions function to be applied\n+        :param list params: list of params to be allpied\n+        :param entity: user or group to be passed to ``perm_func``\n+        :type entity: `~django.contrib.auth.models.User` or\n+            `~django.contrib.auth.models.Group`\n+\n+        \"\"\"\n+        if perms == u'ALL':\n+            perms = full_permissions\n+        for perm in perms:\n+            perm_codename = '{}_{}'.format(perm.lower(), content_type)\n+            if perm_codename not in full_permissions:\n+                raise exceptions.ParseError(\"Unknown permission: {}\".format(perm))\n+            perm_func(perm_codename, entity, obj)\n+\n     def set_permissions(entity_type, perm_type):\n         \"\"\"Set object permissions.\"\"\"\n         perm_func = assign_perm if perm_type == 'add' else remove_perm\n@@ -110,28 +140,22 @@\n             entity = fetch_fn(entity_id)\n             if entity:\n                 perms = data[entity_type][perm_type][entity_id]\n-                if perms == u'ALL':\n-                    perms = full_permissions\n-                for perm in perms:\n-                    perm_func('{}_{}'.format(perm.lower(), content_type), entity, obj)\n-\n-    set_permissions('users', 'add')\n-    set_permissions('users', 'remove')\n-    set_permissions('groups', 'add')\n-    set_permissions('groups', 'remove')\n+                apply_perm(perm_func, perms, entity)\n \n     def set_public_permissions(perm_type):\n         \"\"\"Set public permissions.\"\"\"\n         perm_func = assign_perm if perm_type == 'add' else remove_perm\n         user = AnonymousUser()\n         perms = data.get('public', {}).get(perm_type, [])\n-        if perms == u'ALL':\n-            perms = full_permissions\n-        for perm in perms:\n-            perm_func('{}_{}'.format(perm.lower(), content_type), user, obj)\n-\n-    set_public_permissions('add')\n-    set_public_permissions('remove')\n+        apply_perm(perm_func, perms, user)\n+\n+    with transaction.atomic():\n+        set_permissions('users', 'add')\n+        set_permissions('users', 'remove')\n+        set_permissions('groups', 'add')\n+        set_permissions('groups', 'remove')\n+        set_public_permissions('add')\n+        set_public_permissions('remove')\n \n \n def assign_contributor_permissions(obj):\n", "issue": "500 error returned when permission does not exist\nWe should return 400 Bad request response.\r\n\r\nFailing unit test: https://github.com/genialis/resolwe/pull/309\n", "before_files": [{"content": "\"\"\".. Ignore pydocstyle D400.\n\n=================\nPermissions utils\n=================\n\n.. autofunction:: copy_permissions\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport copy\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import AnonymousUser, Group\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom guardian.models import GroupObjectPermission, UserObjectPermission\nfrom guardian.shortcuts import assign_perm, remove_perm\nfrom rest_framework import exceptions\n\n\ndef copy_permissions(src_obj, dest_obj):\n    \"\"\"Copy permissions form ``src_obj`` to ``dest_obj``.\"\"\"\n    src_obj_ctype = ContentType.objects.get_for_model(src_obj)\n    dest_obj_ctype = ContentType.objects.get_for_model(dest_obj)\n\n    if src_obj_ctype != dest_obj_ctype:\n        raise AssertionError('Content types of source and destination objects are not equal.')\n\n    for perm in UserObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):\n        assign_perm(perm.permission.codename, perm.user, dest_obj)\n    for perm in GroupObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):\n        assign_perm(perm.permission.codename, perm.group, dest_obj)\n\n\ndef fetch_user(query):\n    \"\"\"Get user by ``pk`` or ``username``. Return ``None`` if doesn't exist.\"\"\"\n    user_filter = {'pk': query} if query.isdigit() else {'username': query}\n    return get_user_model().objects.get(**user_filter)\n\n\ndef fetch_group(query):\n    \"\"\"Get group by ``pk`` or ``name``. Return ``None`` if doesn't exist.\"\"\"\n    group_filter = {'pk': query} if query.isdigit() else {'name': query}\n    return Group.objects.get(**group_filter)\n\n\ndef check_owner_permission(payload, allow_user_owner):\n    \"\"\"Raise ``PermissionDenied``if ``owner`` found in ``data``.\"\"\"\n    for entity_type in ['users', 'groups']:\n        for perm_type in ['add', 'remove']:\n            for perms in payload.get(entity_type, {}).get(perm_type, {}).values():\n                if 'owner' in perms:\n                    if entity_type == 'users' and allow_user_owner:\n                        continue\n\n                    if entity_type == 'groups':\n                        raise exceptions.ParseError(\"Owner permission cannot be assigned to a group\")\n\n                    raise exceptions.PermissionDenied(\"Only owners can grant/revoke owner permission\")\n\n\ndef check_public_permissions(payload):\n    \"\"\"Raise ``PermissionDenied`` if public permissions are too open.\"\"\"\n    allowed_public_permissions = ['view', 'add', 'download']\n    for perm_type in ['add', 'remove']:\n        for perm in payload.get('public', {}).get(perm_type, []):\n            if perm not in allowed_public_permissions:\n                raise exceptions.PermissionDenied(\"Permissions for public users are too open\")\n\n\ndef check_user_permissions(payload, user_pk):\n    \"\"\"Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``.\"\"\"\n    for perm_type in ['add', 'remove']:\n        user_pks = payload.get('users', {}).get(perm_type, {}).keys()\n        if user_pk in user_pks:\n            raise exceptions.PermissionDenied(\"You cannot change your own permissions\")\n\n\ndef remove_permission(payload, permission):\n    \"\"\"Remove all occurrences of ``permission`` from ``payload``.\"\"\"\n    payload = copy.deepcopy(payload)\n\n    for entity_type in ['users', 'groups']:\n        for perm_type in ['add', 'remove']:\n            for perms in payload.get(entity_type, {}).get(perm_type, {}).values():\n                if permission in perms:\n                    perms.remove(permission)\n\n    for perm_type in ['add', 'remove']:\n        perms = payload.get('public', {}).get(perm_type, [])\n        if permission in perms:\n            perms.remove(permission)\n\n    return payload\n\n\ndef update_permission(obj, data):\n    \"\"\"Update object permissions.\"\"\"\n    content_type = ContentType.objects.get_for_model(obj)\n    full_permissions = list(zip(*obj._meta.permissions))[0]  # pylint: disable=protected-access\n\n    def set_permissions(entity_type, perm_type):\n        \"\"\"Set object permissions.\"\"\"\n        perm_func = assign_perm if perm_type == 'add' else remove_perm\n        fetch_fn = fetch_user if entity_type == 'users' else fetch_group\n\n        for entity_id in data.get(entity_type, {}).get(perm_type, []):\n            entity = fetch_fn(entity_id)\n            if entity:\n                perms = data[entity_type][perm_type][entity_id]\n                if perms == u'ALL':\n                    perms = full_permissions\n                for perm in perms:\n                    perm_func('{}_{}'.format(perm.lower(), content_type), entity, obj)\n\n    set_permissions('users', 'add')\n    set_permissions('users', 'remove')\n    set_permissions('groups', 'add')\n    set_permissions('groups', 'remove')\n\n    def set_public_permissions(perm_type):\n        \"\"\"Set public permissions.\"\"\"\n        perm_func = assign_perm if perm_type == 'add' else remove_perm\n        user = AnonymousUser()\n        perms = data.get('public', {}).get(perm_type, [])\n        if perms == u'ALL':\n            perms = full_permissions\n        for perm in perms:\n            perm_func('{}_{}'.format(perm.lower(), content_type), user, obj)\n\n    set_public_permissions('add')\n    set_public_permissions('remove')\n\n\ndef assign_contributor_permissions(obj):\n    \"\"\"Assign all permissions to object's contributor.\"\"\"\n    for permission in list(zip(*obj._meta.permissions))[0]:  # pylint: disable=protected-access\n        assign_perm(permission, obj.contributor, obj)\n", "path": "resolwe/permissions/utils.py"}], "after_files": [{"content": "\"\"\".. Ignore pydocstyle D400.\n\n=================\nPermissions utils\n=================\n\n.. autofunction:: copy_permissions\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport copy\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import AnonymousUser, Group\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import transaction\n\nfrom guardian.models import GroupObjectPermission, UserObjectPermission\nfrom guardian.shortcuts import assign_perm, remove_perm\nfrom rest_framework import exceptions\n\n\ndef copy_permissions(src_obj, dest_obj):\n    \"\"\"Copy permissions form ``src_obj`` to ``dest_obj``.\"\"\"\n    src_obj_ctype = ContentType.objects.get_for_model(src_obj)\n    dest_obj_ctype = ContentType.objects.get_for_model(dest_obj)\n\n    if src_obj_ctype != dest_obj_ctype:\n        raise AssertionError('Content types of source and destination objects are not equal.')\n\n    for perm in UserObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):\n        assign_perm(perm.permission.codename, perm.user, dest_obj)\n    for perm in GroupObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):\n        assign_perm(perm.permission.codename, perm.group, dest_obj)\n\n\ndef fetch_user(query):\n    \"\"\"Get user by ``pk`` or ``username``. Return ``None`` if doesn't exist.\"\"\"\n    user_filter = {'pk': query} if query.isdigit() else {'username': query}\n    return get_user_model().objects.get(**user_filter)\n\n\ndef fetch_group(query):\n    \"\"\"Get group by ``pk`` or ``name``. Return ``None`` if doesn't exist.\"\"\"\n    group_filter = {'pk': query} if query.isdigit() else {'name': query}\n    return Group.objects.get(**group_filter)\n\n\ndef check_owner_permission(payload, allow_user_owner):\n    \"\"\"Raise ``PermissionDenied``if ``owner`` found in ``data``.\"\"\"\n    for entity_type in ['users', 'groups']:\n        for perm_type in ['add', 'remove']:\n            for perms in payload.get(entity_type, {}).get(perm_type, {}).values():\n                if 'owner' in perms:\n                    if entity_type == 'users' and allow_user_owner:\n                        continue\n\n                    if entity_type == 'groups':\n                        raise exceptions.ParseError(\"Owner permission cannot be assigned to a group\")\n\n                    raise exceptions.PermissionDenied(\"Only owners can grant/revoke owner permission\")\n\n\ndef check_public_permissions(payload):\n    \"\"\"Raise ``PermissionDenied`` if public permissions are too open.\"\"\"\n    allowed_public_permissions = ['view', 'add', 'download']\n    for perm_type in ['add', 'remove']:\n        for perm in payload.get('public', {}).get(perm_type, []):\n            if perm not in allowed_public_permissions:\n                raise exceptions.PermissionDenied(\"Permissions for public users are too open\")\n\n\ndef check_user_permissions(payload, user_pk):\n    \"\"\"Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``.\"\"\"\n    for perm_type in ['add', 'remove']:\n        user_pks = payload.get('users', {}).get(perm_type, {}).keys()\n        if user_pk in user_pks:\n            raise exceptions.PermissionDenied(\"You cannot change your own permissions\")\n\n\ndef remove_permission(payload, permission):\n    \"\"\"Remove all occurrences of ``permission`` from ``payload``.\"\"\"\n    payload = copy.deepcopy(payload)\n\n    for entity_type in ['users', 'groups']:\n        for perm_type in ['add', 'remove']:\n            for perms in payload.get(entity_type, {}).get(perm_type, {}).values():\n                if permission in perms:\n                    perms.remove(permission)\n\n    for perm_type in ['add', 'remove']:\n        perms = payload.get('public', {}).get(perm_type, [])\n        if permission in perms:\n            perms.remove(permission)\n\n    return payload\n\n\ndef update_permission(obj, data):\n    \"\"\"Update object permissions.\"\"\"\n    content_type = ContentType.objects.get_for_model(obj)\n    full_permissions = list(zip(*obj._meta.permissions))[0]  # pylint: disable=protected-access\n\n    def apply_perm(perm_func, perms, entity):\n        \"\"\"Apply permissions using given ``perm_func``.\n\n        ``perm_func`` is intended to be ``assign_perms`` or\n        ``remove_perms`` shortcut function from ``django-guardian``, but\n        can be any function that accepts permission codename,\n        user/group and object parameters (in this order).\n\n        If given permission does not exist, ``exceptions.ParseError`` is\n        raised.\n\n        \"ALL\" passed as ``perms`` parameter, will call ``perm_function``\n        with ``full_permissions`` list.\n\n        :param func perm_func: Permissions function to be applied\n        :param list params: list of params to be allpied\n        :param entity: user or group to be passed to ``perm_func``\n        :type entity: `~django.contrib.auth.models.User` or\n            `~django.contrib.auth.models.Group`\n\n        \"\"\"\n        if perms == u'ALL':\n            perms = full_permissions\n        for perm in perms:\n            perm_codename = '{}_{}'.format(perm.lower(), content_type)\n            if perm_codename not in full_permissions:\n                raise exceptions.ParseError(\"Unknown permission: {}\".format(perm))\n            perm_func(perm_codename, entity, obj)\n\n    def set_permissions(entity_type, perm_type):\n        \"\"\"Set object permissions.\"\"\"\n        perm_func = assign_perm if perm_type == 'add' else remove_perm\n        fetch_fn = fetch_user if entity_type == 'users' else fetch_group\n\n        for entity_id in data.get(entity_type, {}).get(perm_type, []):\n            entity = fetch_fn(entity_id)\n            if entity:\n                perms = data[entity_type][perm_type][entity_id]\n                apply_perm(perm_func, perms, entity)\n\n    def set_public_permissions(perm_type):\n        \"\"\"Set public permissions.\"\"\"\n        perm_func = assign_perm if perm_type == 'add' else remove_perm\n        user = AnonymousUser()\n        perms = data.get('public', {}).get(perm_type, [])\n        apply_perm(perm_func, perms, user)\n\n    with transaction.atomic():\n        set_permissions('users', 'add')\n        set_permissions('users', 'remove')\n        set_permissions('groups', 'add')\n        set_permissions('groups', 'remove')\n        set_public_permissions('add')\n        set_public_permissions('remove')\n\n\ndef assign_contributor_permissions(obj):\n    \"\"\"Assign all permissions to object's contributor.\"\"\"\n    for permission in list(zip(*obj._meta.permissions))[0]:  # pylint: disable=protected-access\n        assign_perm(permission, obj.contributor, obj)\n", "path": "resolwe/permissions/utils.py"}]}