I am trying to implement a Django backend for a mobile app where users authenticate through their mobile numbers only. When the user tries to login, the backend will send him an OTP so that he can login. For this use case, I think I don't need a password field. However, I think I need a password for superusers. I am thinking of a solution but I don't know whether it is a suitable solution.
models.py:
class UserManager(BaseUserManager):
def create_user(self, email, phone_number, password=None):
user = self.model(email=email, phone_number=phone_number)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, phone_number, password=None):
user = self.create_user(email, phone_number, password)
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(blank=False, null=False, unique=True)
phone_number = PhoneNumberField(blank=False, null=False, unique=True)
is_staff = models.BooleanField(default=False, blank=False, null=False)
objects = UserManager()
USERNAME_FIELD = 'phone_number'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.phone_number
Will the code above do the job?
Related
Below is my custom user model:
class CUserManager(BaseUserManager):
def _create_user(self, email, first_name, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
first_name = first_name,
is_staff=is_staff, is_active=False,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, first_name, password=None, **extra_fields):
return self._create_user(email, first_name, password, False, False,
**extra_fields)
def create_superuser(self, email, first_name, password, **extra_fields):
return self._create_user(email, first_name, password, True, True,
**extra_fields)
class CUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=False,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
last_updated = models.DateTimeField(_('last updated'), default=timezone.now)
objects = CUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
It creates a new user correctly. But when I try to authenticate the user from shell or from views, the authenticate() function doesn't work for users having is_active=False.
>>> from django.contrib.auth import get_user_model, auhtenticate
>>> u = get_user_model()
>>> authenticate(username='abc#gmail.com', password='abc)
The above line returns nothing if the user is inactive but returns the user object otherwise.
I don't understand why its returning nothing for inactive users.
It is happening because of how django's authentication works. By default it uses ModelBackend which checks for is_active https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.backends.ModelBackend.get_user_permissions
So you can create custom authentication backend which will ignore this option
https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#writing-an-authentication-backend
Hi You can write Custom backend for this problem.
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
from apps.staffs.models import Staff(Custom User)
class StaffBackend:
# Create an authentication method
# This is called by the standard Django login procedure
def authenticate(self, username=None, password=None):
try:
# Try to find a user matching your username
user = Staff.objects.get(username=username)
# Check the password is the reverse of the username
if check_password(password, user.password):
# Yes? return the Django user object
return user
else:
# No? return None - triggers default login failed
return None
except Staff.DoesNotExist:
# No user was found, return None - triggers default login failed
return None
# Required for your backend to work properly - unchanged in most scenarios
def get_user(self, user_id):
try:
return Staff.objects.get(pk=user_id)
except Staff.DoesNotExist:
return None
I'd appreciate help with a custom user modul. I set it up analog to this example in the django documentation. I have the following problems:
Login to the admin interface does not work. The login page shows up, but does not accept my credentials after creating an user with ./manage createsuperuser in the shell.
When creating a superuser, it saves initially the password in cleartext. I had a look in the database and found the password in clear text. I guess this comes from create_superuser() where user.set_password() is not used but password=password (as in the example from django docs, so why would they do that?). I changed it in the shell and then it is encrypted. Login still doesnt work tho.
My Code is as following:
authentication/models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email,
password=password,
**kwargs
)
user.is_admin=True
user.save(using=self._db)
return user
and
class MyUser(AbstractBaseUser):
# use this for auth and sessions
# REQUIRED_FIELDS = ['password']
session = models.ForeignKey(
'sessions.Session',
verbose_name='Session',
blank=True, null=True,
)
email = models.EmailField(unique=True, primary_key=True)
#password = forms.CharField(max_length=30, widget=forms.PasswordInput()) #render_value=False
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
signed_up_since = models.DateTimeField('Signed up since', default=timezone.now())
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
I edited the settings:
AUTH_USER_MODEL = "authentication.MyUser"
I dont use a custom session backend or authentication backends, did the migrations, sqlmigrations etc. Shell gives me this:
>>> user.is_staff
True
Any ideas? Thanks a lot!
The problem is that you are creating a user using self.model() in your create_user method. This leads to the password being saved as plain text.
You should use the create_user method, as in the example in the docs. This will hash the password correctly.
def create_superuser(self, email, password, **kwargs):
user = self.create_user(
email,
password=password,
**kwargs
)
Is there any way to implement form only with email field (without password and username)? User will receive email with link to confirm his account and set password.
Any information will be helpfull, thanks.
To user Temka:
I've already have cutom RegistrationForm:
from registration.forms import RegistrationForm
class UserForm(RegistrationForm):
username = forms.CharField(
max_length=254,
required=False,
widget=forms.HiddenInput(),
)
password1 = forms.CharField(
widget=forms.HiddenInput(),
required=False,
)
password2 = forms.CharField(
widget=forms.HiddenInput(),
required=False,
)
def clean_email(self):
email = self.cleaned_data['email']
self.cleaned_data['username'] = email
return email
def clean_password2(self):
pass
Also thanks for "unusable password" info.
User model
First you need to create custom User manager and model.
Documentation can be found here https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#a-full-example
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class EmailUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
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):
user = self.create_user(email, password=password,)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class EmailUser(AbstractBaseUser, PermissionsMixin):
email = EmailField(
verbose_name='email',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = EmailUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
#property
def is_staff(self):
return self.is_admin
And register it in your settings.py with this line AUTH_USER_MODEL = 'app.EmailUser'.
Now your EmailUser model can be used with from django.contrib.auth import get_user_model and from django.conf.settings import AUTH_USER_MODEL.
Example usage (foreign key):
from django.db import models
from django.conf.settings import AUTH_USER_MODEL
class Profile(models.Model):
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
user = models.OneToOneField(AUTH_USER_MODEL, verbose_name='User',
related_name='profile')
full_name = models.CharField('Full name', max_length=64, blank=False)
phone = models.CharField('Phone', max_length=64, blank=True)
Registration
When using django-registration-redux two-step registration:
Create User with None password on registration. This will make User model with unusable password https://docs.djangoproject.com/es/1.9/ref/contrib/auth/#django.contrib.auth.models.User.has_usable_password. It may be necessary to create custom RegistrationForm and RegistrationView to avoid password checking.
On activation form submit (activation form template with password field) use methods RegistrationManager.activate_user(key) and User.set_password(password)
I am trying to build a custom user model in Django. My models.py looks like this:
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError(_('The given username must be set'))
if not email:
raise ValueError(_('The given email must be set'))
email = self.normalize_email(email)
user = self.model(
username=username, email=email,
is_staff=is_staff, is_active=False,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, password=None, **extra_fields):
return self._create_user(username, email, password, False, False, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
user=self._create_user(username, email, password, True, True, **extra_fields)
user.is_active=True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
# Standard fields
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and #/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.#+-]+$'), _('Enter a valid username.'), _('invalid'))
])
first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
email = models.EmailField(_('email address'), max_length=255)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
# Custom fields
is_publisher = models.BooleanField(_('publisher status'), default=False)
# User manager
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
Anyway, if I create a super user using the createsuperuser command, everything works fine : the user is created, and the password is hashed properly and secured. However, if I create a user from my admin panel, the user created has his/her password completely exposed. Also the confirm password field doesn't show up, which it does in the regular user model used in Django. How can I solve this problem?
Also, yes I do have AUTH_USER_MODEL = 'myapp.User' in my settings.py.
You need a custom ModelForm and ModelAdmin for creating/ updating User model items.
See: Custom User Models with Admin Site
def home(request):
if request.method == 'POST':
uf = UserForm(request.POST, prefix='user')
upf = UserProfileForm(request.POST, prefix='userprofile')
if uf.is_valid() * upf.is_valid():
userform = uf.save(commit=False)
userform.password = make_password(uf.cleaned_data['password'])
userform.save()
messages.success(request,
'successful Registration',
extra_tags='safe')
else:
uf = UserForm(prefix='user')
return render_to_response('base.html',
dict(userform=uf
),
context_instance=RequestContext(request))
In your views.py try to use this and in forms.py try to get the password from django form. Hope this works
A form with no custom code, and direct access to password field, writes directly on the password field. No call is made to createuser or createsuperuser, so set_password is never called (by default, a ModelForm calls save in the model when called save in it). Recall that writing the user password does not write a secure password (that's why createuser and createsuperuser call set_password somewhere). To do that, avoid writing directly on the field but, instead, calling:
myuserinstance.set_password('new pwd')
# not this:
# myuserinstance.password = 'new pwd'
So you must use custom logic in a custom form. See the implementation for details; you will notice those forms have custom logic calling set_password and check_password. BTW default UserAdmin in Django creates a user in TWO steps: user/password/password_confirm (such password creates), and then whole user data. There's a very custom implementation for that.
I have created a custom user in my django project that inherits from AbstractBaseUser and PermissionsMixin.
class CustomUserManager(BaseUserManager):
def _create_user(self, username, password, is_staff, is_superuser, email=None, **extrafields):
now = timezone.now()
if not username:
raise ValueError("You must specify a username first")
if email:
email = self.normalize_email(email)
user = self.model(username=username, email=email, is_superuser=is_superuser,
is_staff=is_staff, is_active=True, last_login=now,
date_joined=now, **extrafields)
user.set_password(password)
user.save(self._db)
return user
def create_user(self, username, password=None, email=None, **extrafields):
return self._create_user(username, password, False, False, email=email, **extrafields)
def create_superuser(self, username, password, email=None, **extrafields):
return self._create_user(username, password, True, True, email=email, **extrafields)
class MyCustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(_("email address"), max_length=254, unique=True, blank=True, null=True)
first_name = models.CharField(max_length=30, blank=True)
#more custom user fields
I have set the settings attribute
settings.AUTH_USER_MODEL = "users.MyCustomUser"
and used this user as a ForeignKey to another model
class Customer(models.Model):
creator = models.ForeignKey(settings.AUTH_USER_MODEL)
another_model = models.ForeignKey(AnotherModel)
When I run the migrate function it gives me the error described on the title. If i comment out creator field it works (so only the creator foreignkey is causing an issue). I didn't have this problem with sqlite3 and and Django 1.6. I am now in Django 1.8.x and changed to MySQL (locally for developement)and having this issue. Has something changed?