def test_send_lockout_signal(self): """Test if the lockout signal is emitted """ class Scope(object): pass # this "hack" is needed so we don't have to use global variables or python3 features scope = Scope() scope.signal_received = 0 def signal_handler(request, username, ip_address, *args, **kwargs): scope.signal_received += 1 self.assertIsNotNone(request) # Connect signal handler user_locked_out.connect(signal_handler) # Make a lockout self.test_failure_limit_once() self.assertEquals(scope.signal_received, 1) reset() # Make another lockout self.test_failure_limit_once() self.assertEquals(scope.signal_received, 2)
def unlock_user_view(request, user_id=None): user = get_object_or_404(fEMRUser, pk=user_id) reset(username=user.username) user.is_active = True user.last_login = timezone.now() user.save() return redirect("main:list_users_view")
def test_run_user_deactivate(): u = fEMRUser.objects.create_user( username="******", password="******", email="*****@*****.**", ) u.change_password = False u.save() reset(username="******") client = Client() r = client.post( "/login_view/", { "username": "******", "password": "******" }, ) assert r.status_code == 302 assert r.url == "/home/" assert u.is_active n = now() + timedelta(days=35) run_user_deactivate(n) u = fEMRUser.objects.get(username="******") assert not u.is_active u.delete()
def post(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Arguments: request: a Django Request object, must contain in the POST body: - email: Valid email address. - password: Valid password. Returns: HttpResponse response with the user's token and user data Raises: AccessDenied if request fails. """ serializer = AuthenticationSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): user = serializer.validated_data["user"] email = serializer.validated_data["email"] invitation_code = request.data.get("invitation_code") login(request, user) # Logging the user in reset(username=email) # Reset any remaining access attempts Invitation.objects.validate_all_pending( user, invitation_code) # validate all pending invitations return ResponseSuccess(serializer.data, http_status=status.HTTP_200_OK) else: raise ValidationAPIException(serializer_errors=serializer.errors)
def bloquear_usuario(request, pk): user = User.objects.get(pk=pk) user.is_active = not user.is_active user.save() reset(username=user.username) messages.add_message(request, messages.INFO, 'Cambio de estado exitoso') return HttpResponseRedirect(reverse("usuarios"))
def unlock(request): if request.method == 'POST': username = request.POST['username'] reset(username=username) return (render(request, 'sales/index.html')) else: return (render(request, 'sales/unlock.html'))
def reset_lockouts(request, username=None): if username is not None: reset(username=username) return_response = render(request, "admin/user_reset_success.html", {"username": username}) else: return_response = render(request, "admin/user_reset_no_success.html") return return_response
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) ip = get_client_ip(request) reset(ip=ip) return response.Response(status=status.HTTP_201_CREATED)
def test_reset_ip(self): """Tests if can reset an ip address """ # Make a lockout self.test_with_real_username_max() # Reset the ip so we can try again reset(ip='127.0.0.1') # Make a login attempt again self.test_with_real_username_max()
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip, is_routable = get_client_ip(request) reset(ip=ip) return HttpResponseRedirect(reverse_lazy('login')) else: form = AxesCaptchaForm() return render(request, 'djcyradm/locked_out.html', context=dict(form=form))
def test_reset_all(self): """Tests if can reset all attempts """ # Make a lockout self.test_with_real_username_max() # Reset all attempts so we can try again reset() # Make a login attempt again self.test_with_real_username_max()
def dispatch(self, request, *args, **kwargs): response = super(CaptchaLoginView, self).dispatch(request, *args, **kwargs) if request.POST: if request.user.is_authenticated: ip = get_ip_address_from_request(request) reset(ip=ip) return set_ticket_cookie(request.user, response) else: return response return response
def test_reset_all(self): """Tests if can reset all attempts """ # Make a lockout self.test_failure_limit_once() # Reset all attempts so we can try again reset() # Make a login attempt again self.test_valid_login()
def login_locked(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip = get_client_ip(request) reset(ip=ip) return HttpResponseRedirect(reverse_lazy('login')) else: form = AxesCaptchaForm() context = {'form': form} return render(request, 'login_locked.html', context)
def test_reset_ip(self): """Tests if can reset an ip address """ # Make a lockout self.test_failure_limit_once() # Reset the ip so we can try again reset(ip='127.0.0.1') # Make a login attempt again self.test_valid_login()
def locked_out(request, exception=None): if request.POST: form = AxesLockoutCaptchaForm(request.POST) if form.is_valid(): ip = get_client_ip_address(request) reset(ip=ip) return HttpResponseRedirect(reverse_lazy("account_login")) else: form = AxesLockoutCaptchaForm() return render(request, "captcha.html", {"form": form})
def test_reset_ip(self): """Tests if can reset an ip address """ # Make a lockout self.test_failure_limit_once() # Reset the ip so we can try again reset(ip="127.0.0.1") # Make a login attempt again self.test_valid_login()
def dispatch(self, request, *args, **kwargs): response = super(CaptchaLoginView, self).dispatch( request, *args, **kwargs) if request.POST: if request.user.is_authenticated: ip = get_ip_address_from_request(request) reset(ip=ip) return set_ticket_cookie(request.user, response) else: return response return response
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): #ip = get_ip_address_from_request(request) reset() return HttpResponseRedirect('/login') else: form = AxesCaptchaForm() return render(request, 'locked_out.html', dict(form=form))
def login(request): message = [] next = request.GET.get('next') if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) reset(username=username) if next: return redirect(next) else: return redirect('/') else: message = ["Usuario o password Incorrecto", messages.WARNING] try: axes = AccessAttempt.objects.get(username=username) user = User.objects.get(username=username) if user.is_staff or user.is_superuser: # Las cuentas de administrador no se bloquearán reset(username=user.username) else: if user.is_active: if axes.failures_since_start >= settings.AXES_FAILURE_LIMIT: user.is_active = False user.save() message = [ "Usuario bloqueado, póngase en contacto con el administrador", messages.ERROR ] else: message = [ "Contraseña errónea le quedan " + str(settings.AXES_FAILURE_LIMIT - axes.failures_since_start) + " intentos", messages.WARNING ] else: message = [ "Usuario bloqueado, póngase en contacto con el administrador", messages.ERROR ] except: pass messages.add_message(request, message[1], message[0]) return render(request, 'registration/login.html', { 'message': message, }) else: return render(request, 'registration/login.html', { 'message': message, })
def handle(self, *args, **kwargs): count = 0 if kwargs: for ip in kwargs['ip']: count += reset(ip=ip) else: count = reset() if count: print('{0} attempts removed.'.format(count)) else: print('No attempts found.')
def test_reset_ip(self): """ Test resetting all attempts for an IP address. """ # Make a lockout self.test_failure_limit_once() # Reset the ip so we can try again reset(ip='127.0.0.1') # Make a login attempt again self.test_valid_login()
def handle(self, *args, **kwargs): count = 0 if kwargs and kwargs.get('ip'): for ip in kwargs['ip'][1:]: count += reset(ip=ip) else: count = reset() if kwargs['verbosity']: if count: self.stdout.write('{0} attempts removed.'.format(count)) else: self.stdout.write('No attempts found.')
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip = get_ip(request) if ip is not None: msg = "User locked out with IP address=%s" % ip logger.warning(msg) reset(ip=ip) return HttpResponseRedirect(reverse_lazy('frogs:index')) else: form = AxesCaptchaForm() return render_to_response('frogs/locked.html', dict(form=form), context_instance=RequestContext(request))
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip = get_ip(request) if ip is not None: msg = "User locked out with IP address=%s" % ip logger.warning(msg) reset(ip=ip) return HttpResponseRedirect(reverse_lazy('index')) else: form = AxesCaptchaForm() return render(request, 'auth/locked.html', context=dict(form=form))
def handle(self, *args, **options): # pylint: disable=unused-argument count = reset() if count: self.stdout.write(f'{count} attempts removed.') else: self.stdout.write('No attempts found.')
def handle(self, *args, **options): # pylint: disable=unused-argument count = reset() if count: self.stdout.write('{0} attempts removed.'.format(count)) else: self.stdout.write('No attempts found.')
def clearEverything(): # Delete all django-axes lockouts and access records reset() # Erase all entries in these tables tables = [ Players.objects.all(), Matches.objects.all(), Practices.objects.all(), AttendanceHistory.objects.all(), LogEntry.objects.all(), ] for table in tables: for entry in table: entry.delete()
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip = get_client_ip(request) reset(ip=ip) return HttpResponseRedirect(reverse('admin:login')) else: form = AxesCaptchaForm() return render( request, 'admin/locked_out.html', dict(form=form), )
def handle(self, *args, **options): # pylint: disable=unused-argument count = reset() if count: self.stdout.write(f"{count} attempts removed.") else: self.stdout.write("No attempts found.")
def handle(self, *args, **kwargs): count = 0 count += reset(username=kwargs['username']) if count: print('{0} attempts removed.'.format(count)) else: print('No attempts found.')
def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): ip = get_ip(request) reset(ip=ip) return HttpResponseRedirect(reverse_lazy("cas_login")) else: messages.error( request, _("Too many failed login attempts. " "Please enter the letters in the box beneath."), ) form = AxesCaptchaForm() return render(request, "core/locked_out.html", dict(form=form))
def bloquear_usuario(request, pk): if request.user.id != int(pk): try: user = User.objects.get(pk=pk) user.is_active = not user.is_active user.save() reset(username=user.username) messages.add_message(request, messages.SUCCESS, 'Cambio de estado exitoso') except: messages.add_message(request, messages.INFO, 'Error al cambiar el estado del usuario') else: messages.add_message(request, messages.INFO, 'No puede bloquear su propio usuario') return HttpResponseRedirect(reverse("usuarios"))
def handle(self, *args, **kwargs): count = 0 count += reset(username=kwargs['username']) if kwargs['verbosity']: if count: self.stdout.write('{0} attempts removed.'.format(count)) else: self.stdout.write('No attempts found.')
def test_lockout_by_user_only(self): """Tests the login lock with a valid username and invalid password when AXES_ONLY_USER_FAILURES is True """ # test until one try before the limit for _ in range(1, settings.AXES_FAILURE_LIMIT): response = self._login( is_valid_username=True, is_valid_password=False, ) # Check if we are in the same login page self.assertContains(response, self.LOGIN_FORM_KEY, html=True) # So, we shouldn't have gotten a lock-out yet. # But we should get one now response = self._login(is_valid_username=True, is_valid_password=False) self.assertContains(response, self.LOCKED_MESSAGE, status_code=403) # reset the username only and make sure we can log in now even though # our IP has failed each time reset(username=AccessAttemptTest.VALID_USERNAME) response = self._login( is_valid_username=True, is_valid_password=True, ) # Check if we are still in the login page self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302, html=True) # now create failure_limit + 1 failed logins and then we should still # be able to login with valid_username for _ in range(settings.AXES_FAILURE_LIMIT): response = self._login( is_valid_username=False, is_valid_password=False, ) # Check if we can still log in with valid user response = self._login(is_valid_username=True, is_valid_password=True) self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302, html=True)
def handle(self, *args, **options): count = 0 for username in options['username']: count += reset(username=username) if count: self.stdout.write('{0} attempts removed.'.format(count)) else: self.stdout.write('No attempts found.')
def handle(self, *args, **options): count = 0 for ip in options['ip']: count += reset(ip=ip) if count: self.stdout.write(f'{count} attempts removed.') else: self.stdout.write('No attempts found.')
def test_lockout_by_user_only(self): """ Test login failure when AXES_ONLY_USER_FAILURES is True. """ # test until one try before the limit for _ in range(1, settings.AXES_FAILURE_LIMIT): response = self._login( is_valid_username=True, is_valid_password=False, ) # Check if we are in the same login page self.assertContains(response, self.LOGIN_FORM_KEY, html=True) # So, we shouldn't have gotten a lock-out yet. # But we should get one now response = self._login(is_valid_username=True, is_valid_password=False) self.assertContains(response, self.LOCKED_MESSAGE, status_code=403) # reset the username only and make sure we can log in now even though # our IP has failed each time reset(username=AccessAttemptTest.VALID_USERNAME) response = self._login( is_valid_username=True, is_valid_password=True, ) # Check if we are still in the login page self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302, html=True) # now create failure_limit + 1 failed logins and then we should still # be able to login with valid_username for _ in range(settings.AXES_FAILURE_LIMIT): response = self._login( is_valid_username=False, is_valid_password=False, ) # Check if we can still log in with valid user response = self._login(is_valid_username=True, is_valid_password=True) self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302, html=True)
def test_reset_username(self): self.create_attempt(username=self.username) reset(username=self.username) self.assertFalse(AccessAttempt.objects.count())
def reset(self, ip=None, username=None): return reset(ip, username)
def PWreset(request): reset(ip=request.META['REMOTE_ADDR']) reset(username=request.user.username) return password_reset_complete(request)
def test_reset(self): self.create_attempt() reset() self.assertFalse(AccessAttempt.objects.count())
def test_reset_ip(self): self.create_attempt(ip_address=self.ip_address) reset(ip=self.ip_address) self.assertFalse(AccessAttempt.objects.count())
def handle(self, *args, **kwargs): if args: for ip in args: reset(ip) else: reset()
def form_valid(self, form): utils.reset(username=form.cleaned_data['username']) return super(GenericLockedView, self).form_valid(form)
def edit_user(request, username=None): """ edit_user(request, username = None) -> reply @type request: HttpRequest @param request: The request object @type username: string @param username: Default to None, when creating a new user """ if request.user.username != username and not request.user.is_superuser: request.audit = {'allowed': False} if username is not None: request.audit['operation'] = 'EDIT_USER' request.audit['operationText'] = _get_failed_operation_text(request.user.username, 'EDIT_USER') else: request.audit['operation'] = 'CREATE_USER' request.audit['operationText'] = _get_failed_operation_text(request.user.username, 'CREATE_USER') raise PopupException(_("You must be a superuser to add or edit another user."), error_code=401) userprofile = get_profile(request.user) if username is not None: instance = User.objects.get(username=username) else: instance = None if require_change_password(userprofile): form_class = PasswordChangeForm elif request.user.is_superuser: form_class = SuperUserChangeForm else: form_class = UserChangeForm if request.method == 'POST': form = form_class(request.POST, instance=instance) if request.user.is_superuser and request.user.username != username: form.fields.pop("password_old") if form.is_valid(): # All validation rules pass if instance is None: instance = form.save() get_profile(instance) else: if username != form.instance.username: raise PopupException(_("You cannot change a username."), error_code=401) if request.user.username == username and not form.instance.is_active: raise PopupException(_("You cannot make yourself inactive."), error_code=401) global __users_lock __users_lock.acquire() try: # form.instance (and instance) now carry the new data orig = User.objects.get(username=username) if orig.is_superuser: if not form.instance.is_superuser or not form.instance.is_active: _check_remove_last_super(orig) else: if form.instance.is_superuser and not request.user.is_superuser: raise PopupException(_("You cannot make yourself a superuser."), error_code=401) # All ok form.save() request.info(_('User information updated')) # Unlock account if selected if form.cleaned_data.get('unlock_account'): if not request.user.is_superuser: raise PopupException(_('You must be a superuser to reset users.'), error_code=401) try: reset(username=username) request.info(_('Successfully unlocked account for user: %s') % username) except Exception, e: raise PopupException(_('Failed to reset login attempts for %s: %s') % (username, str(e))) finally: __users_lock.release() # Ensure home directory is created, if necessary. if form.cleaned_data.get('ensure_home_directory'): try: ensure_home_directory(request.fs, instance) except (IOError, WebHdfsException), e: request.error(_('Cannot make home directory for user %s.') % instance.username) # Change langugage preference, if necessary if form.cleaned_data.get('language') and form.cleaned_data.get('language') != get_language(): request.session['django_language'] = form.cleaned_data.get('language') # Audit log if username is not None: request.audit = { 'operation': 'EDIT_USER', 'operationText': 'Edited User with username: %s' % username } else: request.audit = { 'operation': 'CREATE_USER', 'operationText': 'Created User with username: %s' % instance.username } if require_change_password(userprofile): userprofile.first_login = False userprofile.save() if request.user.is_superuser: return redirect(reverse('about:index')) else: return redirect(reverse('desktop.views.home')) elif request.user.is_superuser: return redirect(reverse(list_users)) else: return redirect(reverse(edit_user, kwargs={'username': username}))