Django的管理员在自定义身份验证后无法登录

时间:2017-02-07 15:20:53

标签: python django django-authentication django-modeladmin

我编写的自定义身份验证遵循the docs的说明。我可以注册,登录和注销用户,没问题。然后,当我创建一个超级用户python manage.py createsuperuser时,它会在数据库中创建一个用户,但是当我进入管理页面并尝试登录时,它不会让我登录

  

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

这是我的代码:

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中:

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中:

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中:

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

那么缺少什么?

1 个答案:

答案 0 :(得分:1)

我认为问题出在你的EmailAuthBackend。如果您向后端添加一些打印/日志记录,您会发现the login form calls the authenticate methodusernamepassword。这意味着emailNone,因此user = User.objects.get(email = email)查找失败。

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

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