From 17650b72baf43b00aa4d8ee862b0cd406366d054 Mon Sep 17 00:00:00 2001 From: Midgard Date: Sat, 25 Jul 2020 11:29:26 +0200 Subject: [PATCH] Allow admin password to be set from environment Require password to be different from "admin" in production. --- users/migrations/0002_auto_20200724_2340.py | 27 ++++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/users/migrations/0002_auto_20200724_2340.py b/users/migrations/0002_auto_20200724_2340.py index f9d04c3..74a7f80 100644 --- a/users/migrations/0002_auto_20200724_2340.py +++ b/users/migrations/0002_auto_20200724_2340.py @@ -1,6 +1,9 @@ -# Generated by Django 3.0.8 on 2020-07-24 21:40 -import logging +# 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 @@ -9,15 +12,27 @@ 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="admin", # os.environ['ADMIN_USERNAME'], + username=os.environ.get(ENV_USERNAME, 'admin'), last_login=timezone.now(), ) - # superuser.set_password(os.environ['ADMIN_PASSWORD']) - superuser.set_password('admin') + + 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() @@ -39,7 +54,7 @@ def add_group_permissions(apps, schema_editor): for group in kers_group_permissions: role, created = Group.objects.get_or_create(name=group) - logger.info(f'{group} Group created') + 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}')