无法在Django的数据库中存储哈希密码

时间:2019-05-31 09:00:38

标签: django django-rest-framework

我正在通过扩展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]
        })

serializers.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数据库中。

2 个答案:

答案 0 :(得分:1)

您可以简单地使用:

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

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

答案 1 :(得分:0)

如果要散列密码,则应尝试这种方式,不要使用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()

希望,对您有帮助。