|
| 1 | +from django.core.management.base import BaseCommand, CommandError |
| 2 | +from django.core.validators import validate_email |
| 3 | +from django.core.exceptions import ValidationError |
| 4 | +from django.contrib.auth.password_validation import validate_password |
| 5 | +from getpass import getpass |
| 6 | + |
| 7 | +from eventyay.base.models.auth import User |
| 8 | + |
| 9 | + |
| 10 | +class Command(BaseCommand): |
| 11 | + help = 'Creates an admin user without setting is_superuser to True.' |
| 12 | + |
| 13 | + def handle(self, *args, **options): |
| 14 | + email = self.get_email() |
| 15 | + password = self.get_password() |
| 16 | + |
| 17 | + # Prevent duplicate users |
| 18 | + if User.objects.filter(email=email).exists(): |
| 19 | + raise CommandError(f"A user with email {email} already exists.") |
| 20 | + |
| 21 | + # Create admin user |
| 22 | + user = User.objects.create_adminuser(email=email, password=password) |
| 23 | + |
| 24 | + self.stdout.write(self.style.SUCCESS(f"Successfully created admin user: {user.email}")) |
| 25 | + |
| 26 | + def get_email(self): |
| 27 | + """Prompt for email and validate format.""" |
| 28 | + while True: |
| 29 | + email = input("E-mail: ").strip() |
| 30 | + if not email: |
| 31 | + self.stderr.write(self.style.ERROR("The email field cannot be empty.")) |
| 32 | + continue |
| 33 | + try: |
| 34 | + validate_email(email) |
| 35 | + return email |
| 36 | + except ValidationError: |
| 37 | + self.stderr.write(self.style.ERROR("Please enter a valid email address.")) |
| 38 | + |
| 39 | + def get_password(self): |
| 40 | + """Prompt for password and apply Django's password validation.""" |
| 41 | + while True: |
| 42 | + password1 = self._get_password("Password: ") |
| 43 | + password2 = self._get_password("Confirm password: ") |
| 44 | + |
| 45 | + if password1 != password2: |
| 46 | + self.stderr.write(self.style.ERROR("Passwords do not match. Please try again.")) |
| 47 | + continue |
| 48 | + |
| 49 | + try: |
| 50 | + validate_password(password1) |
| 51 | + return password1 |
| 52 | + except ValidationError as e: |
| 53 | + for error in e.messages: |
| 54 | + self.stderr.write(self.style.ERROR(error)) |
| 55 | + |
| 56 | + def _get_password(self, prompt): |
| 57 | + """Securely read a password input.""" |
| 58 | + return getpass(prompt) |
0 commit comments