Django registration redux registration only with email (no password) - python

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)

Related

How to add an extra field in auth user model in django admin?

I want to customize my existing auth user model.
I need the command or code for executing the solution?
from datetime import datetime
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
import uuid
from django.db import models
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=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)
class User(models.Model, AbstractUser):
"""Custom user model"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)
username = models.UUIDField(default=uuid.uuid4, editable=False)
email = models.EmailField(_('email address'), unique=True,
help_text='User personal unique email')
date_of_birth = models.DateField(blank=True, null=True)
last_pass_change = models.DateTimeField(default=datetime.now)
forgot_password = models.BooleanField(default=False)
user_ip = models.CharField(default='', max_length=128)
"""You can other fields based on your requirements."""
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
Then add AUTH_USER_MODEL = 'your_app_name.User' in your Django project settings.py file.So from now you will get proper flexibility of User model.So you have to run 2 commands-
python manage.py makemigrations
python manage.py migrate
So from now, you can check from Django admin page or browse the database. I hope this solution might help you.

I have extended my Django model from AbstractUser, how do I query the extended model to get date_joined of the user?

I have created a model class which extends from AbstractUser to handle token authentication, how do I get date_joined property of the modal's object when querying it in django rest framework views.py?
Models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from .managers import CustomUserManager
# Create your models here.
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
date_of_birth = models.DateField(blank=True, null=True)
def __str__(self):
return self.email
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False, blank=True, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
def __str__(self):
return self.title
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Here is my Managers.py
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password,**extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=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)
This my drf view:
#api_view(['GET'])
#permission_classes([IsAuthenticated])
def report2(request):
user_data = CustomUser.objects.get(id=request.user.id)
print("User data ",user_data)
return Response("date_joined", status=status.HTTP_200_OK)
The user_data only returns email_id, I expect it to return all the attributes of the table including date_joined.
Below is an image from my database:
Kindly someone guide me, how can I get date_joined attribute of the CustomUser object in my view function?
Thanks

Making password required for admins, but unusable for users

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?

Django admin Login page giving error "incorrect username password" although I am using correct

This is my model class
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
class UserProfileManager(BaseUserManager):
"""Helps Djamgo work with our custom user model"""
def create_user(self,email,name,password=None):
if not email:
raise ValueError('users must have an email address')
#normalizing the email address convert it to the lowercase
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,name,password):
user = self.create_user(email,name,password)
user.is_superuser =True
user.is_staff = True
class UserProfile(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(max_length=255,unique = True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
related_name = "+"
object = UserProfileManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ['name']
#helper funtionality
def full_name(self):
"""Use to get full name of the user"""
return self.name
def short_name(self):
"""Use to get short name name of the user"""
return self.name
def __str__(self):
`enter code here`return self.email
My setting.py contains everything
and my db is sync and I have already created a superuser. When I am trying to access my admin from admin login page it gives an error "please login with correct email password " But I have already ensured 5 times that I am using correct email password!

Why isn't my password being secured when using a custom user model in Django?

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.

Categories

Resources