59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
from django.conf import settings
|
|
from django.core.management import call_command
|
|
from django.core.management.base import BaseCommand
|
|
from django.db import transaction
|
|
|
|
from apps.accounts.models import ApiKey, User
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = (
|
|
"Seed demo superadmin login + API key, then Sukawarna Kandang 1 "
|
|
"and Kandang 2 as the default closed cycles"
|
|
)
|
|
|
|
@transaction.atomic
|
|
def handle(self, *args, **options):
|
|
user, created = User.objects.get_or_create(
|
|
user_name="admin",
|
|
defaults={
|
|
"display_name": "Admin",
|
|
"status": User.STATUS_SUPERADMIN,
|
|
"is_staff": True,
|
|
"is_superuser": True,
|
|
},
|
|
)
|
|
if created or not user.has_usable_password():
|
|
user.set_password("admin123")
|
|
user.status = User.STATUS_SUPERADMIN
|
|
if not (user.display_name or "").strip():
|
|
user.display_name = "Admin"
|
|
user.save()
|
|
self.stdout.write("Created/updated user admin / admin123")
|
|
elif not (user.display_name or "").strip():
|
|
user.display_name = "Admin"
|
|
user.save(update_fields=["display_name", "updated_at"])
|
|
|
|
raw_key = None
|
|
bootstrap = settings.SITE_API_KEY
|
|
if bootstrap:
|
|
api_key, raw_key = ApiKey.generate(user, "site")
|
|
api_key.prefix = bootstrap[:8]
|
|
api_key.key_hash = ApiKey.hash_key(bootstrap)
|
|
api_key.save(update_fields=["prefix", "key_hash", "updated_at"])
|
|
raw_key = bootstrap
|
|
self.stdout.write(f"Site API key installed (prefix={api_key.prefix})")
|
|
elif not ApiKey.objects.filter(user=user).exists():
|
|
api_key, raw_key = ApiKey.generate(user, "seed")
|
|
self.stdout.write(self.style.WARNING(f"Demo API key (save now): {raw_key}"))
|
|
|
|
call_command("seed_sukawarna_kandang4")
|
|
call_command("seed_sukawarna_kandang5")
|
|
call_command("seed_iot_10min")
|
|
|
|
self.stdout.write(
|
|
self.style.SUCCESS(
|
|
"Seed OK: Sukawarna Kandang 1 & Kandang 2 closed cycles + 10-minute IoT panels"
|
|
)
|
|
)
|