From d70b51bc4c2b650fdc759939192acb5e6421026d Mon Sep 17 00:00:00 2001 From: Tom Kazimiers Date: Tue, 16 Oct 2018 16:47:17 -0400 Subject: [PATCH] Add migration that ensures there is always a system user available This makes migrations more robust and allows them to reference such a system user, which becomes in handy in data migrations. --- CHANGELOG.md | 3 ++ .../migrations/0050_ensure_system_user.py | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 django/applications/catmaid/migrations/0050_ensure_system_user.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c96b3bded..84ef96d95c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ - Python 3 is now required for the back-end. We recommend the use of Python 3.6. +- A database migration ensures there will be always at least one system user + available. If there isn't an inactive system user is created. Such a user is + used whenever the CATMAID back-end needs to perform tasks on its own. ### Features and enhancements diff --git a/django/applications/catmaid/migrations/0050_ensure_system_user.py b/django/applications/catmaid/migrations/0050_ensure_system_user.py new file mode 100644 index 0000000000..02fde98720 --- /dev/null +++ b/django/applications/catmaid/migrations/0050_ensure_system_user.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.db import migrations, models + +from catmaid.apps import get_system_user + + +def forward(apps, schema_editor): + User = apps.get_model('auth', 'User') + try: + system_user = get_system_user(User) + except ImproperlyConfigured: + system_user_name = 'catmaid-system-user' + i = 0 + # Find a username that isn't taken yet and create an inactive super + # user. It can't be used to log in. + while True: + user_name = '{}{}'.format(system_user_name, (str(i)) if i > 0 else '') + if User.objects.filter(username=user_name).count() == 0: + User.objects.create(username=user_name, is_active=False, + is_staff=False, is_superuser=True) + break + + +class Migration(migrations.Migration): + """This migration makes sure there is at least one inactive system user in + the database. This user is needed in future data migrations.""" + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('catmaid', '0049_volume_tin_representation'), + ] + + operations = [ + migrations.RunPython(forward, migrations.RunPython.noop), + ]