开发者

Django 1.3 post login/logout signals in relation with authentication

开发者 https://www.devze.com 2023-04-13 03:49 出处:网络
First of all both methods below return True. I\'d expect the second one to return False using the django standard admin authentication procedure or am I wrong?

First of all both methods below return True. I'd expect the second one to return False using the django standard admin authentication procedure or am I wrong?

def post_login(sender, **kwargs):
    """
    Django 1.3 post login signal handler
    """
    # do stuff
    user = kwargs['user']
    print user.is_authenticated()

user_logged_in.connect(post_login)


def post_logout(sender, **kwargs):
    """
    Django 1.3 post logout signal handler
    """
    # do stuff
    user = kwargs['user']
    print user.is_authenticated()

user_logged_out.connect(post_logout)

Anyway I'm trying to understand why django doesn't have a hook on authentication failure also.. I can use my own backend for users to login and out of their account, however I would like to hook onto the admin procedure as well to cover everything in one portion of code.. I found some topics but no real awnser how to fix this.

I came up with:

import settings

from django.dispatch import Signal

failed_login = Signal(providing_args=['user'])

from django.contrib.auth.backends import ModelBackend
from dja开发者_StackOverflow社区ngo.contrib.auth.models import User

class AuthSignalBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                return user
            else:
                failed_login.send(sender=None, user=user)
        except User.DoesNotExist:
            return None


def login_handler(sender, **kwargs):
    if settings.DEBUG:
        print "failed login detected...!"
failed_login.connect(login_handler)

That works great, however there's no request in the ModelBackend, while the post_login and logout signals do have the request.. This is unfortunate because it would be great for IP logging

Any advise is welcome, I'm pretty sure people should have come across this one before..


  1. If user is an instance of User model, user.is_authenticated() will always return True. Models instance can't know what's going on on request level. This method is for views.

  2. If you want to deal with failed login attempts, take a look at django-axes. You can just use it, or look at the code and reimplement some ideas as you like.

0

精彩评论

暂无评论...
验证码 换一张
取 消