Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ChangePasswordView(UpdateAPIView):
- serializer_class = ChangePasswordSerializer
- model = UserInfo
- permission_classes = (IsAuthenticated,)
- def get(self, request, *args, **kwargs):
- return Response(status=200)
- def put(self, request, *args, **kwargs):
- self.object = self.request.user
- serializer = self.get_serializer(data=request.data)
- if serializer.is_valid():
- if not self.object.check_password(serializer.data.get("old_password")):
- return Response(
- {"old_password": ["Wrong password"]},
- status=400
- )
- self.object.set_password(serializer.data.get("new_password"))
- self.object.save()
- return Response("Success", status=200)
- return Response(serializer.errors, status=400)
- def test_change_password(self):
- client = APIClient()
- self.client.post('/api/user/login/', self.data, follow=True)
- self.client.login(username="testuser", password="secret")
- request = client.put('/api/user/change_password/', self.new_data)
- self.assertEqual(
- request, '<Response status_code=200, "application/json">'
- )
- def setUp(self):
- self.data = {
- 'username': 'testuser',
- 'password': 'secret'
- }
- self.new_data = {
- 'old_password': 'secret',
- 'new_password': 'other_secret'
- }
- User.objects.create_user(**self.data)
- from rest_framework import status
- class ChangePasswordView(UpdateAPIView):
- serializer_class = ChangePasswordSerializer
- model = UserInfo
- permission_classes = (IsAuthenticated,)
- def get(self, request, *args, **kwargs):
- return Response(status=status.HTTP_200_OK)
- def post(self, request, *args, **kwargs):
- user = request.user
- serializer = self.get_serializer(data=request.data)
- if serializer.is_valid():
- if not self.object.check_password(serializer.data.get("old_password")):
- msg = _("Wrong old password.")
- raise ValidationError(msg)
- user.set_password(serializer.data.get("new_password"))
- user.save()
- return Response("Success", status=status.HTTP_200_OK)
- msg = _('Something went wrong while reading the passwords')
- raise ValidationError(msg)
- from rest_framework import status
- def test_change_password(self):
- client = APIClient()
- self.client.post('/api/user/login/', self.data, follow=True)
- self.client.login(username="testuser", password="secret")
- response = self.post('/api/user/change_password/', self.new_data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement