You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

83 lines
2.2 KiB

  1. from django.conf import settings
  2. from django.contrib.auth import login
  3. from rest_framework import serializers
  4. from rest_framework.exceptions import ValidationError
  5. from users.models import User, create_token_if_necessary
  6. class PublicUserSerializer(serializers.HyperlinkedModelSerializer):
  7. class Meta:
  8. model = User
  9. fields = (
  10. 'username',
  11. 'gravatar',
  12. settings.DRF_URL_FIELD_NAME,
  13. )
  14. extra_kwargs = {
  15. settings.DRF_URL_FIELD_NAME: {
  16. "view_name": "public-users:user-detail",
  17. },
  18. }
  19. class UserSerializer(serializers.HyperlinkedModelSerializer):
  20. class Meta:
  21. model = User
  22. fields = (
  23. 'username',
  24. 'token',
  25. 'email',
  26. 'gravatar',
  27. 'password',
  28. 'password_repeat',
  29. settings.DRF_URL_FIELD_NAME,
  30. )
  31. extra_kwargs = {
  32. settings.DRF_URL_FIELD_NAME: {
  33. "view_name": "users:user-detail",
  34. },
  35. }
  36. password = serializers.CharField(
  37. write_only=True,
  38. required=True,
  39. allow_blank=False,
  40. min_length=6,
  41. max_length=32,
  42. )
  43. password_repeat = serializers.CharField(
  44. write_only=True,
  45. required=True,
  46. allow_blank=False,
  47. min_length=6,
  48. max_length=32,
  49. )
  50. token = serializers.SerializerMethodField(read_only=True)
  51. def create(self, validated_data):
  52. if validated_data['password'] != validated_data['password_repeat']:
  53. raise ValidationError(
  54. detail={
  55. "password_repeat": "Tow password doesn't match",
  56. }
  57. )
  58. validated_data.pop('password_repeat')
  59. password = validated_data.pop('password')
  60. user = super(UserSerializer, self).create(
  61. validated_data,
  62. )
  63. user.set_password(password)
  64. user.save()
  65. login(
  66. self.context['request'],
  67. user=user,
  68. backend=settings.AUTHENTICATION_BACKENDS[0],
  69. )
  70. return user
  71. def get_token(self, obj: User):
  72. if self.context['request'].user == obj:
  73. return create_token_if_necessary(obj).key
  74. return None