Keep SSO command separate from dev user management module

This commit is contained in:
Aleksandr Meshchryakov
2026-09-28 14:00:43 +02:00
parent 951abfb843
commit 64caf6135e
3 changed files with 0 additions and 0 deletions

View File

@@ -1,63 +0,0 @@
from apps.user.models import SsoIdentity
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError, transaction
User = get_user_model()
class Command(BaseCommand):
help = "Explicitly link a verified IAS subject to an existing local user."
def add_arguments(self, parser):
parser.add_argument("--user-id", type=int, required=True)
parser.add_argument("--expected-username", required=True)
parser.add_argument("--subject", required=True)
parser.add_argument("--dry-run", action="store_true")
def handle(self, *args, **options):
issuer = settings.SSO_ISSUER
subject = options["subject"]
if not isinstance(issuer, str) or not issuer.strip() or len(issuer) > 64:
raise CommandError("Configured SSO issuer is invalid.")
if not subject.strip() or subject != subject.strip() or len(subject) > 255:
raise CommandError("SSO subject is invalid.")
try:
with transaction.atomic():
user = (
User.objects.select_for_update()
.filter(
pk=options["user_id"],
username=options["expected_username"],
is_active=True,
)
.first()
)
if user is None:
raise CommandError(
"Active local user and expected username must match."
)
identity = SsoIdentity.objects.filter(
issuer=issuer, subject=subject
).first()
if identity is not None:
if identity.user_id != user.pk:
raise CommandError(
"This SSO identity is already linked to another user."
)
self.stdout.write("SSO identity already linked; no changes.")
return
if SsoIdentity.objects.filter(user=user).exists():
raise CommandError(
"This local user already has another SSO identity."
)
if options["dry_run"]:
self.stdout.write("SSO link validated; dry run, no changes.")
return
SsoIdentity.objects.create(user=user, issuer=issuer, subject=subject)
except IntegrityError as exc:
raise CommandError("SSO link conflicts with an existing identity.") from exc
self.stdout.write(
self.style.SUCCESS("SSO identity linked; local permissions unchanged.")
)