Allow IAS SSO without email and provide explicit identity linking
This commit is contained in:
0
src/apps/user/management/__init__.py
Normal file
0
src/apps/user/management/__init__.py
Normal file
0
src/apps/user/management/commands/__init__.py
Normal file
0
src/apps/user/management/commands/__init__.py
Normal file
63
src/apps/user/management/commands/link_sso_identity.py
Normal file
63
src/apps/user/management/commands/link_sso_identity.py
Normal file
@@ -0,0 +1,63 @@
|
||||
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.")
|
||||
)
|
||||
24
src/apps/user/migrations/0010_sso_optional_email.py
Normal file
24
src/apps/user/migrations/0010_sso_optional_email.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("user", "0009_ssoidentity")]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="user",
|
||||
name="email",
|
||||
field=models.EmailField(
|
||||
blank=True, null=True, unique=True, max_length=254,
|
||||
verbose_name="email address",
|
||||
help_text="Optional for SSO users. Must be unique when provided.",
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="ssoidentity",
|
||||
name="last_authenticated_at",
|
||||
field=models.DateTimeField(
|
||||
blank=True, null=True, verbose_name="last authenticated at",
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -29,7 +29,11 @@ class User(AbstractUser):
|
||||
)
|
||||
|
||||
email = models.EmailField(
|
||||
_("email address"), unique=True, help_text=_("Required. Must be unique.")
|
||||
_("email address"),
|
||||
unique=True,
|
||||
blank=True,
|
||||
null=True,
|
||||
help_text=_("Optional for SSO users. Must be unique when provided."),
|
||||
)
|
||||
|
||||
phone = models.CharField(
|
||||
@@ -122,7 +126,9 @@ class SsoIdentity(models.Model):
|
||||
)
|
||||
issuer = models.CharField(_("issuer"), max_length=64)
|
||||
subject = models.CharField(_("external user id"), max_length=255)
|
||||
last_authenticated_at = models.DateTimeField(_("last authenticated at"))
|
||||
last_authenticated_at = models.DateTimeField(
|
||||
_("last authenticated at"), null=True, blank=True
|
||||
)
|
||||
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
||||
updated_at = models.DateTimeField(_("updated at"), auto_now=True)
|
||||
|
||||
|
||||
@@ -89,6 +89,9 @@ class UserSerializer(serializers.ModelSerializer):
|
||||
"updated_at",
|
||||
)
|
||||
read_only_fields = ("id", "is_verified", "created_at", "updated_at")
|
||||
extra_kwargs = {
|
||||
"email": {"required": True, "allow_null": False, "allow_blank": False},
|
||||
}
|
||||
|
||||
|
||||
class CurrentUserProfileSerializer(serializers.ModelSerializer):
|
||||
@@ -156,7 +159,7 @@ class UserManagementSerializer(serializers.Serializer):
|
||||
|
||||
id = serializers.IntegerField(read_only=True)
|
||||
username = serializers.CharField(read_only=True)
|
||||
email = serializers.EmailField(read_only=True)
|
||||
email = serializers.EmailField(read_only=True, allow_null=True)
|
||||
phone = serializers.CharField(read_only=True, allow_null=True)
|
||||
is_active = serializers.BooleanField(read_only=True)
|
||||
is_verified = serializers.BooleanField(read_only=True)
|
||||
@@ -322,6 +325,9 @@ class AdminUserCreateSerializer(serializers.ModelSerializer):
|
||||
)
|
||||
extra_kwargs = {
|
||||
"email": {
|
||||
"required": True,
|
||||
"allow_null": False,
|
||||
"allow_blank": False,
|
||||
"validators": [UniqueValidator(queryset=User.objects.all())],
|
||||
},
|
||||
"username": {
|
||||
@@ -375,6 +381,10 @@ class AdminUserUpdateSerializer(serializers.ModelSerializer):
|
||||
"last_name",
|
||||
)
|
||||
|
||||
extra_kwargs = {
|
||||
"email": {"required": True, "allow_null": False, "allow_blank": False},
|
||||
}
|
||||
|
||||
def validate(self, attrs):
|
||||
profile_fields = {"first_name", "middle_name", "last_name"}
|
||||
if not any(field in attrs for field in profile_fields):
|
||||
|
||||
@@ -30,7 +30,7 @@ class SsoClaims:
|
||||
issuer: str
|
||||
subject: str
|
||||
username: str
|
||||
email: str
|
||||
email: str | None
|
||||
first_name: str
|
||||
middle_name: str
|
||||
last_name: str
|
||||
@@ -75,7 +75,6 @@ def _decode_sso_payload(encoded_token: str) -> dict:
|
||||
"sso_target",
|
||||
"user_id",
|
||||
"username",
|
||||
"email",
|
||||
]
|
||||
},
|
||||
)
|
||||
@@ -102,6 +101,23 @@ def _validate_token_lifetime(payload: dict) -> tuple[int, int]:
|
||||
return issued_at, expires_at
|
||||
|
||||
|
||||
def _optional_email(payload: dict) -> str | None:
|
||||
email = payload.get("email")
|
||||
if email is None:
|
||||
return None
|
||||
if not isinstance(email, str):
|
||||
raise SsoAuthenticationError("Некорректный email SSO-пользователя.")
|
||||
email = email.strip()
|
||||
if not email:
|
||||
return None
|
||||
try:
|
||||
validate_email(email)
|
||||
User._meta.get_field("email").run_validators(email)
|
||||
except DjangoValidationError as exc:
|
||||
raise SsoAuthenticationError("Некорректный email SSO-пользователя.") from exc
|
||||
return email
|
||||
|
||||
|
||||
def verify_sso_token(encoded_token: str) -> SsoClaims:
|
||||
"""Проверяет ES256 SSO JWT и возвращает только нужные локальному сервису claims."""
|
||||
payload = _decode_sso_payload(encoded_token)
|
||||
@@ -114,13 +130,11 @@ def verify_sso_token(encoded_token: str) -> SsoClaims:
|
||||
_, expires_at = _validate_token_lifetime(payload)
|
||||
|
||||
username = payload.get("username")
|
||||
email = payload.get("email")
|
||||
email = _optional_email(payload)
|
||||
jti = payload.get("jti")
|
||||
subject = payload.get("user_id")
|
||||
if not isinstance(username, str) or not username.strip():
|
||||
raise SsoAuthenticationError("В SSO-токене отсутствует username.")
|
||||
if not isinstance(email, str) or not email.strip():
|
||||
raise SsoAuthenticationError("В SSO-токене отсутствует email.")
|
||||
if not isinstance(jti, str) or not jti.strip():
|
||||
raise SsoAuthenticationError("В SSO-токене отсутствует jti.")
|
||||
if isinstance(subject, bool) or not isinstance(subject, int | str):
|
||||
@@ -129,7 +143,6 @@ def verify_sso_token(encoded_token: str) -> SsoClaims:
|
||||
raise SsoAuthenticationError("В SSO-токене отсутствует user_id.")
|
||||
|
||||
try:
|
||||
validate_email(email)
|
||||
User._meta.get_field("username").run_validators(username)
|
||||
except DjangoValidationError as exc:
|
||||
raise SsoAuthenticationError(
|
||||
@@ -160,9 +173,10 @@ def reserve_sso_token(claims: SsoClaims) -> None:
|
||||
|
||||
|
||||
def _ensure_user_claims_available(claims: SsoClaims, *, exclude_user_id=None) -> None:
|
||||
conflicts = User.objects.filter(
|
||||
Q(username=claims.username) | Q(email__iexact=claims.email)
|
||||
)
|
||||
query = Q(username=claims.username)
|
||||
if claims.email is not None:
|
||||
query |= Q(email__iexact=claims.email)
|
||||
conflicts = User.objects.filter(query)
|
||||
if exclude_user_id is not None:
|
||||
conflicts = conflicts.exclude(id=exclude_user_id)
|
||||
if conflicts.exists():
|
||||
@@ -186,7 +200,11 @@ def provision_sso_user(claims: SsoClaims):
|
||||
_ensure_user_claims_available(claims, exclude_user_id=user.id)
|
||||
else:
|
||||
username_user = User.objects.filter(username=claims.username).first()
|
||||
email_users = list(User.objects.filter(email__iexact=claims.email)[:2])
|
||||
email_users = (
|
||||
list(User.objects.filter(email__iexact=claims.email)[:2])
|
||||
if claims.email is not None
|
||||
else []
|
||||
)
|
||||
if username_user is not None or email_users:
|
||||
if (
|
||||
username_user is None
|
||||
@@ -200,7 +218,11 @@ def provision_sso_user(claims: SsoClaims):
|
||||
if not user.is_active:
|
||||
raise SsoAuthenticationError("Локальная учётная запись отключена.")
|
||||
else:
|
||||
user = User(username=claims.username, email=claims.email, is_verified=True)
|
||||
user = User(
|
||||
username=claims.username,
|
||||
email=claims.email,
|
||||
is_verified=claims.email is not None,
|
||||
)
|
||||
user.set_unusable_password()
|
||||
user.save()
|
||||
|
||||
@@ -212,8 +234,9 @@ def provision_sso_user(claims: SsoClaims):
|
||||
)
|
||||
|
||||
user.username = claims.username
|
||||
user.email = claims.email
|
||||
user.is_verified = True
|
||||
if claims.email is not None:
|
||||
user.email = claims.email
|
||||
user.is_verified = True
|
||||
user.save(update_fields=["username", "email", "is_verified", "updated_at"])
|
||||
profile = user.profile
|
||||
profile.first_name = claims.first_name
|
||||
|
||||
Reference in New Issue
Block a user