Vineet
Vineet

Reputation: 783

Unable to store hashed password in database in django

I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database.

I followed the solution given at the below link but it didn't work:-

Django: set_password isn't hashing passwords?

Folloing is my code for models and managers

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'


...

For example if you run following command in shell.

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

Then, password is getting stored as plain text in my postgres database.

Upvotes: 2

Views: 917

Answers (2)

ruddra
ruddra

Reputation: 51938

You can simply use:

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

create_user is a manager method, which is defined in your custom model manager class UserManager.

Upvotes: 2

gachdavit
gachdavit

Reputation: 1261

You should try this way and not use create() method, if you want hashed password.

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

Hope, it helps you.

Upvotes: 1

Related Questions