我可以使用django-nonrel和自定义身份验证后端吗?

时间:2012-02-28 10:47:32

标签: python google-app-engine django-nonrel django-authentication

我正在尝试使用自定义后端进行用户授权,使用django-nonrel(电子邮件地址而不是用户名,没什么特别之处),而且它只是不起作用。所有对authenticate()的调用都返回None。这是我的后端:

from django.contrib.auth.models import User, check_password

    class EmailAuthBackend(object):
        """
        Email Authentication Backend

        Allows a user to sign in using an email/password pair rather than
        a username/password pair.
        """
        supports_anonymous_user = False
        supports_object_permissions = True


        def authenticate(self, email=None, password=None):
            """ Authenticate a user based on email address as the user name. """
            try:
                user = User.objects.get(email=email)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None

        def get_user(self, user_id):
            """ Get a User object from the user_id. """
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None

视图(我试图在用户注册后立即登录用户)。 new_user始终为无:

def create_new_user(request):
    if request.method == 'POST':
        data = request.POST.copy()
        data['username'] = ''.join([choice(letters) for i in xrange(30)])
        data['password'] = data['password1']
        form = CustomUserCreationForm(data)
        if form.is_valid(): 
            user = form.save(commit=False)
            # user must be active for login to work
            user.is_active = True
            user.save() #not sure if this is actually saving
            new_user = authenticate(username=data['username'],\
                    password=data['password'])
            if new_user is None:
                messages.error(request,"God damn it.")
            login(request, new_user)

            messages.info(request, "Thanks for registering! You are\
                                                            now logged in.")
            return render_to_response('invoicer/welcome.html',
                                                     {'user':new_user})

        else:
            messages.error(request, form._errors)
            return HttpResponseRedirect('//')

有人可以向我提供一些见解,说明为什么我对authenticate()的电话无效?


编辑:此外,部署后,我的注册表单肯定会创建用户,可以在appengine.google.com上的数据查看器中看到

1 个答案:

答案 0 :(得分:1)

原来我需要做的就是改变

  

的authenticate(用户名=电子邮件

在视图中:

  

的authenticate(电子邮件=电子邮件

我的后端没有收到电子邮件,所以默认为没有。对我感到羞耻。但是,当我使用标准的django登录表单时,它会将一个名为usernamepassword的文件传递给我的后端,所以我必须能够处理两个用户名(实际上是用户的电子邮件地址)和电子邮件作为命名关键字。

现在,我只是在我的后端这样做:

def authenticate(self, username=None, email=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        if username:
            might_be_email = username
        elif email:
            might_be_email = email

尝试按might_be_email找到用户。