【问题标题】:Unable to store hashed password in database in django无法在 django 的数据库中存储散列密码
【发布时间】:2019-05-31 09:00:38
【问题描述】:

我通过扩展 AbstractBaseUser 使用自定义用户模型。然而,尽管在自定义用户管理器中调用 set_password,我无法在我的 postgres 数据库中存储散列密码。

我按照以下链接给出的解决方案进行了操作,但没有成功:-

Django: set_password isn't hashing passwords?

以下是我的模型和管理器代码

models.py

from django.contrib.auth.models import PermissionsMixin
from django.contrib.gis.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import InterestedUserManager


# Create your models here.

class User(AbstractBaseUser, PermissionsMixin):

    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=False, unique=True)
    phone_no = models.CharField(max_length=10, blank=False)
    address = models.CharField(max_length=100, blank=False)


    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')

    def __str__(self):
        return "%s %s -- %s" % (self.first_name, self.last_name, self.address)

managers.py

from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        print("User object is ",user)
        print("User password is ".user.password)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True')

        return self._create_user(email, password, **extra_fields)

views.py

class RegisterUserSerializer(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    queryset = User.objects.all()

    # override create method of ListCreateAPIView to include token
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

序列化器.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User

        fields = ('first_name', 'last_name', 'email', 'password', 'phone_no', 'address')

settings.py

...

"""
Django settings for djan project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'rest_framework',
    'knox',
    'rest_framework_gis',  # rest framework for GIS
    'server',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

ROOT_URLCONF = 'djan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djan.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        #db credentials goes here
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'knox.auth.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'server.InterestedUser'


...

例如,如果您在shell 中运行以下命令。

User.objects.create( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )

然后,密码以纯文本形式存储在我的 postgres 数据库中。

【问题讨论】:

  • 您正在尝试实现自己的用户表?
  • 是的,我有我的自定义用户模型
  • 我添加了答案,检查一下。

标签: django django-rest-framework


【解决方案1】:

如果你想要散列密码,你应该尝试这种方式,而不是使用create() 方法。

user = InterestedUser( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", phone_no="9944002255")
user.set_password('test@123')
user.save()

希望对你有帮助。

【讨论】:

    【解决方案2】:

    你可以简单地使用:

    User.objects.<b>create_user</b>( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )

    create_user 是一个管理器方法,它在您的custom model managerUserManager 中定义。

    【讨论】:

      猜你喜欢
      • 2014-09-25
      • 2011-03-30
      • 2023-03-10
      • 2013-02-16
      • 2023-03-04
      • 2019-06-18
      • 2013-07-25
      • 2011-08-23
      • 2011-01-20
      相关资源
      最近更新 更多