We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Removing last user from "on my own facility" does not remove the facility from the device

## Observed behavior
Reported by @rtibbles in the alpha9 bug bash 

When the last user is migrated out of an on my own facility, that facility is not removed from the device

## Expected behavior
The facility should be removed from the device


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kolibri/plugins/user_profile/tasks.py`
Content:
```
1 import requests
2 from django.core.management import call_command
3 from morango.errors import MorangoError
4 from rest_framework import serializers
5 from rest_framework.exceptions import AuthenticationFailed
6 from rest_framework.status import HTTP_201_CREATED
7 
8 from .utils import TokenGenerator
9 from kolibri.core.auth.constants import role_kinds
10 from kolibri.core.auth.models import FacilityUser
11 from kolibri.core.auth.tasks import PeerImportSingleSyncJobValidator
12 from kolibri.core.auth.utils.migrate import merge_users
13 from kolibri.core.device.models import DevicePermissions
14 from kolibri.core.device.utils import set_device_settings
15 from kolibri.core.tasks.decorators import register_task
16 from kolibri.core.tasks.job import JobStatus
17 from kolibri.core.tasks.job import Priority
18 from kolibri.core.tasks.permissions import IsFacilityAdmin
19 from kolibri.core.tasks.permissions import IsSelf
20 from kolibri.core.tasks.permissions import IsSuperAdmin
21 from kolibri.core.tasks.permissions import PermissionsFromAny
22 from kolibri.core.tasks.utils import get_current_job
23 from kolibri.core.utils.urls import reverse_remote
24 from kolibri.utils.translation import ugettext as _
25 
26 
27 class MergeUserValidator(PeerImportSingleSyncJobValidator):
28     local_user_id = serializers.PrimaryKeyRelatedField(
29         queryset=FacilityUser.objects.all()
30     )
31     new_superuser_id = serializers.PrimaryKeyRelatedField(
32         queryset=FacilityUser.objects.all(), required=False
33     )
34     facility_name = serializers.CharField(default="")
35 
36     def validate(self, data):
37         try:
38             job_data = super(MergeUserValidator, self).validate(data)
39         except AuthenticationFailed:
40             self.create_remote_user(data)
41             job_data = super(MergeUserValidator, self).validate(data)
42 
43         job_data["kwargs"]["local_user_id"] = data["local_user_id"].id
44         job_data["extra_metadata"].update(user_fullname=data["local_user_id"].full_name)
45         if data.get("new_superuser_id"):
46             job_data["kwargs"]["new_superuser_id"] = data["new_superuser_id"].id
47 
48         return job_data
49 
50     def create_remote_user(self, data):
51         baseurl = data["baseurl"]
52         facility = data["facility"]
53         user_data = {
54             "username": data["username"],
55             "password": data["password"],
56             "facility": facility,
57         }
58         for f in ["gender", "birth_year", "id_number", "full_name"]:
59             if getattr(data["local_user_id"], f, "NOT_SPECIFIED") != "NOT_SPECIFIED":
60                 user_data[f] = getattr(data["local_user_id"], f, None)
61         public_signup_url = reverse_remote(baseurl, "kolibri:core:publicsignup-list")
62         response = requests.post(public_signup_url, data=user_data)
63         if response.status_code != HTTP_201_CREATED:
64             raise serializers.ValidationError(response.json()[0]["id"])
65 
66 
67 def status_fn(job):
68     # Translators: A notification title shown to users when their learner account is joining a new learning facility.
69     account_transfer_in_progress = _("Account transfer in progress")
70     # Translators: Notification text shown to users when their learner account is joining a new learning facility.
71     notification_text = _(
72         "Moving {learner_name} to learning facility {facility_name}"
73     ).format(
74         learner_name=job.extra_metadata["user_fullname"],
75         facility_name=job.extra_metadata["facility_name"],
76     )
77     return JobStatus(account_transfer_in_progress, notification_text)
78 
79 
80 @register_task(
81     queue="soud",
82     validator=MergeUserValidator,
83     priority=Priority.HIGH,
84     cancellable=False,
85     track_progress=True,
86     permission_classes=[
87         PermissionsFromAny(IsSelf(), IsSuperAdmin(), IsFacilityAdmin())
88     ],
89     status_fn=status_fn,
90 )
91 def mergeuser(command, **kwargs):
92     """
93     This is an example of the POST payload to create this task:
94     {
95         "type": "kolibri.plugins.user_profile.tasks.mergeuser",
96         "baseurl": "http://192.168.0.201:80/",
97         "facility": "41d0e8bb1600347f17ab3d9172fff87a",
98         "username": "uno",
99         "local_user_id": "05685392311d1d259fe01c65c7a6c28e"
100     }
101     being baseurl, facility and username all parameters of the remote server.
102     If the remote server requires password to authenticate user,
103     a "password" parameter must be added, otherwise it's not needed.
104 
105     If the username/password does not exist in the remote server,
106     this task will try to create the user.
107     """
108 
109     local_user_id = kwargs.pop("local_user_id")
110     local_user = FacilityUser.objects.get(id=local_user_id)
111     job = get_current_job()
112 
113     # Sync with the server to get the remote user:
114     kwargs["no_push"] = True
115     try:
116         call_command(command, **kwargs)
117     except MorangoError:
118         # error syncing with the server, probably a networking issue
119         raise
120 
121     remote_user = FacilityUser.objects.get(id=kwargs["user"])
122     merge_users(local_user, remote_user)
123     set_device_settings(subset_of_users_device=True)
124 
125     # Resync with the server to update the merged records
126     del kwargs["no_push"]
127 
128     try:
129         call_command(command, **kwargs)
130     except MorangoError:
131         # error syncing with the server, probably a networking issue
132         # syncing will happen later in scheduled syncs
133         from kolibri.core.auth.tasks import begin_request_soud_sync
134 
135         begin_request_soud_sync(kwargs["baseurl"], remote_user.id)
136 
137     new_superuser_id = kwargs.get("new_superuser_id")
138     if new_superuser_id:
139         new_superuser = FacilityUser.objects.get(id=new_superuser_id)
140         # make the user a new super user for this device:
141         new_superuser.facility.add_role(new_superuser, role_kinds.ADMIN)
142         DevicePermissions.objects.create(
143             user=new_superuser, is_superuser=True, can_manage_content=True
144         )
145 
146     # create token to validate user in the new facility
147     # after it's deleted in the current facility:
148     remote_user_pk = job.kwargs["user"]
149     remote_user = FacilityUser.objects.get(pk=remote_user_pk)
150     token = TokenGenerator().make_token(remote_user)
151     job.extra_metadata["token"] = token
152     job.extra_metadata["remote_user_pk"] = remote_user_pk
153     job.save_meta()
154     job.update_progress(1.0, 1.0)
155     local_user.delete()
156
```
--- 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()

```

diff --git a/kolibri/plugins/user_profile/tasks.py b/kolibri/plugins/user_profile/tasks.py
--- a/kolibri/plugins/user_profile/tasks.py
+++ b/kolibri/plugins/user_profile/tasks.py
@@ -9,6 +9,7 @@
 from kolibri.core.auth.constants import role_kinds
 from kolibri.core.auth.models import FacilityUser
 from kolibri.core.auth.tasks import PeerImportSingleSyncJobValidator
+from kolibri.core.auth.utils.delete import delete_facility
 from kolibri.core.auth.utils.migrate import merge_users
 from kolibri.core.device.models import DevicePermissions
 from kolibri.core.device.utils import set_device_settings
@@ -32,6 +33,7 @@
         queryset=FacilityUser.objects.all(), required=False
     )
     facility_name = serializers.CharField(default="")
+    set_as_super_user = serializers.BooleanField(required=False)
 
     def validate(self, data):
         try:
@@ -44,6 +46,8 @@
         job_data["extra_metadata"].update(user_fullname=data["local_user_id"].full_name)
         if data.get("new_superuser_id"):
             job_data["kwargs"]["new_superuser_id"] = data["new_superuser_id"].id
+        if data.get("set_as_super_user"):
+            job_data["kwargs"]["set_as_super_user"] = data["set_as_super_user"]
 
         return job_data
 
@@ -152,4 +156,14 @@
     job.extra_metadata["remote_user_pk"] = remote_user_pk
     job.save_meta()
     job.update_progress(1.0, 1.0)
-    local_user.delete()
+
+    # check if current user should be set as superuser:
+    set_as_super_user = kwargs.get("set_as_super_user")
+    if set_as_super_user:
+        DevicePermissions.objects.create(
+            user=remote_user, is_superuser=True, can_manage_content=True
+        )
+        delete_facility(local_user.facility)
+        set_device_settings(default_facility=remote_user.facility)
+    else:
+        local_user.delete()

{"golden_diff": "diff --git a/kolibri/plugins/user_profile/tasks.py b/kolibri/plugins/user_profile/tasks.py\n--- a/kolibri/plugins/user_profile/tasks.py\n+++ b/kolibri/plugins/user_profile/tasks.py\n@@ -9,6 +9,7 @@\n from kolibri.core.auth.constants import role_kinds\n from kolibri.core.auth.models import FacilityUser\n from kolibri.core.auth.tasks import PeerImportSingleSyncJobValidator\n+from kolibri.core.auth.utils.delete import delete_facility\n from kolibri.core.auth.utils.migrate import merge_users\n from kolibri.core.device.models import DevicePermissions\n from kolibri.core.device.utils import set_device_settings\n@@ -32,6 +33,7 @@\n         queryset=FacilityUser.objects.all(), required=False\n     )\n     facility_name = serializers.CharField(default=\"\")\n+    set_as_super_user = serializers.BooleanField(required=False)\n \n     def validate(self, data):\n         try:\n@@ -44,6 +46,8 @@\n         job_data[\"extra_metadata\"].update(user_fullname=data[\"local_user_id\"].full_name)\n         if data.get(\"new_superuser_id\"):\n             job_data[\"kwargs\"][\"new_superuser_id\"] = data[\"new_superuser_id\"].id\n+        if data.get(\"set_as_super_user\"):\n+            job_data[\"kwargs\"][\"set_as_super_user\"] = data[\"set_as_super_user\"]\n \n         return job_data\n \n@@ -152,4 +156,14 @@\n     job.extra_metadata[\"remote_user_pk\"] = remote_user_pk\n     job.save_meta()\n     job.update_progress(1.0, 1.0)\n-    local_user.delete()\n+\n+    # check if current user should be set as superuser:\n+    set_as_super_user = kwargs.get(\"set_as_super_user\")\n+    if set_as_super_user:\n+        DevicePermissions.objects.create(\n+            user=remote_user, is_superuser=True, can_manage_content=True\n+        )\n+        delete_facility(local_user.facility)\n+        set_device_settings(default_facility=remote_user.facility)\n+    else:\n+        local_user.delete()\n", "issue": "Removing last user from \"on my own facility\" does not remove the facility from the device\n\r\n## Observed behavior\r\nReported by @rtibbles in the alpha9 bug bash \r\n\r\nWhen the last user is migrated out of an on my own facility, that facility is not removed from the device\r\n\r\n## Expected behavior\r\nThe facility should be removed from the device\r\n\n", "before_files": [{"content": "import requests\nfrom django.core.management import call_command\nfrom morango.errors import MorangoError\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom rest_framework.status import HTTP_201_CREATED\n\nfrom .utils import TokenGenerator\nfrom kolibri.core.auth.constants import role_kinds\nfrom kolibri.core.auth.models import FacilityUser\nfrom kolibri.core.auth.tasks import PeerImportSingleSyncJobValidator\nfrom kolibri.core.auth.utils.migrate import merge_users\nfrom kolibri.core.device.models import DevicePermissions\nfrom kolibri.core.device.utils import set_device_settings\nfrom kolibri.core.tasks.decorators import register_task\nfrom kolibri.core.tasks.job import JobStatus\nfrom kolibri.core.tasks.job import Priority\nfrom kolibri.core.tasks.permissions import IsFacilityAdmin\nfrom kolibri.core.tasks.permissions import IsSelf\nfrom kolibri.core.tasks.permissions import IsSuperAdmin\nfrom kolibri.core.tasks.permissions import PermissionsFromAny\nfrom kolibri.core.tasks.utils import get_current_job\nfrom kolibri.core.utils.urls import reverse_remote\nfrom kolibri.utils.translation import ugettext as _\n\n\nclass MergeUserValidator(PeerImportSingleSyncJobValidator):\n    local_user_id = serializers.PrimaryKeyRelatedField(\n        queryset=FacilityUser.objects.all()\n    )\n    new_superuser_id = serializers.PrimaryKeyRelatedField(\n        queryset=FacilityUser.objects.all(), required=False\n    )\n    facility_name = serializers.CharField(default=\"\")\n\n    def validate(self, data):\n        try:\n            job_data = super(MergeUserValidator, self).validate(data)\n        except AuthenticationFailed:\n            self.create_remote_user(data)\n            job_data = super(MergeUserValidator, self).validate(data)\n\n        job_data[\"kwargs\"][\"local_user_id\"] = data[\"local_user_id\"].id\n        job_data[\"extra_metadata\"].update(user_fullname=data[\"local_user_id\"].full_name)\n        if data.get(\"new_superuser_id\"):\n            job_data[\"kwargs\"][\"new_superuser_id\"] = data[\"new_superuser_id\"].id\n\n        return job_data\n\n    def create_remote_user(self, data):\n        baseurl = data[\"baseurl\"]\n        facility = data[\"facility\"]\n        user_data = {\n            \"username\": data[\"username\"],\n            \"password\": data[\"password\"],\n            \"facility\": facility,\n        }\n        for f in [\"gender\", \"birth_year\", \"id_number\", \"full_name\"]:\n            if getattr(data[\"local_user_id\"], f, \"NOT_SPECIFIED\") != \"NOT_SPECIFIED\":\n                user_data[f] = getattr(data[\"local_user_id\"], f, None)\n        public_signup_url = reverse_remote(baseurl, \"kolibri:core:publicsignup-list\")\n        response = requests.post(public_signup_url, data=user_data)\n        if response.status_code != HTTP_201_CREATED:\n            raise serializers.ValidationError(response.json()[0][\"id\"])\n\n\ndef status_fn(job):\n    # Translators: A notification title shown to users when their learner account is joining a new learning facility.\n    account_transfer_in_progress = _(\"Account transfer in progress\")\n    # Translators: Notification text shown to users when their learner account is joining a new learning facility.\n    notification_text = _(\n        \"Moving {learner_name} to learning facility {facility_name}\"\n    ).format(\n        learner_name=job.extra_metadata[\"user_fullname\"],\n        facility_name=job.extra_metadata[\"facility_name\"],\n    )\n    return JobStatus(account_transfer_in_progress, notification_text)\n\n\n@register_task(\n    queue=\"soud\",\n    validator=MergeUserValidator,\n    priority=Priority.HIGH,\n    cancellable=False,\n    track_progress=True,\n    permission_classes=[\n        PermissionsFromAny(IsSelf(), IsSuperAdmin(), IsFacilityAdmin())\n    ],\n    status_fn=status_fn,\n)\ndef mergeuser(command, **kwargs):\n    \"\"\"\n    This is an example of the POST payload to create this task:\n    {\n        \"type\": \"kolibri.plugins.user_profile.tasks.mergeuser\",\n        \"baseurl\": \"http://192.168.0.201:80/\",\n        \"facility\": \"41d0e8bb1600347f17ab3d9172fff87a\",\n        \"username\": \"uno\",\n        \"local_user_id\": \"05685392311d1d259fe01c65c7a6c28e\"\n    }\n    being baseurl, facility and username all parameters of the remote server.\n    If the remote server requires password to authenticate user,\n    a \"password\" parameter must be added, otherwise it's not needed.\n\n    If the username/password does not exist in the remote server,\n    this task will try to create the user.\n    \"\"\"\n\n    local_user_id = kwargs.pop(\"local_user_id\")\n    local_user = FacilityUser.objects.get(id=local_user_id)\n    job = get_current_job()\n\n    # Sync with the server to get the remote user:\n    kwargs[\"no_push\"] = True\n    try:\n        call_command(command, **kwargs)\n    except MorangoError:\n        # error syncing with the server, probably a networking issue\n        raise\n\n    remote_user = FacilityUser.objects.get(id=kwargs[\"user\"])\n    merge_users(local_user, remote_user)\n    set_device_settings(subset_of_users_device=True)\n\n    # Resync with the server to update the merged records\n    del kwargs[\"no_push\"]\n\n    try:\n        call_command(command, **kwargs)\n    except MorangoError:\n        # error syncing with the server, probably a networking issue\n        # syncing will happen later in scheduled syncs\n        from kolibri.core.auth.tasks import begin_request_soud_sync\n\n        begin_request_soud_sync(kwargs[\"baseurl\"], remote_user.id)\n\n    new_superuser_id = kwargs.get(\"new_superuser_id\")\n    if new_superuser_id:\n        new_superuser = FacilityUser.objects.get(id=new_superuser_id)\n        # make the user a new super user for this device:\n        new_superuser.facility.add_role(new_superuser, role_kinds.ADMIN)\n        DevicePermissions.objects.create(\n            user=new_superuser, is_superuser=True, can_manage_content=True\n        )\n\n    # create token to validate user in the new facility\n    # after it's deleted in the current facility:\n    remote_user_pk = job.kwargs[\"user\"]\n    remote_user = FacilityUser.objects.get(pk=remote_user_pk)\n    token = TokenGenerator().make_token(remote_user)\n    job.extra_metadata[\"token\"] = token\n    job.extra_metadata[\"remote_user_pk\"] = remote_user_pk\n    job.save_meta()\n    job.update_progress(1.0, 1.0)\n    local_user.delete()\n", "path": "kolibri/plugins/user_profile/tasks.py"}], "after_files": [{"content": "import requests\nfrom django.core.management import call_command\nfrom morango.errors import MorangoError\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom rest_framework.status import HTTP_201_CREATED\n\nfrom .utils import TokenGenerator\nfrom kolibri.core.auth.constants import role_kinds\nfrom kolibri.core.auth.models import FacilityUser\nfrom kolibri.core.auth.tasks import PeerImportSingleSyncJobValidator\nfrom kolibri.core.auth.utils.delete import delete_facility\nfrom kolibri.core.auth.utils.migrate import merge_users\nfrom kolibri.core.device.models import DevicePermissions\nfrom kolibri.core.device.utils import set_device_settings\nfrom kolibri.core.tasks.decorators import register_task\nfrom kolibri.core.tasks.job import JobStatus\nfrom kolibri.core.tasks.job import Priority\nfrom kolibri.core.tasks.permissions import IsFacilityAdmin\nfrom kolibri.core.tasks.permissions import IsSelf\nfrom kolibri.core.tasks.permissions import IsSuperAdmin\nfrom kolibri.core.tasks.permissions import PermissionsFromAny\nfrom kolibri.core.tasks.utils import get_current_job\nfrom kolibri.core.utils.urls import reverse_remote\nfrom kolibri.utils.translation import ugettext as _\n\n\nclass MergeUserValidator(PeerImportSingleSyncJobValidator):\n    local_user_id = serializers.PrimaryKeyRelatedField(\n        queryset=FacilityUser.objects.all()\n    )\n    new_superuser_id = serializers.PrimaryKeyRelatedField(\n        queryset=FacilityUser.objects.all(), required=False\n    )\n    facility_name = serializers.CharField(default=\"\")\n    set_as_super_user = serializers.BooleanField(required=False)\n\n    def validate(self, data):\n        try:\n            job_data = super(MergeUserValidator, self).validate(data)\n        except AuthenticationFailed:\n            self.create_remote_user(data)\n            job_data = super(MergeUserValidator, self).validate(data)\n\n        job_data[\"kwargs\"][\"local_user_id\"] = data[\"local_user_id\"].id\n        job_data[\"extra_metadata\"].update(user_fullname=data[\"local_user_id\"].full_name)\n        if data.get(\"new_superuser_id\"):\n            job_data[\"kwargs\"][\"new_superuser_id\"] = data[\"new_superuser_id\"].id\n        if data.get(\"set_as_super_user\"):\n            job_data[\"kwargs\"][\"set_as_super_user\"] = data[\"set_as_super_user\"]\n\n        return job_data\n\n    def create_remote_user(self, data):\n        baseurl = data[\"baseurl\"]\n        facility = data[\"facility\"]\n        user_data = {\n            \"username\": data[\"username\"],\n            \"password\": data[\"password\"],\n            \"facility\": facility,\n        }\n        for f in [\"gender\", \"birth_year\", \"id_number\", \"full_name\"]:\n            if getattr(data[\"local_user_id\"], f, \"NOT_SPECIFIED\") != \"NOT_SPECIFIED\":\n                user_data[f] = getattr(data[\"local_user_id\"], f, None)\n        public_signup_url = reverse_remote(baseurl, \"kolibri:core:publicsignup-list\")\n        response = requests.post(public_signup_url, data=user_data)\n        if response.status_code != HTTP_201_CREATED:\n            raise serializers.ValidationError(response.json()[0][\"id\"])\n\n\ndef status_fn(job):\n    # Translators: A notification title shown to users when their learner account is joining a new learning facility.\n    account_transfer_in_progress = _(\"Account transfer in progress\")\n    # Translators: Notification text shown to users when their learner account is joining a new learning facility.\n    notification_text = _(\n        \"Moving {learner_name} to learning facility {facility_name}\"\n    ).format(\n        learner_name=job.extra_metadata[\"user_fullname\"],\n        facility_name=job.extra_metadata[\"facility_name\"],\n    )\n    return JobStatus(account_transfer_in_progress, notification_text)\n\n\n@register_task(\n    queue=\"soud\",\n    validator=MergeUserValidator,\n    priority=Priority.HIGH,\n    cancellable=False,\n    track_progress=True,\n    permission_classes=[\n        PermissionsFromAny(IsSelf(), IsSuperAdmin(), IsFacilityAdmin())\n    ],\n    status_fn=status_fn,\n)\ndef mergeuser(command, **kwargs):\n    \"\"\"\n    This is an example of the POST payload to create this task:\n    {\n        \"type\": \"kolibri.plugins.user_profile.tasks.mergeuser\",\n        \"baseurl\": \"http://192.168.0.201:80/\",\n        \"facility\": \"41d0e8bb1600347f17ab3d9172fff87a\",\n        \"username\": \"uno\",\n        \"local_user_id\": \"05685392311d1d259fe01c65c7a6c28e\"\n    }\n    being baseurl, facility and username all parameters of the remote server.\n    If the remote server requires password to authenticate user,\n    a \"password\" parameter must be added, otherwise it's not needed.\n\n    If the username/password does not exist in the remote server,\n    this task will try to create the user.\n    \"\"\"\n\n    local_user_id = kwargs.pop(\"local_user_id\")\n    local_user = FacilityUser.objects.get(id=local_user_id)\n    job = get_current_job()\n\n    # Sync with the server to get the remote user:\n    kwargs[\"no_push\"] = True\n    try:\n        call_command(command, **kwargs)\n    except MorangoError:\n        # error syncing with the server, probably a networking issue\n        raise\n\n    remote_user = FacilityUser.objects.get(id=kwargs[\"user\"])\n    merge_users(local_user, remote_user)\n    set_device_settings(subset_of_users_device=True)\n\n    # Resync with the server to update the merged records\n    del kwargs[\"no_push\"]\n\n    try:\n        call_command(command, **kwargs)\n    except MorangoError:\n        # error syncing with the server, probably a networking issue\n        # syncing will happen later in scheduled syncs\n        from kolibri.core.auth.tasks import begin_request_soud_sync\n\n        begin_request_soud_sync(kwargs[\"baseurl\"], remote_user.id)\n\n    new_superuser_id = kwargs.get(\"new_superuser_id\")\n    if new_superuser_id:\n        new_superuser = FacilityUser.objects.get(id=new_superuser_id)\n        # make the user a new super user for this device:\n        new_superuser.facility.add_role(new_superuser, role_kinds.ADMIN)\n        DevicePermissions.objects.create(\n            user=new_superuser, is_superuser=True, can_manage_content=True\n        )\n\n    # create token to validate user in the new facility\n    # after it's deleted in the current facility:\n    remote_user_pk = job.kwargs[\"user\"]\n    remote_user = FacilityUser.objects.get(pk=remote_user_pk)\n    token = TokenGenerator().make_token(remote_user)\n    job.extra_metadata[\"token\"] = token\n    job.extra_metadata[\"remote_user_pk\"] = remote_user_pk\n    job.save_meta()\n    job.update_progress(1.0, 1.0)\n\n    # check if current user should be set as superuser:\n    set_as_super_user = kwargs.get(\"set_as_super_user\")\n    if set_as_super_user:\n        DevicePermissions.objects.create(\n            user=remote_user, is_superuser=True, can_manage_content=True\n        )\n        delete_facility(local_user.facility)\n        set_device_settings(default_facility=remote_user.facility)\n    else:\n        local_user.delete()\n", "path": "kolibri/plugins/user_profile/tasks.py"}]}