密码字段在Django管理站点可见且未加密

8gsdolmq  于 2023-02-05  发布在  Go
关注(0)|答案(4)|浏览(111)

因此,要使用email作为用户名,我将覆盖内置的User模型,如下所示(受Django source code启发)

    • 型号. py**
class User(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    objects = UserManager()
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email
    • 管理员py**
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {"fields": ("email", "password")}),
        (("Personal info"), {"fields": ("first_name", "last_name")}),
        (
            ("Permissions"),
            {
                "fields": (
                    "is_active",
                    "is_staff",
                    "is_superuser",
                    "groups",
                    "user_permissions",
                ),
            },
        ),
        (("Important dates"), {"fields": ("last_login", "date_joined")}),
    )
    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": ("email", "password1", "password2"),
            },
        ),
    )
    list_display = ("email", "is_active", "is_staff", "is_superuser")
    list_filter = ("is_active", "is_staff", "is_superuser")
    search_fields = ("email",)
    ordering = ("email",)
    filter_horizontal = ("groups", "user_permissions",)

但这是当我去管理员网站更改用户时的样子:

密码可见未散列,且无更改密码表单链接。
与默认Django项目的外观比较:

密码不可见并且有一个指向更改密码表单的链接
很明显我漏掉了什么但我不知道是什么。

ogsagwnx

ogsagwnx1#

Django Admin外观的问题很可能与继承有关,更准确地说,将类改为从UserAdmin继承。

from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin

class UserAdmin(DefaultUserAdmin):

这样做会使它看起来更接近默认的Django项目。
密码没有加密的问题很可能是因为它在数据库. OP has this question中没有加密,这不是Django管理员的问题。

    • 注:**
  • 当我想删除username时,我也使用AbstractUser
  • 由于当前的问题没有足够的信息来回答pwd被散列的问题,我将把它留给OP's other question
mklgxw1f

mklgxw1f2#

您无法看到散列状态的密码,因为password字段是一个CharField,它将其呈现为普通文本字段。在Django的管理端,django.contrib.auth.forms中有一个名为ReadOnlyPasswordHashField的字段,它将密码字段呈现为散列状态,并带有密码更改链接。
Django的UserAdmin使用不同的表单类来创建和更新用户。

form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm

要编辑用户详细信息,UserAdmin使用form = UserChangeForm(源代码),其中密码字段设置为ReadOnlyPasswordHashField(源代码)。

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField(
        label=_("Password"),
        help_text=_(
            "Raw passwords are not stored, so there is no way to see this "
            "user’s password, but you can change the password using "
            '<a href="{}">this form</a>.'
        ),
    )

因此,只是通过继承UserAdmindjango.contrib.auth.admin将使密码处于散列状态与所有其他要素,如在默认管理网站中看到的用户.

您可以简单地从django.contrib.auth.forms导入UserChangeForm并在自定义UserAdmin中设置form = UserChangeForm

from django.contrib.auth.forms import UserChangeForm,AdminPasswordChangeForm

# code

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    # code
    form = UserChangeForm
    change_password_form = AdminPasswordChangeForm
    # code
w6mmgewl

w6mmgewl3#

DjangoDocumentation清楚地解释了如何在Django中定制认证

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 django.core.exceptions import ValidationError

from customauth.models import MyUser

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

    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')

    def clean_password2(self):
        # Check 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 ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().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 fields on
    the user, but replaces the password field with admin's
    disabled password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')

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

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('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', 'date_of_birth', 'password1', 'password2'),
        }),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
klsxnrf1

klsxnrf14#

一种方法是在admin.py中为UserAdmin定义一个自定义字段集。

fieldsets = (
    (None, {"fields": ("username")}),
    (_("Personal info"), {"fields": ("first_name", "last_name", "email")}),
    (
        _("Permissions"),
        {
            "fields": (
                "is_active",
                "is_staff",
                "is_superuser",
                "groups",
                "user_permissions",
            ),
        },
    ),
    (_("Important dates"), {"fields": ("last_login", "date_joined")}),
)

相关问题