自定义身份验证后,Django的管理员未登录 [英] Django's admin does not login after custom authentication

查看:138
本文介绍了自定义身份验证后,Django的管理员未登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写的自定义身份验证遵循文档。我能够注册,登录和注销用户,在那里没有问题。然后,当我创建一个超级用户 python manage.py createsuperuser 时,它将在数据库中创建一个用户,但是当我进入管理页面并尝试运行时,它不允许我登录。登录说

The custom authentication I wrote follows the instructions from the docs. I am able to register, login, and logout the user, no problem there. Then, when I create a superuser python manage.py createsuperuser, it creates a user in the database, but it does not let me login when I go to the admin page and try to login saying


请输入员工帐户的正确电子邮件地址和密码。两个地方都要注意大小写。

Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.

这是我的代码:

models.py:

models.py:

from __future__ import unicode_literals
from django.db import models

from django.db import models

from django.contrib.auth.models import AbstractUser, AbstractBaseUser, Group, Permission
from django.contrib.auth.models import BaseUserManager
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, MultipleObjectsReturned
from datetime import datetime

from django.contrib.auth.models import PermissionsMixin

import re

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password = None):
        '''Creates and saves a user with the given email and password '''

        if not email:
            raise ValueError('Email address is requied.')
        user = self.model(email = self.normalize_email(email))
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, password):
        ''' Creates and saves a superuser with the given email and password '''
        user = self.create_user(email, password = password)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)

        return user



class User(AbstractBaseUser, PermissionsMixin):
    """
    Custom user class
    """

    email = models.EmailField(verbose_name = 'email address',unique = True, db_index = True)
    # email is the unique field that can be used for identification purposes

    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 30)
    joined = models.DateTimeField(auto_now_add = True)
    is_active = models.BooleanField(default = True)
    is_admin = models.BooleanField(default = False)
    is_superuser = models.BooleanField(default = False)

    group = models.ManyToManyField(Group, related_name = 'users')
    permission = models.ManyToManyField(Permission, related_name = 'users')

    objects = CustomUserManager()


    USERNAME_FIELD = 'email'  # the unique identifier (mandatory)  The filed must have unique=True set in its definition (see above)


    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.first_name

    def has_perm(self, perm, obj=None):
        ''' Does the user have a specific permission'''
        return True   # This may need to be changed depending on the object we want to find permission for

    def has_module_perms(self, app_label):
        ''' Does the user have permission to view the app 'app_label'? The default answer is yes.
        This may be modified later on. '''

        return True

    @property
    def is_staff(self):
        ''' IS the user a member of staff? '''
        return self.is_admin



    def __unicode__(self):
        return '{user_email}, {user_title} joined on {joined_date}'.format(user_email = self.email,
                                                                       user_title = self.user_type,
                                                                       joined_date = self.joined)

在backends.py中:

In backends.py:

from django.conf import settings

from django.contrib.auth.hashers import check_password
from accounts.models import User

class EmailAuthBackend(object):
    ''' Custom authentication backend.  Allows users to login using their email address '''

    def authenticate(self, email=None, password = None):
        ''' the main method of the backend '''

        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):
        try:
            user = User.objects.get(pk = user_id) # Note that you MUST use pk = user_id in getting the user.  Otherwise, it will fail and even though the user is authenticated, the user will not be logged in

            if user.is_active:
                return user
            return None
        except User.DoesNotExist:
            return None

在admin.py中:

in admin.py:

from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from accounts.models import User as CustomUser


class UserCreationForm(forms.ModelForm):
    ''' A Form for creating new users. Includes all the required field, plus a repeated password.'''
    password1 = forms.CharField(label = 'Password', widget = forms.PasswordInput)
    password2 = forms.CharField(label = 'Password Confirmation', widget = forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ('email',)

    def clean_password2(self):
        ''' Checks that the two password entries match '''
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise forms.ValidationError('Passwords do NOT match!')
        return password2

    def save(self, commit = True):
        ''' Save the provided password in hashed format '''
        user = super(UserCreationForm, self).save(commit = False)
        user.set_password(self.cleaned_data['password1'])

        if commit:
            user.save()

        return user

class UserChangeForm(forms.ModelForm):
    ''' A form for updating users. Includes all the field on the user, but replaces the password field with admin's password hash display field '''
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = CustomUser
        fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')

        def clean_password(self):
            ''' Regardless of what the user provides, return the initial value.  This is done here rather than on the field because the field 
        does not have access to the initial value'''

            return self.initial['password']

class UserAdmin(BaseUserAdmin):
    ''' The form to add and change user instances '''
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the user model.
    # These override the defintions on the base UserAdmin
    # that reference specific fields on auth.User

    list_display = ('email', 'first_name', 'last_name', 'is_admin')
    list_filter = ('is_admin',)

    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal Info',{'fields': ('first_name', 'last_name',)}),
        ('Permissions', {'fields': ('is_admin',)}),

        )
    # add_fieldsets is not a standard ModelAdmin attribute.  UserAdmin 
    # overrides get_fieldsets to use this attribute when creating a user

    add_fieldsets = (
        (None, {'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'password1', 'password2')}
            ),
    )

    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now, register the new UserAdmin...

admin.site.register(CustomUser, UserAdmin)

# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

最后,在settings.py中:

And, finally, in settings.py:

AUTHENTICATION_BACKENDS = ['accounts.backends.EmailAuthBackend',]

那还缺少什么?

推荐答案

我认为问题出在您的 EmailAuthBackend 中。如果您在后端添加一些打印/日志记录,则会发现登录表单使用用户名密码调用身份验证方法。这意味着电子邮件,因此 user = User.objects.get(电子邮件=电子邮件)查找失败。

I think the problem is in your EmailAuthBackend. If you add some printing/logging to the backend, you'll find that the login form calls the authenticate method with username and password. This means that email is None, and therefore the user = User.objects.get(email = email) lookup fails.

在您的情况下,常规 ModelBackend 可以正常工作,因为您有 USERNAME_FIELD ='email'。如果您从设置中删除 AUTHENTICATION_BACKENDS ,则该登录应该有效。然后,您可以删除您的 EmailAuthBackend

In your case, the regular ModelBackend will work fine for you, because you have USERNAME_FIELD = 'email'. If you remove AUTHENTICATION_BACKENDS from your settings then the login should work. You can then remove your EmailAuthBackend.

如果您想使用其手机号和密码(和 cell_number 不是 USERNAME_FIELD ,那么您需要自定义身份验证后端。还需要一个名为 authenticate(cell_number = cell_number,password = password)的自定义身份验证表单,另一个支持自定义身份验证的示例是 RemoteUserBackend ,它根据服务器设置的环境变量登录用户。

If you wanted to log in users with their cell number and password (and cell_number was not the USERNAME_FIELD, then you would need a custom authentication backend. You would also need a custom authentication form that called authenticate(cell_number=cell_number, password=password). Another example of a custom authentication backed is RemoteUserBackend, which logs in the user based on an environment variable set by the server.

这篇关于自定义身份验证后,Django的管理员未登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆