Last active
October 15, 2019 18:43
-
-
Save mitchtabian/23336b8c57f6bc6314af8011fb2dcc0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework.generics import UpdateAPIView | |
from rest_framework.authentication import TokenAuthentication | |
from account.api.serializers import ChangePasswordSerializer | |
@api_view(['GET', ]) | |
@permission_classes([]) | |
@authentication_classes([]) | |
def does_account_exist_view(request): | |
if request.method == 'GET': | |
email = request.GET['email'].lower() | |
data = {} | |
try: | |
account = Account.objects.get(email=email) | |
data['response'] = email | |
except Account.DoesNotExist: | |
data['response'] = "Account does not exist" | |
return Response(data) | |
class ChangePasswordView(UpdateAPIView): | |
serializer_class = ChangePasswordSerializer | |
model = Account | |
permission_classes = (IsAuthenticated,) | |
authentication_classes = (TokenAuthentication,) | |
def get_object(self, queryset=None): | |
obj = self.request.user | |
return obj | |
def update(self, request, *args, **kwargs): | |
self.object = self.get_object() | |
serializer = self.get_serializer(data=request.data) | |
if serializer.is_valid(): | |
# Check old password | |
if not self.object.check_password(serializer.data.get("old_password")): | |
return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) | |
# confirm the new passwords match | |
new_password = serializer.data.get("new_password") | |
confirm_new_password = serializer.data.get("confirm_new_password") | |
if new_password != confirm_new_password: | |
return Response({"new_password": ["New passwords must match"]}, status=status.HTTP_400_BAD_REQUEST) | |
# set_password also hashes the password that the user will get | |
self.object.set_password(serializer.data.get("new_password")) | |
self.object.save() | |
return Response({"response":"successfully changed password"}, status=status.HTTP_200_OK) | |
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment