from rest_framework import serializers, permissions, status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.validators import UniqueValidator
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from bp_auth.models import CustomUser as User
class SignupSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
email = serializers.CharField(
validators=[UniqueValidator(queryset=User.objects.all())]
)
class Meta:
model = User
fields = ('email', 'password')
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super(MyTokenObtainPairSerializer, cls).get_token(user)
token['email'] = user.email
return token
class RegisterUsers(CreateAPIView):
serializer_class = SignupSerializer
permission_classes = (permissions.AllowAny,)
def post(self, request, *args, **kwargs):
serialized_user = SignupSerializer(data=request.data)
if serialized_user.is_valid():
User.objects.create_user(
serialized_user.initial_data['email'],
serialized_user.initial_data['password']
)
tokens = MyTokenObtainPairSerializer(request.data).validate(request.data)
return Response(tokens, status=status.HTTP_201_CREATED)
else:
return Response(serialized_user._errors, status=status.HTTP_400_BAD_REQUEST)