1

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

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

这是我的代码:

模型.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',]

那么缺少什么?

4

2 回答 2

4

我认为问题出在您的EmailAuthBackend. 如果您在后端添加一些打印/日志记录,您会发现登录表单使用and调用 authenticate 方法。这意味着是,因此查找失败。usernamepasswordemailNoneuser = User.objects.get(email = email)

在你的情况下,常规ModelBackend对你来说很好,因为你有USERNAME_FIELD = 'email'. 如果您AUTHENTICATION_BACKENDS从设置中删除,那么登录应该可以工作。然后,您可以删除您的EmailAuthBackend.

如果您想使用他们的手机号码和密码登录用户(而cell_number不是在用户中基于服务器设置的环境变量。USERNAME_FIELDauthenticate(cell_number=cell_number, password=password)RemoteUserBackend

于 2017-02-08T14:46:21.843 回答
1

有同样的问题。而不是password=None,我将其更改为passwordonly。并通过'password=password''username=username'如下所示:

class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, password):
        if not email:
            raise ValueError('Please add an email address')
        if not username:
            raise ValueError('Please add an username')

        user = self.model(email=self.normalize_email(
            email), username=username, password=password)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user = self.create_user(email=self.normalize_email(
            email), username=username, password=password)

正如 Denis 上面已经说过的,确保添加AUTH_USER_MODEL = 'accounts.User'到 settings.py

于 2021-10-03T11:29:46.193 回答