自定义身份验证后,Django的管理员未登录

早期编码器

我编写的自定义身份验证遵循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',]

那还缺少什么呢?

阿拉斯代尔

我认为问题出在你的EmailAuthBackend如果将一些打印/日志记录添加到后端,则会发现登录表单使用username调用authenticate方法password这意味着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,该日志用户根据服务器设置的环境变量进行设置。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

首次登录后HUE撤销管理员访问权限的SAML身份验证

来自分类Dev

Django身份验证自定义

来自分类Dev

邮递员自定义身份验证

来自分类Dev

Django,自定义身份验证登录。身份验证失败时如何显示错误消息?

来自分类Dev

特定模型的Django管理员自定义模板

来自分类Dev

Django管理员的自定义URL

来自分类Dev

Django管理员添加自定义按钮

来自分类Dev

在Django中测试自定义管理员操作

来自分类Dev

Django管理员,自定义模板

来自分类Dev

Django管理员:自定义搜索

来自分类Dev

自定义标签中的Django管理员StackedInline

来自分类Dev

基于自定义条件的Django管理员操作

来自分类Dev

特定模型的Django管理员自定义模板

来自分类Dev

Django管理员。新的用户。自定义权限

来自分类Dev

django管理员自定义列表视图

来自分类Dev

如何自定义 Django 管理员

来自分类Dev

用户,管理员和超级管理员自定义Django

来自分类Dev

无法使用自定义身份验证后端登录

来自分类Dev

使用 LDAP 在 Laravel 中进行身份验证/登录而无需管理员连接?

来自分类Dev

有关Django自定义身份验证和登录的错误?

来自分类Dev

在Django中使用自定义用户模型登录时的身份验证问题

来自分类Dev

有关Django自定义身份验证和登录的错误?

来自分类Dev

Laravel 5.4 多重身份验证管理员和用户在以管理员身份登录时重定向到用户登录

来自分类Dev

如何使用自定义身份验证后端连接django中的管理页面?

来自分类Dev

未调用自定义身份验证提供程序

来自分类Dev

在自定义身份验证后运行Gitlab CI?

来自分类Dev

如何自定义Django rest框架中的[未提供身份验证凭据]错误消息

来自分类Dev

在自定义列上的Django管理员自定义搜索

来自分类Dev

将按钮重定向到Django管理员身份验证视图

Related 相关文章

  1. 1

    首次登录后HUE撤销管理员访问权限的SAML身份验证

  2. 2

    Django身份验证自定义

  3. 3

    邮递员自定义身份验证

  4. 4

    Django,自定义身份验证登录。身份验证失败时如何显示错误消息?

  5. 5

    特定模型的Django管理员自定义模板

  6. 6

    Django管理员的自定义URL

  7. 7

    Django管理员添加自定义按钮

  8. 8

    在Django中测试自定义管理员操作

  9. 9

    Django管理员,自定义模板

  10. 10

    Django管理员:自定义搜索

  11. 11

    自定义标签中的Django管理员StackedInline

  12. 12

    基于自定义条件的Django管理员操作

  13. 13

    特定模型的Django管理员自定义模板

  14. 14

    Django管理员。新的用户。自定义权限

  15. 15

    django管理员自定义列表视图

  16. 16

    如何自定义 Django 管理员

  17. 17

    用户,管理员和超级管理员自定义Django

  18. 18

    无法使用自定义身份验证后端登录

  19. 19

    使用 LDAP 在 Laravel 中进行身份验证/登录而无需管理员连接?

  20. 20

    有关Django自定义身份验证和登录的错误?

  21. 21

    在Django中使用自定义用户模型登录时的身份验证问题

  22. 22

    有关Django自定义身份验证和登录的错误?

  23. 23

    Laravel 5.4 多重身份验证管理员和用户在以管理员身份登录时重定向到用户登录

  24. 24

    如何使用自定义身份验证后端连接django中的管理页面?

  25. 25

    未调用自定义身份验证提供程序

  26. 26

    在自定义身份验证后运行Gitlab CI?

  27. 27

    如何自定义Django rest框架中的[未提供身份验证凭据]错误消息

  28. 28

    在自定义列上的Django管理员自定义搜索

  29. 29

    将按钮重定向到Django管理员身份验证视图

热门标签

归档