98 lines
3.2 KiB
Python
98 lines
3.2 KiB
Python
"""
|
|
Management command to create a superadmin user.
|
|
"""
|
|
import getpass
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
from apps.users.models import User
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Create a superadmin user with admin role'
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
'--username',
|
|
type=str,
|
|
help='Username for the admin account',
|
|
)
|
|
parser.add_argument(
|
|
'--email',
|
|
type=str,
|
|
help='Email for the admin account',
|
|
)
|
|
parser.add_argument(
|
|
'--password',
|
|
type=str,
|
|
help='Password for the admin account (not recommended, use interactive mode instead)',
|
|
)
|
|
parser.add_argument(
|
|
'--name',
|
|
type=str,
|
|
help='Display name for the admin account',
|
|
)
|
|
parser.add_argument(
|
|
'--noinput',
|
|
action='store_true',
|
|
help='Do not prompt for input (requires --username and --password)',
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
username = options.get('username')
|
|
email = options.get('email')
|
|
password = options.get('password')
|
|
name = options.get('name')
|
|
noinput = options.get('noinput')
|
|
|
|
if noinput:
|
|
if not username or not password:
|
|
raise CommandError('--username and --password are required when using --noinput')
|
|
else:
|
|
# Interactive mode
|
|
if not username:
|
|
username = input('Username: ').strip()
|
|
if not username:
|
|
raise CommandError('Username cannot be empty')
|
|
|
|
if not email:
|
|
email = input('Email (optional): ').strip() or None
|
|
|
|
if not name:
|
|
name = input('Display name (optional): ').strip() or None
|
|
|
|
if not password:
|
|
password = getpass.getpass('Password: ')
|
|
password_confirm = getpass.getpass('Password (again): ')
|
|
if password != password_confirm:
|
|
raise CommandError('Passwords do not match')
|
|
|
|
if not password:
|
|
raise CommandError('Password cannot be empty')
|
|
|
|
if len(password) < 6:
|
|
raise CommandError('Password must be at least 6 characters')
|
|
|
|
# Check if user already exists
|
|
if User.objects.filter(open_id=username).exists():
|
|
raise CommandError(f'User with username "{username}" already exists')
|
|
|
|
if email and User.objects.filter(email=email).exists():
|
|
raise CommandError(f'User with email "{email}" already exists')
|
|
|
|
# Create the admin user
|
|
user = User(
|
|
open_id=username,
|
|
email=email,
|
|
name=name or username,
|
|
role='admin',
|
|
is_active=True,
|
|
)
|
|
user.set_password(password)
|
|
user.save()
|
|
|
|
self.stdout.write(
|
|
self.style.SUCCESS(f'Successfully created superadmin user "{username}"')
|
|
)
|
|
self.stdout.write(f' - Role: admin')
|
|
self.stdout.write(f' - Email: {email or "(not set)"}')
|
|
self.stdout.write(f' - Display name: {name or username}')
|