Skip to content

Commit

Permalink
Migrate CoreDeveloper to StaffAreaAdministrator
Browse files Browse the repository at this point in the history
Coupling of migrations to role classes (be the historic or current)
causes difficulties for future changes to role classes.

This migration therefore uses local classes which will match database
values created from the real role classes, and whose own corresponding
database values will parse to real role classes (if existing).
  • Loading branch information
Jongmassey committed Oct 4, 2024
1 parent ec33b2d commit 81cc5ed
Showing 1 changed file with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 5.1.1 on 2024-10-02 11:00

from django.db import migrations


# We have removed the "real" CoreDeveloper role so make a fake one here
class CoreDeveloper:
__module__ = "jobserver.authorization.roles"


# If we ever want to change StaffAreaAdministrator in future, coupling this migration
# to that class would cause us problems, so use a local fake for this one as well
class StaffAreaAdministrator:
__module__ = "jobserver.authorization.roles"


def change_user_role(apps, from_role, to_role):
User = apps.get_model("jobserver", "User")
users = User.objects.filter(roles__contains=from_role)
for user in users:
for role in user.roles:
# we can't rely on vanilla python comparison of our fakes,
# so use RoleField.get_prep_value() for consistency with Django QuerySet
get_prep_value = User.roles.field.base_field.get_prep_value
from_path = get_prep_value(from_role)
if get_prep_value(role) == from_path:
user.roles.remove(role)
user.roles.append(to_role)
User.objects.bulk_update(users, ["roles"])


def coredeveloper_to_staffadministrator(apps, schema_editor):
change_user_role(apps, CoreDeveloper, StaffAreaAdministrator)


def staffadministrator_to_coredeveloper(apps, schema_editor):
change_user_role(apps, StaffAreaAdministrator, CoreDeveloper)


class Migration(migrations.Migration):
dependencies = [
("jobserver", "0007_remove_user_is_staff_remove_user_is_superuser"),
]

operations = [
migrations.RunPython(
coredeveloper_to_staffadministrator,
reverse_code=staffadministrator_to_coredeveloper,
)
]

0 comments on commit 81cc5ed

Please sign in to comment.