Files
Inventory/inventory/management/commands/create_api_key.py
2026-09-29 08:43:05 +02:00

47 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from inventory.models import InventoryAPIKey, UserProfile
from inventory.permissions import can_edit
class Command(BaseCommand):
help = "Erstellt einen zeitlich begrenzten API-Schlüssel und zeigt ihn genau einmal an."
def add_arguments(self, parser):
parser.add_argument("name", help="Eindeutiger Zweck, z. B. inventur-laptop-team2")
parser.add_argument("username", help="Aktives Django-Konto für die Audit-Zuordnung")
parser.add_argument("--write", action="store_true", help="Schreibzugriff erlauben")
parser.add_argument("--read-only", action="store_true", help="Nur Lesezugriff (Standard)")
parser.add_argument("--expires-days", type=int, default=90, help="Gültigkeit in Tagen (Standard: 90)")
def handle(self, *args, **options):
if options["write"] and options["read_only"]:
raise CommandError("--write und --read-only können nicht gemeinsam verwendet werden.")
if options["expires_days"] < 1 or options["expires_days"] > 365:
raise CommandError("Die Gültigkeit muss zwischen 1 und 365 Tagen liegen.")
user_model = get_user_model()
try:
user = user_model.objects.get(username=options["username"], is_active=True)
except user_model.DoesNotExist as exc:
raise CommandError("Das angegebene aktive Konto wurde nicht gefunden.") from exc
if options["write"] and not can_edit(user):
raise CommandError(
f"Schreibzugriff erfordert die Rolle {UserProfile.Role.EDITOR} oder {UserProfile.Role.ADMIN}."
)
api_key, secret = InventoryAPIKey.objects.create_key(
name=options["name"],
service_user=user,
can_read=True,
can_write=options["write"],
expiry_date=timezone.now() + timedelta(days=options["expires_days"]),
)
self.stdout.write(self.style.SUCCESS(f"API-Schlüssel '{api_key.name}' wurde erstellt."))
self.stdout.write(f"Präfix: {api_key.prefix}")
self.stdout.write(f"Läuft ab: {api_key.expiry_date.isoformat()}")
self.stdout.write(self.style.WARNING("Nur jetzt sichtbar – sicher speichern und niemals in Git einchecken:"))
self.stdout.write(secret)