2
\$\begingroup\$

I am working on Django Rest Framework for backend to develop android app. My project is about Food Delivery System.

My app has user login and registration feature. I preferred oAuth2 for token based authentication. I did the user registration part. When a user registers, a new token is created for that user.

But I want an expert to review my code and provide some feedback and if possible please enlighten me what else I should implement in my code for better user registration functionality.

serializers.py

class UserCreateSerializer(ModelSerializer):
    email = EmailField()
    username =  CharField()
    first_name = CharField(required=False)
    last_name = CharField(required=False)
    password = CharField()
    confirm_password = CharField()
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'first_name',
            'last_name',
            'password',
            'confirm_password'          
        ]
        extra_kwargs = {"password": {"write_only": True}}

    def validate(self, data):
        if not data.get('password') or not data.get('confirm_password'):
            raise ValidationError('Please enter a password and cofirm it')
        if data.get('password') != data.get('confirm_password'):
            raise ValidationError('Password must match')
        return data


    def validate_email(self, email):
        existing_email = User.objects.filter(email=email).exists()
        print('existing',existing_email)
        if existing_email:
            raise ValidationError("Someone with that email address has already registered. Was it you?")
        return email


    def create(self, validated_data):
        username = validated_data['username']
        first_name = validated_data['first_name']
        last_name = validated_data['last_name']
        email = validated_data['email']
        password = validated_data['password']
        confirm_password = validated_data['password']
        user_obj = User(
                username = username,
                first_name = first_name,
                last_name = last_name,
                email = email
            )
        user_obj.set_password(password)
        user_obj.save()
        if user_obj:
            expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS']
            scopes = oauth2_settings.user_settings['SCOPES']

            application = Application.objects.get(name="Foodie")
            expires = datetime.now() + timedelta(seconds=expire_seconds)
            access_token = AccessToken.objects.create(user=user_obj, 
                                                    application=application,
                                                    token = generate_token(),
                                                    expires=expires, 
                                                    scope=scopes)
        return validated_data

class UserLoginSerializer(ModelSerializer):
    # token = CharField(allow_blank=True, read_only=True)
    username = CharField()
    # email = EmailField(label='Email Address')
    class Meta:
        model = User
        fields = [
            'username',
            # 'email',
            'password',
            # 'token',

        ]
        extra_kwargs = {"password":
                            {"write_only": True}
                            }
    def validate(self, data):
        return data

views.py

class UserCreateAPI(CreateAPIView):
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()
    permission_classes = [AllowAny]

class UserLoginAPI(APIView): # i could not solve login using oAuth2
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        # access_token = AccessToken.objects.get(token=request.data.get('token'), expires__gt=timezone.now())
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review, good job on your first question, you should get some good answers! \$\endgroup\$ – ferada Sep 6 '16 at 11:39
  • \$\begingroup\$ Thanks. I am confident i will get good answers from experts. \$\endgroup\$ – Serenity Sep 6 '16 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.