prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Employment application requires Django login
  ## Test plan
  
  GIVEN the `/rest/v1/user/../request_organisation/` endpoint
  WHEN POSTing a request from outside of RSR
  AND the correct authentication details are provided
  THEN the request should be process accordingly, instead trying to authenticate through Django's auth system
  ## Issue description
  
  Just as for #2037, when posting a request for employment to the /rest/v1/user/request_organisation/ endpoint, a Django login is required, which is not the case for the rest of the API; an API key should be sufficient.
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `akvo/rest/views/user.py`
  Content:
  ```
  1 # -*- coding: utf-8 -*-
  2 """Akvo RSR is covered by the GNU Affero General Public License.
  3 
  4 See more details in the license.txt file located at the root folder of the Akvo RSR module.
  5 For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
  6 """
  7 
  8 from django.contrib.auth import get_user_model
  9 from django.db import IntegrityError
  10 from django.utils.translation import ugettext_lazy as _
  11 
  12 from rest_framework import status
  13 from rest_framework.decorators import api_view, permission_classes
  14 from rest_framework.exceptions import PermissionDenied
  15 from rest_framework.response import Response
  16 
  17 from ...rsr.models import Country, Employment, Organisation
  18 from ..viewsets import BaseRSRViewSet
  19 from ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer
  20 from ..serializers import UserSerializer, UserDetailsSerializer, UserPasswordSerializer
  21 
  22 
  23 class UserViewSet(BaseRSRViewSet):
  24 
  25     """User resource."""
  26 
  27     queryset = get_user_model().objects.select_related(
  28         'organisation',
  29         'organisation__primary_location',
  30         'organisation__primary_location__country',
  31         'organisation__primary_location__location_target',
  32         'organisation__primary_location__location_target__internal_org_ids',
  33     ).prefetch_related(
  34         'organisations',
  35         'organisations__primary_location',
  36         'organisations__primary_location__country',
  37         'organisations__primary_location__location_target',)
  38     serializer_class = UserSerializer
  39     filter_fields = ('username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff',
  40                      'is_admin')
  41 
  42 
  43 @api_view(['POST'])
  44 def change_password(request, pk=None):
  45     # Get the user, or return an error if the user does not exist
  46     try:
  47         user = get_user_model().objects.get(pk=pk)
  48     except get_user_model().DoesNotExist:
  49         return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)
  50 
  51     # Users are only allowed to edit their own details
  52     request_user = getattr(request, 'user', None)
  53     if not user == request_user:
  54         raise PermissionDenied()
  55 
  56     # Process request
  57     serializer = UserPasswordSerializer(data=request.DATA, instance=user)
  58     if serializer.is_valid():
  59         user.set_password(serializer.data['new_password2'])
  60         user.save()
  61         return Response({'status': 'password set'})
  62     else:
  63         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  64 
  65 
  66 @api_view(['POST'])
  67 def update_details(request, pk=None):
  68     # Get the user, or return an error if the user does not exist
  69     try:
  70         user = get_user_model().objects.get(pk=pk)
  71     except get_user_model().DoesNotExist:
  72         return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)
  73 
  74     # Users are only allowed to edit their own details
  75     request_user = getattr(request, 'user', None)
  76     if not user == request_user:
  77         raise PermissionDenied()
  78 
  79     # Process request
  80     serializer = UserDetailsSerializer(data=request.DATA, instance=user)
  81     if serializer.is_valid():
  82         user.first_name = serializer.data['first_name']
  83         user.last_name = serializer.data['last_name']
  84         user.save()
  85         return Response(request.DATA)
  86     else:
  87         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  88 
  89 
  90 @api_view(['POST'])
  91 def request_organisation(request, pk=None):
  92     # Get the user, or return an error if the user does not exist
  93     try:
  94         user = get_user_model().objects.get(pk=pk)
  95     except get_user_model().DoesNotExist:
  96         return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)
  97 
  98     # Users themselves are only allowed to request to join an organisation
  99     request_user = getattr(request, 'user', None)
  100     if not user == request_user:
  101         raise PermissionDenied()
  102     request.DATA['user'] = pk
  103 
  104     # Process request
  105     serializer = EmploymentSerializer(data=request.DATA)
  106     if serializer.is_valid():
  107         try:
  108             organisation = Organisation.objects.get(pk=serializer.data['organisation'])
  109             if serializer.data['country']:
  110                 country = Country.objects.get(pk=serializer.data['country'])
  111             else:
  112                 country = None
  113             employment = Employment(
  114                 user=user,
  115                 organisation=organisation,
  116                 country=country,
  117                 job_title=serializer.data['job_title'],
  118                 is_approved=False,
  119             )
  120             employment.save()
  121         except IntegrityError:
  122             return Response({'detail': _(u'User already linked to this organisation')},
  123                             status=status.HTTP_409_CONFLICT)
  124 
  125         serializer.data['country_full'] = CountrySerializer(country).data
  126         serializer.data['organisation_full'] = OrganisationSerializer(organisation).data
  127         serializer.data['id'] = employment.pk
  128 
  129         return Response(serializer.data)
  130     else:
  131         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  132
  ```
  --- 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/akvo/rest/views/user.py b/akvo/rest/views/user.py
  --- a/akvo/rest/views/user.py
  +++ b/akvo/rest/views/user.py
  @@ -10,10 +10,12 @@
   from django.utils.translation import ugettext_lazy as _
   
   from rest_framework import status
  -from rest_framework.decorators import api_view, permission_classes
  +from rest_framework.authentication import SessionAuthentication
  +from rest_framework.decorators import api_view, permission_classes, authentication_classes
   from rest_framework.exceptions import PermissionDenied
   from rest_framework.response import Response
   
  +from akvo.rest.models import TastyTokenAuthentication
   from ...rsr.models import Country, Employment, Organisation
   from ..viewsets import BaseRSRViewSet
   from ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer
  @@ -88,16 +90,19 @@
   
   
   @api_view(['POST'])
  +@authentication_classes([SessionAuthentication, TastyTokenAuthentication])
   def request_organisation(request, pk=None):
  +
       # Get the user, or return an error if the user does not exist
       try:
  -        user = get_user_model().objects.get(pk=pk)
  +        user_by_pk = get_user_model().objects.get(pk=pk)
       except get_user_model().DoesNotExist:
           return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)
   
  +    # request.user is the user identified by the auth token
  +    user = request.user
       # Users themselves are only allowed to request to join an organisation
  -    request_user = getattr(request, 'user', None)
  -    if not user == request_user:
  +    if not user_by_pk == request.user:
           raise PermissionDenied()
       request.DATA['user'] = pk
  
verification_info: {"golden_diff": "diff --git a/akvo/rest/views/user.py b/akvo/rest/views/user.py\n--- a/akvo/rest/views/user.py\n+++ b/akvo/rest/views/user.py\n@@ -10,10 +10,12 @@\n from django.utils.translation import ugettext_lazy as _\n \n from rest_framework import status\n-from rest_framework.decorators import api_view, permission_classes\n+from rest_framework.authentication import SessionAuthentication\n+from rest_framework.decorators import api_view, permission_classes, authentication_classes\n from rest_framework.exceptions import PermissionDenied\n from rest_framework.response import Response\n \n+from akvo.rest.models import TastyTokenAuthentication\n from ...rsr.models import Country, Employment, Organisation\n from ..viewsets import BaseRSRViewSet\n from ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer\n@@ -88,16 +90,19 @@\n \n \n @api_view(['POST'])\n+@authentication_classes([SessionAuthentication, TastyTokenAuthentication])\n def request_organisation(request, pk=None):\n+\n     # Get the user, or return an error if the user does not exist\n     try:\n-        user = get_user_model().objects.get(pk=pk)\n+        user_by_pk = get_user_model().objects.get(pk=pk)\n     except get_user_model().DoesNotExist:\n         return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n \n+    # request.user is the user identified by the auth token\n+    user = request.user\n     # Users themselves are only allowed to request to join an organisation\n-    request_user = getattr(request, 'user', None)\n-    if not user == request_user:\n+    if not user_by_pk == request.user:\n         raise PermissionDenied()\n     request.DATA['user'] = pk\n", "issue": "Employment application requires Django login\n## Test plan\n\nGIVEN the `/rest/v1/user/../request_organisation/` endpoint\nWHEN POSTing a request from outside of RSR\nAND the correct authentication details are provided\nTHEN the request should be process accordingly, instead trying to authenticate through Django's auth system\n## Issue description\n\nJust as for #2037, when posting a request for employment to the /rest/v1/user/request_organisation/ endpoint, a Django login is required, which is not the case for the rest of the API; an API key should be sufficient.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Akvo RSR is covered by the GNU Affero General Public License.\n\nSee more details in the license.txt file located at the root folder of the Akvo RSR module.\nFor additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\"\"\"\n\nfrom django.contrib.auth import get_user_model\nfrom django.db import IntegrityError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.response import Response\n\nfrom ...rsr.models import Country, Employment, Organisation\nfrom ..viewsets import BaseRSRViewSet\nfrom ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer\nfrom ..serializers import UserSerializer, UserDetailsSerializer, UserPasswordSerializer\n\n\nclass UserViewSet(BaseRSRViewSet):\n\n    \"\"\"User resource.\"\"\"\n\n    queryset = get_user_model().objects.select_related(\n        'organisation',\n        'organisation__primary_location',\n        'organisation__primary_location__country',\n        'organisation__primary_location__location_target',\n        'organisation__primary_location__location_target__internal_org_ids',\n    ).prefetch_related(\n        'organisations',\n        'organisations__primary_location',\n        'organisations__primary_location__country',\n        'organisations__primary_location__location_target',)\n    serializer_class = UserSerializer\n    filter_fields = ('username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff',\n                     'is_admin')\n\n\n@api_view(['POST'])\ndef change_password(request, pk=None):\n    # Get the user, or return an error if the user does not exist\n    try:\n        user = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # Users are only allowed to edit their own details\n    request_user = getattr(request, 'user', None)\n    if not user == request_user:\n        raise PermissionDenied()\n\n    # Process request\n    serializer = UserPasswordSerializer(data=request.DATA, instance=user)\n    if serializer.is_valid():\n        user.set_password(serializer.data['new_password2'])\n        user.save()\n        return Response({'status': 'password set'})\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef update_details(request, pk=None):\n    # Get the user, or return an error if the user does not exist\n    try:\n        user = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # Users are only allowed to edit their own details\n    request_user = getattr(request, 'user', None)\n    if not user == request_user:\n        raise PermissionDenied()\n\n    # Process request\n    serializer = UserDetailsSerializer(data=request.DATA, instance=user)\n    if serializer.is_valid():\n        user.first_name = serializer.data['first_name']\n        user.last_name = serializer.data['last_name']\n        user.save()\n        return Response(request.DATA)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef request_organisation(request, pk=None):\n    # Get the user, or return an error if the user does not exist\n    try:\n        user = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # Users themselves are only allowed to request to join an organisation\n    request_user = getattr(request, 'user', None)\n    if not user == request_user:\n        raise PermissionDenied()\n    request.DATA['user'] = pk\n\n    # Process request\n    serializer = EmploymentSerializer(data=request.DATA)\n    if serializer.is_valid():\n        try:\n            organisation = Organisation.objects.get(pk=serializer.data['organisation'])\n            if serializer.data['country']:\n                country = Country.objects.get(pk=serializer.data['country'])\n            else:\n                country = None\n            employment = Employment(\n                user=user,\n                organisation=organisation,\n                country=country,\n                job_title=serializer.data['job_title'],\n                is_approved=False,\n            )\n            employment.save()\n        except IntegrityError:\n            return Response({'detail': _(u'User already linked to this organisation')},\n                            status=status.HTTP_409_CONFLICT)\n\n        serializer.data['country_full'] = CountrySerializer(country).data\n        serializer.data['organisation_full'] = OrganisationSerializer(organisation).data\n        serializer.data['id'] = employment.pk\n\n        return Response(serializer.data)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n", "path": "akvo/rest/views/user.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Akvo RSR is covered by the GNU Affero General Public License.\n\nSee more details in the license.txt file located at the root folder of the Akvo RSR module.\nFor additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\"\"\"\n\nfrom django.contrib.auth import get_user_model\nfrom django.db import IntegrityError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import status\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.decorators import api_view, permission_classes, authentication_classes\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.response import Response\n\nfrom akvo.rest.models import TastyTokenAuthentication\nfrom ...rsr.models import Country, Employment, Organisation\nfrom ..viewsets import BaseRSRViewSet\nfrom ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer\nfrom ..serializers import UserSerializer, UserDetailsSerializer, UserPasswordSerializer\n\n\nclass UserViewSet(BaseRSRViewSet):\n\n    \"\"\"User resource.\"\"\"\n\n    queryset = get_user_model().objects.select_related(\n        'organisation',\n        'organisation__primary_location',\n        'organisation__primary_location__country',\n        'organisation__primary_location__location_target',\n        'organisation__primary_location__location_target__internal_org_ids',\n    ).prefetch_related(\n        'organisations',\n        'organisations__primary_location',\n        'organisations__primary_location__country',\n        'organisations__primary_location__location_target',)\n    serializer_class = UserSerializer\n    filter_fields = ('username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff',\n                     'is_admin')\n\n\n@api_view(['POST'])\ndef change_password(request, pk=None):\n    # Get the user, or return an error if the user does not exist\n    try:\n        user = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # Users are only allowed to edit their own details\n    request_user = getattr(request, 'user', None)\n    if not user == request_user:\n        raise PermissionDenied()\n\n    # Process request\n    serializer = UserPasswordSerializer(data=request.DATA, instance=user)\n    if serializer.is_valid():\n        user.set_password(serializer.data['new_password2'])\n        user.save()\n        return Response({'status': 'password set'})\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef update_details(request, pk=None):\n    # Get the user, or return an error if the user does not exist\n    try:\n        user = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # Users are only allowed to edit their own details\n    request_user = getattr(request, 'user', None)\n    if not user == request_user:\n        raise PermissionDenied()\n\n    # Process request\n    serializer = UserDetailsSerializer(data=request.DATA, instance=user)\n    if serializer.is_valid():\n        user.first_name = serializer.data['first_name']\n        user.last_name = serializer.data['last_name']\n        user.save()\n        return Response(request.DATA)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\n@authentication_classes([SessionAuthentication, TastyTokenAuthentication])\ndef request_organisation(request, pk=None):\n\n    # Get the user, or return an error if the user does not exist\n    try:\n        user_by_pk = get_user_model().objects.get(pk=pk)\n    except get_user_model().DoesNotExist:\n        return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)\n\n    # request.user is the user identified by the auth token\n    user = request.user\n    # Users themselves are only allowed to request to join an organisation\n    if not user_by_pk == request.user:\n        raise PermissionDenied()\n    request.DATA['user'] = pk\n\n    # Process request\n    serializer = EmploymentSerializer(data=request.DATA)\n    if serializer.is_valid():\n        try:\n            organisation = Organisation.objects.get(pk=serializer.data['organisation'])\n            if serializer.data['country']:\n                country = Country.objects.get(pk=serializer.data['country'])\n            else:\n                country = None\n            employment = Employment(\n                user=user,\n                organisation=organisation,\n                country=country,\n                job_title=serializer.data['job_title'],\n                is_approved=False,\n            )\n            employment.save()\n        except IntegrityError:\n            return Response({'detail': _(u'User already linked to this organisation')},\n                            status=status.HTTP_409_CONFLICT)\n\n        serializer.data['country_full'] = CountrySerializer(country).data\n        serializer.data['organisation_full'] = OrganisationSerializer(organisation).data\n        serializer.data['id'] = employment.pk\n\n        return Response(serializer.data)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n", "path": "akvo/rest/views/user.py"}]}