MSRS/users/migrations/0002_seed_admin_and_zeus_board.py

73 lines
2 KiB
Python
Raw Normal View History

2021-04-18 20:58:18 +02:00
# Created manually
import logging
import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
from django.utils import timezone
logger = logging.getLogger(__name__)
ENV_USERNAME = 'KERS_ADMIN_USERNAME'
ENV_PASSWORD = 'KERS_ADMIN_PASSWORD'
def create_superuser(apps, schema_editor):
superuser = get_user_model()(
is_superuser=True,
is_staff=True,
username=os.environ.get(ENV_USERNAME, 'admin'),
last_login=timezone.now(),
)
dev_password = 'admin'
password = os.environ.get(ENV_PASSWORD, dev_password)
if password == dev_password:
log = logger.warning if settings.DEBUG else logger.error
log(
f"Admin password is '{password}'. This is not for use in production. Set environment variable {ENV_PASSWORD} to choose a different password.")
if not settings.DEBUG:
raise Exception("Development admin password used in production")
superuser.set_password(password)
superuser.save()
kers_group_permissions = {
"Bestuur": [
"add_event",
"delete_event",
"change_event",
]
}
def add_group_permissions(apps, schema_editor):
db_alias = schema_editor.connection.alias
emit_post_migrate_signal(2, False, db_alias)
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
for group in kers_group_permissions:
role, created = Group.objects.get_or_create(name=group)
logger.info(f'{group} Group {"created" if created else "exists"}')
for perm in kers_group_permissions[group]:
role.permissions.add(Permission.objects.get(codename=perm))
logger.info(f'Permitting {group} to {perm}')
role.save()
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.RunPython(create_superuser),
migrations.RunPython(add_group_permissions),
]