fix / AEB-68 account type doesn't displayed correctly

This commit is contained in:
Timofey
2025-10-29 09:56:32 +03:00
parent 6ac5acebba
commit efc9d5c579
9 changed files with 184 additions and 178 deletions

View File

@@ -2,6 +2,7 @@ from typing import Any, Optional
from rest_framework import serializers
from django.conf import settings
from api.types import User
from sitemanagement.constants.account_types import account_types
class UserResponseSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
@@ -14,6 +15,7 @@ class UserResponseSerializer(serializers.Serializer):
surname = serializers.CharField(source='last_name', read_only=True)
imageURL = serializers.SerializerMethodField()
uuid = serializers.SerializerMethodField()
account_type = serializers.SerializerMethodField()
class Meta:
ref_name = "UserResponse" # для OpenAPI
@@ -22,6 +24,10 @@ class UserResponseSerializer(serializers.Serializer):
"""Получает короткий UUID (первые 6 символов) из профиля пользователя"""
return obj.userprofile.short_uuid if hasattr(obj, 'userprofile') else None
def get_account_type(self, obj: User) -> Optional[str]:
"""Получает тип аккаунта пользователя"""
return obj.userprofile.get_account_type() if hasattr(obj, 'userprofile') else None
def get_imageURL(self, obj: User) -> Optional[str]:
"""Получает полный URL для изображения профиля пользователя"""
try:
@@ -44,6 +50,7 @@ class UserResponseSerializer(serializers.Serializer):
'name': data['name'], # str
'surname': data['surname'], # str
'imageURL': data['imageURL'], # Optional[str]
'account_type': data['account_type'], # AccountTypeLiteral
'uuid': data['uuid'], # Optional[str]
}
@@ -60,6 +67,11 @@ class LoginRequestSerializer(serializers.Serializer):
required=True,
style={'input_type': 'password'}
)
role = serializers.ChoiceField(
help_text="Роль пользователя",
choices=account_types,
required=False
)
class LoginResponseSerializer(serializers.Serializer):

View File

@@ -10,6 +10,7 @@ from drf_spectacular.utils import extend_schema, OpenApiResponse, OpenApiExample
from drf_spectacular.types import OpenApiTypes
from django.contrib.auth.models import User as DjangoUser
from api.types import User
from .serializers import (
UserResponseSerializer,
@@ -49,7 +50,8 @@ class LoginViewSet(AuthBaseViewSet):
"name": "Иван",
"surname": "Иванов",
"imageURL": "https://example.com/avatar.jpg",
"uuid": "abc123"
"uuid": "abc123",
"account_type": "admin"
}
}
)
@@ -102,6 +104,7 @@ class LoginViewSet(AuthBaseViewSet):
try:
login = request.data.get("login")
password = request.data.get("password")
role = request.data.get("role")
if not login or not password:
return Response(
@@ -110,7 +113,7 @@ class LoginViewSet(AuthBaseViewSet):
)
try:
user = DjangoUser.objects.get(username=login)
user: User = DjangoUser.objects.get(username=login) # type: ignore[assignment]
except DjangoUser.DoesNotExist:
return Response(
{"error": "Пользователь не найден"},
@@ -123,6 +126,19 @@ class LoginViewSet(AuthBaseViewSet):
status=status.HTTP_403_FORBIDDEN
)
# обновляем account_type в профиле пользователя
if role:
valid_roles = ['engineer', 'operator', 'admin']
if role not in valid_roles:
return Response(
{"error": f"Недопустимая роль. Доступные роли: {', '.join(valid_roles)}"},
status=status.HTTP_400_BAD_REQUEST
)
if hasattr(user, 'userprofile'):
user.userprofile.account_type = role
user.userprofile.save()
refresh = RefreshToken.for_user(user)
user_data = UserResponseSerializer(user).data