def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] # before we continue, delete all existing expired tokens password_reset_token_validation_time = get_password_reset_token_expiry_time() # datetime.now minus expiry hours now_minus_expiry_time = timezone.now() - timedelta(hours=password_reset_token_validation_time) # delete all tokens where created_at < now - 24 hours clear_expired(now_minus_expiry_time) # find a user by email address (case insensitive search) users = User.objects.filter(**{'{}__iexact'.format(get_password_reset_lookup_field()): email}) active_user_found = False # iterate over all users and check if there is any user that is active # also check whether the password can be changed (is useable), as there could be users that are not allowed # to change their password (e.g., LDAP user) for user in users: if user.eligible_for_reset(): active_user_found = True # No active user found, raise a validation error # but not if DJANGO_REST_PASSWORDRESET_NO_INFORMATION_LEAKAGE == True if not active_user_found and not getattr(settings, 'DJANGO_REST_PASSWORDRESET_NO_INFORMATION_LEAKAGE', False): raise exceptions.ValidationError({ 'email': [_( "There is no active user associated with this e-mail address or the password can not be changed")], }) # last but not least: iterate over all users that are active and can change their password # and create a Reset Password Token and send a signal with the created token for user in users: if user.eligible_for_reset(): # define the token as none for now token = None # check if the user already has a token if user.password_reset_tokens.all().count() > 0: # yes, already has a token, re-use this token token = user.password_reset_tokens.all()[0] else: # no token exists, generate a new token token = ResetPasswordToken.objects.create( user=user, user_agent=request.META.get(HTTP_USER_AGENT_HEADER, ''), ip_address=request.META.get(HTTP_IP_ADDRESS_HEADER, ''), ) # send a signal that the password token was created # let whoever receives this signal handle sending the email for the password reset reset_password_token_created.send(sender=self.__class__, instance=self, reset_password_token=token) # done message = get_response_message("PASSWORD_REQUEST_ACCEPT") return Response({"status_code": 200, "status": "OK", "message": message})
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] # before we continue, delete all existing expired tokens password_reset_token_validation_time = get_password_reset_token_expiry_time() # datetime.now minus expiry hours now_minus_expiry_time = timezone.now() - timedelta(hours=password_reset_token_validation_time) # delete all tokens where created_at < now - 24 hours clear_expired(now_minus_expiry_time) # find a user by email address (case insensitive search) users = User.objects.filter(email__iexact=email) active_user_found = False # iterate over all users and check if there is any user that is active # also check whether the password can be changed (is useable), as there could be users that are not allowed # to change their password (e.g., LDAP user) for user in users: if user.is_active and user.has_usable_password(): active_user_found = True # No active user found, raise a validation error if not active_user_found: raise exceptions.ValidationError({ 'email': [_( "There is no active user associated with this e-mail address or the password can not be changed")], }) # last but not least: iterate over all users that are active and can change their password # and create a Reset Password Token and send a signal with the created token for user in users: if user.is_active and user.has_usable_password(): # define the token as none for now token = None # check if the user already has a token if user.password_reset_tokens.all().count() > 0: # yes, already has a token, re-use this token token = user.password_reset_tokens.all()[0] else: # no token exists, generate a new token token = ResetPasswordToken.objects.create( user=user, user_agent=request.META.get('HTTP_USER_AGENT', getattr(settings, 'DJANGO_REST_PASSWORDRESET_HTTP_USER_AGENT', '')), ip_address=request.META.get('REMOTE_ADDR', getattr(settings, 'DJANGO_REST_PASSWORDRESET_REMOTE_ADDR', '')) ) # send a signal that the password token was created # let whoever receives this signal handle sending the email for the password reset reset_password_token_created.send(sender=self.__class__, instance=self, reset_password_token=token) # done return Response({'status': 'OK'})
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] password_reset_token_validation_time = get_password_reset_token_expiry_time() now_minus_expiry_time = timezone.now( ) - timedelta(hours=password_reset_token_validation_time) clear_expired(now_minus_expiry_time) users = User.objects.filter( **{'{}__iexact'.format(get_password_reset_lookup_field()): email}) active_user_found = False for user in users: if user.eligible_for_reset(): active_user_found = True if not active_user_found and not getattr(settings, 'DJANGO_REST_PASSWORDRESET_NO_INFORMATION_LEAKAGE', False): raise exceptions.ValidationError({ 'email': [_( "There is no active user associated with this e-mail address or the password can not be changed")], }) for user in users: if user.eligible_for_reset(): token = None if user.password_reset_tokens.all().count() > 0: token = user.password_reset_tokens.all()[0] else: token = ResetPasswordToken.objects.create( user=user, user_agent=request.META.get( HTTP_USER_AGENT_HEADER, ''), ip_address=request.META.get( HTTP_IP_ADDRESS_HEADER, ''), ) reset_password_token_created.send( sender=self.__class__, instance=self, reset_password_token=token) return Response({'status': 'OK'})
def create_registration_token(user_id): """ A function which creasts a Registration Token for a new User User's must not have a useable password """ # find a user by pk user = User.objects.get(pk=user_id) if user.eligible_for_reset(register_token=True): #clear the user's tokens clear_user_tokens(user) # create a new token token = ResetPasswordToken.objects.create( user=user, ) # send a signal that the password token was created # let whoever receives this signal handle sending the email for the password reset reset_password_token_created.send(sender=None, instance=None, reset_password_token=token) else: raise Exception("User not eligible for reset.")
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] # find a user by email address (case insensitive search) if get_use_username(): users = User.objects.filter(username=email) else: users = User.objects.filter(email=email) active_user_found = False # iterate over all users and check if there is any user that is active # also check whether the password can be changed (is useable), as there could be users that are not allowed # to change their password (e.g., LDAP user) for user in users: if user.is_active and user.has_usable_password(): active_user_found = True # No active user found, raise a validation error if not active_user_found: time.sleep(random.randint(500, 2000) / 1000) return Response() # last but not least: iterate over all users that are active and can change their password # and create a Reset Password Token and send a signal with the created token for user in users: if user.is_active and user.has_usable_password(): # define the token as none for now token = None # check if the user already has a token if user.password_reset_tokens.filter(expired=False, used=False).count() > 0: # yes, already has a token, re-use this token token = user.password_reset_tokens.all()[0] # get token validation time password_reset_token_validation_time = get_password_reset_token_expiry_time( is_long_token=token.is_long_token) expiry_date = token.created_at + timedelta( hours=password_reset_token_validation_time) if timezone.now() > expiry_date: token.expired = True token.used = True token.save() token = get_new_token(user, request) else: # no token exists, generate a new token token = get_new_token(user, request) # send a signal that the password token was created # let whoever receives this signal handle sending the email for the password reset reset_password_token_created.send(sender=self.__class__, reset_password_token=token, request=request) # done return Response()
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] # before we continue, delete all existing expired tokens password_reset_token_validation_time = get_password_reset_token_expiry_time( ) # datetime.now minus expiry hours now_minus_expiry_time = timezone.now() - timedelta( hours=password_reset_token_validation_time) # delete all tokens where created_at < now - 24 hours clear_expired(now_minus_expiry_time) # find a user by email address (case insensitive search) users = User.objects.filter(email__iexact=email) active_user_found = False # iterate over all users and check if there is any user that is active # also check whether the password can be changed (is useable), as there could be users that are not allowed # to change their password (e.g., LDAP user) for user in users: if user.is_active and user.has_usable_password(): active_user_found = True # No active user found, raise a validation error if not active_user_found: raise exceptions.ValidationError({ 'email': [ _("There is no active user associated with this e-mail address or the password can not be changed" ) ], }) # last but not least: iterate over all users that are active and can change their password # and create a Reset Password Token and send a signal with the created token for user in users: if user.is_active and user.has_usable_password(): # define the token as none for now token = None # check if the user already has a token if user.password_reset_tokens.all().count() > 0: # yes, already has a token, re-use this token token = user.password_reset_tokens.all()[0] else: ip = request.META.get('REMOTE_ADDR', None) # REMOTE_ADDR may be blank if socket server or load balancer are used, causing an exception # HTTP_X_FORWARDED_FOR as a fallback would be acceptable, since it's for logging purposes # and not authentication (also hard to spoof if load balancer is configured corrrectly) if ip is None or ip == b'': ip = request.META['HTTP_X_FORWARDED_FOR'].split(',')[ 0] # grab the first entry # no token exists, generate a new token token = ResetPasswordToken.objects.create( user=user, user_agent=request.META['HTTP_USER_AGENT'], ip_address=ip or '127.0.0.1') # send a signal that the password token was created # let whoever receives this signal handle sending the email for the password reset reset_password_token_created.send(sender=self.__class__, instance=self, reset_password_token=token) # done return Response({'status': 'OK'})