Serializers
class UserLoginSerializer(ModelSerializer):
????token = CharField(allow_blank=True, read_only=True)
????class Meta:
? ????? model = User
? ????? fields = [
? ? ? ? 'username',
? ? ? ? 'password',
? ? ? ? 'token',
? ? ]
? ? extra_kwargs = {"password":
? ? ? ? ? ? ? ? ? ? ? ? {"write_only": True}
? ? ? ? ? ? ? ? ? ? }
def validate(self, data):
? ? user_obj = None
? ? username = data.get("username", None)
? ? password = data["password"]
? ? if not username:
? ? ? ? raise ValidationError("Kullan?c? ad? gerekli.")
? ? user = User.objects.filter(
? ? ? ? Q(username=username)
? ? ? ? ).distinct()
? ? user = user.exclude(email__isnull=True).exclude(email__iexact='')
? ? if user.exists() and user.count() == 1:
? ? ? ? user = user.first()
? ? else:
? ? ? ? raise ValidationError("B?yle bir Kullan?c? Ad? yoktur.")
? ? if user_obj:
? ? ? ? if not user_obj.check_password(password):
? ? ? ? ? ? raise ValidationError("Tekrar deneyiniz.")
? ? data["token"] = "asdasdasdasd"
? ? return data
Views
class UserLoginAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UserLoginSerializer
def post(self, request, *args, **kwargs):
? ? data = request.data
? ? serializer = UserLoginSerializer(data=data)
? ? if serializer.is_valid(raise_exception=True):
? ? ? ? new_data = serializer.data
? ? ? ? return Response(new_data, status=HTTP_200_OK)
? ? return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
Settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
? ? 'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
? ? 'rest_framework.authentication.SessionAuthentication',
? ? 'rest_framework.authentication.BasicAuthentication',
? ? 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
urls
urlpatterns = [
url(r'^login/$', UserLoginAPIView.as_view(), name='login'),
url(r'^api-token-auth/', obtain_jwt_token),
url(r'^api-token-refresh/', refresh_jwt_token),
url(r'^api-token-verify/', verify_jwt_token),
url(r'^register/$', UserCreateAPIView.as_view(), name='register'),
]