nice
This commit is contained in:
parent
9ed880b125
commit
8823916d7a
45
backend/education/management/commands/ensure_admin.py
Normal file
45
backend/education/management/commands/ensure_admin.py
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
"""Create the initial superuser from environment, without ever updating another."""
|
||||||
|
from django.db.models import Q
|
||||||
|
from decouple import config
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
from django.db import IntegrityError, transaction
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = 'Crée le premier administrateur depuis ADMIN_* si aucun administrateur n’existe.'
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
User = get_user_model()
|
||||||
|
if User.objects.filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
|
||||||
|
self.stdout.write('Administrateur déjà présent : aucune modification.')
|
||||||
|
return
|
||||||
|
|
||||||
|
username = config('ADMIN_USERNAME', default='').strip()
|
||||||
|
password = config('ADMIN_PASSWORD', default='')
|
||||||
|
first_name = config('ADMIN_FIRST_NAME', default='').strip()
|
||||||
|
last_name = config('ADMIN_LAST_NAME', default='').strip()
|
||||||
|
email = config('ADMIN_EMAIL', default='').strip()
|
||||||
|
if not username or not password:
|
||||||
|
self.stdout.write(self.style.WARNING('ADMIN_USERNAME ou ADMIN_PASSWORD absent : création ignorée.'))
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
with transaction.atomic():
|
||||||
|
if User.objects.select_for_update().filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
|
||||||
|
return
|
||||||
|
if User.objects.filter(username=username).exists():
|
||||||
|
self.stdout.write(self.style.WARNING(
|
||||||
|
'Identifiant déjà utilisé : compte existant inchangé, création ignorée.'))
|
||||||
|
return
|
||||||
|
User.objects.create_superuser(
|
||||||
|
username=username, password=password, email=email,
|
||||||
|
first_name=first_name, last_name=last_name,
|
||||||
|
)
|
||||||
|
except IntegrityError:
|
||||||
|
# Another container could have initialized the superuser in parallel.
|
||||||
|
if User.objects.filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
|
||||||
|
self.stdout.write('Administrateur déjà initialisé par un autre processus.')
|
||||||
|
return
|
||||||
|
raise
|
||||||
|
self.stdout.write(self.style.SUCCESS('Administrateur initial créé.'))
|
||||||
Loading…
x
Reference in New Issue
Block a user