8

I am trying to get a login form I have in django to only allow three login attempts before redirecting to a "login help" page. I am currently using the builtin "django.contrib.auth.views.login" view with a custom template. How do I force it to redirect to another page after n failed login attempts?

3 Answers 3

14

There's actually a project out there which provides a Django middleware to do just this, called django-axes. Simply install it with the instructions provided and then set AXES_LOGIN_FAILURE_LIMIT to the number of login attempts you want before a record is created for the failed logins. You'll still have to check this record when you want to lock someone out, however.

3
  • Thanks Daniel. I chose dotty's answer because it was closer to the method I ended up using. Part of the issue was my own inexperience with Python and Django and as such I didn't have enough knowledge to ask the right question. I think your answer would have been just as good if not better if I wanted something with that many features, and I may well end upo using it when I am more familiar with the framework.
    – RED MONKEY
    Jun 10, 2010 at 19:11
  • 1
    No worries, just wanted to let you know that there was a solution out there already that could potentially work. I didn't know it existed either so I learned something in the process too! Jun 10, 2010 at 19:20
  • Updated link: github.com/jazzband/django-axes
    – Genarito
    Apr 11, 2022 at 21:05
0

i use django-brake and memcached

@ratelimit(field='email', method='POST', rate='5/m')
@ratelimit(field='email', method='POST', rate='10/h')
@ratelimit(field='email', method='POST', rate='20/d')
def login_failure(request, login_form):
    """
    Increment cache counters, 403 if over limit.
    """
    was_limited = getattr(request, 'limited', False)
    if was_limited:
        limits = getattr(request, 'limits', [])
        login_form.full_clean()
        login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())\
            .append('accout locked, try '+ str(limits[0]['period']) + ' seconds later')
        return render(request, 'user/login.html', {'form': login_form})


def login(request):

    if request.method == 'GET':
        next = request.GET.get('next', '')
        return render(request, 'user/login.html', {'next': next})
    elif request.method == 'POST':
        login_form = LoginForm(request.POST)

        # check first 
        from brake.utils import get_limits
        limits = get_limits(request, 'login_failure', 'email', [60, 3600, 86400])
        if limits:
            login_form.full_clean()
            login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())\
                .append('accout locked, try '+ str(limits[0]['period']) + ' seconds later')
            return render(request, 'user/login.html', {'form': login_form})

        if login_form.is_valid():

                email = login_form.cleaned_data['email']
                submit_pwd = login_form.cleaned_data['password']

                user = authenticate(username=email, password=submit_pwd)

                if user is None:
                     # 
                    res = login_failure(request, login_form)
                    if res is None:
                        login_form._errors.setdefault(NON_FIELD_ERRORS, ErrorList()).append('password wrong')
                        res = render(request, 'user/login.html', {'form': login_form})
                    return res

                ...
                login etc...
        else:

        ...
1
  • django-brake is no longer actively maintained.
    – Ashin
    Jan 1, 2021 at 16:23
-9

You could save a session if the user has failed to login.

request.SESSION['login_tries'] = 1

and if they fail to login again

request.SESSioN['login_tries'] = 2

If the session becomes equal to the amount of login tries you want them tho have, then do something.

1
  • 9
    The session will only exist if the client is sending Cookie headers, which a brute force attacker will not be doing. It would be better to link login attempts with a specific user account, or a specific client (or both).
    – NNN
    Aug 27, 2012 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.