Advertisement
Guest User

Untitled

a guest
Sep 14th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. url(r'^login/$', views.UserLoginAPIView.as_view(), name='login'),
  2. url(r'^api/auth/token/', obtain_jwt_token),
  3.  
  4. class UserLoginSerializer(ModelSerializer):
  5. token = CharField(allow_blank=True, read_only= True)
  6. email = EmailField(label='Email Address', allow_blank= True)
  7.  
  8. class Meta:
  9. model = User
  10. fields = [
  11. 'email',
  12. 'password',
  13. 'token'
  14. ]
  15.  
  16. extra_kwargs = {"password":
  17. {"write_only": True}
  18. }
  19.  
  20. def validate(self, data):
  21. user_obj = None
  22. email = data.get("email", None)
  23. password = data["password"]
  24. if not email:
  25. raise ValidationError('A username or email is required to login')
  26. user = User.objects.filter(
  27. Q(email=email)
  28. ).distinct()
  29. if user.exists() and user.count() == 1:
  30. user_obj = user.first()
  31. else:
  32. raise ValidationError("this email is not valid")
  33.  
  34. if user_obj:
  35. if not user_obj.check_password(password):
  36. raise ValidationError("incorrect creadeintial try again")
  37. data["token"] = "SOME BLANK TOKEN"
  38. return data
  39.  
  40. class UserLoginAPIView(APIView):
  41. permission_classes = [AllowAny]
  42. serializer_class = UserLoginSerializer
  43.  
  44. def post(self, request, *args, **kwargs):
  45. data = request.data
  46. serializer = UserLoginSerializer(data=data)
  47. if serializer.is_valid(raise_exception=True):
  48. new_data = serializer.data
  49. return Response(new_data, status=HTTP_200_OK)
  50. return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement