75 lines
2.4 KiB
Python
Executable File
75 lines
2.4 KiB
Python
Executable File
from django.utils.translation import gettext_lazy as _
|
|
from rest_framework import serializers
|
|
from rest_framework.authtoken.serializers import (
|
|
AuthTokenSerializer as BaseAuthTokenSerializer,
|
|
)
|
|
from outbo.apps.authentication.models import User
|
|
from outbo.apps.organizations.models import Organization
|
|
from outbo.apps.organizations.serializers import OrganizationSerializer
|
|
|
|
|
|
class AuthTokenSerializer(BaseAuthTokenSerializer):
|
|
def validate(self, attrs):
|
|
validated_attrs = super().validate(attrs)
|
|
user = validated_attrs["user"]
|
|
if user.is_staff:
|
|
msg = _("Administrators cannot login via API.")
|
|
raise serializers.ValidationError(msg, code="authorization")
|
|
return validated_attrs
|
|
|
|
|
|
class _BaseUserSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = User
|
|
|
|
|
|
class UserSerializer:
|
|
class List(_BaseUserSerializer):
|
|
organization_name = serializers.SlugRelatedField(
|
|
source="organization", slug_field="name", read_only=True
|
|
)
|
|
photo = serializers.SerializerMethodField()
|
|
|
|
class Meta(_BaseUserSerializer.Meta):
|
|
fields = [
|
|
"id",
|
|
"full_name",
|
|
"organization_name",
|
|
"photo",
|
|
"email",
|
|
"phone_number",
|
|
"job_title",
|
|
]
|
|
|
|
def get_photo(self, instance: User):
|
|
if instance.photo_url:
|
|
return self.context["request"].build_absolute_uri(instance.photo_url)
|
|
|
|
class Retrieve(_BaseUserSerializer):
|
|
organization = serializers.SerializerMethodField()
|
|
photo = serializers.SerializerMethodField()
|
|
|
|
class Meta(_BaseUserSerializer.Meta):
|
|
fields = [
|
|
"id",
|
|
"username",
|
|
"full_name",
|
|
"organization",
|
|
"photo",
|
|
"email",
|
|
"phone_number",
|
|
"job_title",
|
|
"is_observer",
|
|
"is_trader",
|
|
]
|
|
|
|
def get_photo(self, instance: User):
|
|
if instance.photo_url:
|
|
return self.context["request"].build_absolute_uri(instance.photo_url)
|
|
|
|
# NOTE: Hacky workaround
|
|
def get_organization(self, instance):
|
|
serializer = OrganizationSerializer.List(read_only=True)
|
|
serializer.instance = Organization.objects.get(id=instance.organization_id)
|
|
return serializer.data
|