I'm extending AbstractBaseUser with my custom user model. I can create a superuser via shell successfully with the UserManager() below which is created in the database correctly.
For testing, I've created a superuser with the username test & password of test.
check_password()
def set_password(self, raw_password):
self.password = make_password(raw_password)
self._password = raw_password
def check_password(self, raw_password):
"""
Return a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
# Password hash upgrades shouldn't be considered password changes.
self._password = None
self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
I can run this test user against the check_password("test", "test") method which returns True as expected, but if I try to login via /admin I get "Password Incorrect" with a 200 status code on the POST.
Update: check_password does return False when given the raw password & hash
>>> u = User.objects.get(pk=1)
>>> u.check_password('test')
False
>>> u.check_password('pbkdf2_sha256$150000$sWSs4Yj3gQe1$75A2JmFurNX2oOeKJ18TvsB2G3YU6mYjIuHlaH7i6/k=')
False
Relevant app versions
Django==2.2.3
djangorestframework==3.10.1
User Model
class User(AbstractBaseUser):
USERNAME_FIELD = ('username')
REQUIRED_FIELDS = ('email', 'password')
username = models.CharField(max_length=15, unique=True)
twitch_id = models.IntegerField(null=True)
avatar = models.URLField(null=True, blank=True)
is_live = models.BooleanField(default=False)
email = models.EmailField(unique=True)
password = models.CharField(max_length=50, default="password")
register_date = models.DateTimeField(auto_now=True)
twitch_token = models.ForeignKey(TwitchToken, on_delete=models.SET_NULL, null=True)
twitter_token = models.ForeignKey(TwitterToken, on_delete=models.SET_NULL, null=True)
# attempted giving flags from original User model
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
class Meta:
db_table = 'users_user'
def __str__(self):
return self.username
"""
Properties are redundant with flags above
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
"""
UserManager()
class UserManager(BaseUserManager):
def create_user(self, username, email, password):
"""
Creates and saves a User with the given email and password.
"""
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_staffuser(self, username, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
username,
email,
password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
username,
email,
password,
)
user.is_staff = True
user.is_admin = True
user.is_active = True
user.save(using=self._db)
return user
I am explicitly stating to use django.contrib.auth.backends.ModelBackend (default) in my settings & my AUTH_USER_MODEL is set. (I have seen some use a tuple & others use a list. I've tried both, same results)
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
I suspect I'm not even hitting ModelBackend 'cause I've put some prints in the authenticate() method that aren't running, as well I have deleted the entire file & see the same results. So I suspect the issue is somewhere between Django's determination of the auth user model & actually attempting authentication.
I've looked through countless SO posts & forum posts and I'm not seeing any step of the extension process that I'm missing, but I can't get anything valuable from stack traces either.
Django ModelBackend for Reference
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
UserModel = get_user_model()
class ModelBackend:
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, True, None)
return is_active or is_active is None
def _get_user_permissions(self, user_obj):
return user_obj.user_permissions.all()
def _get_group_permissions(self, user_obj):
user_groups_field = get_user_model()._meta.get_field('groups')
user_groups_query = 'group__%s' % user_groups_field.related_query_name()
return Permission.objects.filter(**{user_groups_query: user_obj})
def _get_permissions(self, user_obj, obj, from_name):
"""
Return the permissions of `user_obj` from `from_name`. `from_name` can
be either "group" or "user" to return permissions from
`_get_group_permissions` or `_get_user_permissions` respectively.
"""
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_name = '_%s_perm_cache' % from_name
if not hasattr(user_obj, perm_cache_name):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
perms = perms.values_list('content_type__app_label', 'codename').order_by()
setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})
return getattr(user_obj, perm_cache_name)
def get_user_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from their
`user_permissions`.
"""
return self._get_permissions(user_obj, obj, 'user')
def get_group_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from the
groups they belong.
"""
return self._get_permissions(user_obj, obj, 'group')
def get_all_permissions(self, user_obj, obj=None):
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
if not hasattr(user_obj, '_perm_cache'):
user_obj._perm_cache = {
*self.get_user_permissions(user_obj),
*self.get_group_permissions(user_obj),
}
return user_obj._perm_cache
def has_perm(self, user_obj, perm, obj=None):
return user_obj.is_active and perm in self.get_all_permissions(user_obj, obj)
def has_module_perms(self, user_obj, app_label):
"""
Return True if user_obj has any permissions in the given app_label.
"""
return user_obj.is_active and any(
perm[:perm.index('.')] == app_label
for perm in self.get_all_permissions(user_obj)
)
def get_user(self, user_id):
try:
user = UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
class AllowAllUsersModelBackend(ModelBackend):
def user_can_authenticate(self, user):
return True
class RemoteUserBackend(ModelBackend):
"""
This backend is to be used in conjunction with the ``RemoteUserMiddleware``
found in the middleware module of this package, and is used when the server
is handling authentication outside of Django.
By default, the ``authenticate`` method creates ``User`` objects for
usernames that don't already exist in the database. Subclasses can disable
this behavior by setting the ``create_unknown_user`` attribute to
``False``.
"""
# Create a User object if not already in the database?
create_unknown_user = True
def authenticate(self, request, remote_user):
"""
The username passed as ``remote_user`` is considered trusted. Return
the ``User`` object with the given username. Create a new ``User``
object if ``create_unknown_user`` is ``True``.
Return None if ``create_unknown_user`` is ``False`` and a ``User``
object with the given username is not found in the database.
"""
if not remote_user:
return
user = None
username = self.clean_username(remote_user)
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if self.create_unknown_user:
user, created = UserModel._default_manager.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
if created:
user = self.configure_user(user)
else:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
return user if self.user_can_authenticate(user) else None
def clean_username(self, username):
"""
Perform any cleaning on the "username" prior to using it to get or
create the user object. Return the cleaned username.
By default, return the username unchanged.
"""
return username
def configure_user(self, user):
"""
Configure a user after creation and return the updated user.
By default, return the user unmodified.
"""
return user
class AllowAllUsersRemoteUserBackend(RemoteUserBackend):
def user_can_authenticate(self, user):
return True
The ModelBackend.authenticate method first gets the user object from the database using the get_by_natural_key method of the user models default manager, if this fails then authentication will fail
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD: username})
Because your create_user method is not setting the username field correctly this is failing
The reason why you were able to create the user even though the username field is required is probably because you are using MySQL and running in non-strict mode in which case null values will be converted to empty strings
Related
So I've customized user using the AbstractUser and then inherited two users from my custom user. The signup works just fine and registers my users. However I'm having trouble creating login logic that looks in all 2 models to find the credentials and then takes user to their respective dashboard.
Here is my models.py:
class User(AbstractUser):
is_doc = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
objects = UserManager()
class Patient(User):
address = models.CharField(max_length=210)
def __str__(self):
return self.first_name + " " + self.last_name
class Doctor(User):
address = models.CharField(max_length=210)
def __str__(self):
return self.first_name
managers.py:
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if email is None:
raise TypeError('Users must have an email address.')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_patient(self, email, password):
if password is None:
raise TypeError('Must have a password')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.is_patient = True
user.save()
def create_superuser(self, email, password):
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
views.py:
def patient_signup(request):
if request.method == 'POST':
form = forms.PatientSignUpForm(request.POST)
if form.is_valid():
models.Patient.objects.create(**form.cleaned_data)
return redirect('')
else:
form = forms.PatientSignUpForm(initial={'is_patient': True})
return render(request, 'patient_signup.html', {'form': form})
The default authentication using django.contrib.auth does not work and just redirects the same login page again (tried following the docs). So I don't have a login view logic now. How would I login my users and determine is_patient or is_doctor?
i currently try the implement my very own user model. Therefor i created a new app "accounts". But each time when i try to create anew user i get the following error:
AttributeError: 'AnonymousUser' object has no attribute '_meta'
accounts - models.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
#User Model Manager
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not username:
raise ValueError('Error: The User you want to create must have an username, try again')
user = self.model(
user=self.normalize_username(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, username, password):
"""
Creates and saves a staff user with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
#User fields
user = models.CharField(verbose_name='username',max_length=30,unique=True)
bio = models.TextField(max_length=5000, blank=True, null=True)
pubpgp = models.TextField(blank=True, null=True)
#Account typs
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'user'
REQUIRED_FIELDS = [] # Username & Password are required by default.
def get_full_name(self):
# The user is identified by their Username ;)
return self.user
def get_short_name(self):
# The user is identified by their Username address
return self.user
def __str__(self):
return self.user
def has_perm(self, perm, obj=None):
"""Does the user have a specific permission?"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""Does the user have permissions to view the app `app_label`?"""
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"""Is the user a member of staff?"""
return self.staff
#property
def is_admin(self):
"""Is the user a admin member?"""
return self.admin
#property
def is_active(self):
"""Is the user active?"""
return self.active
objects = UserManager()
After that i jumpt back to settings.py and added the custom user model to my acctual blog application:
AUTH_USER_MODEL = 'accounts.User'
and i also added
INSTALLED_APPS = [
...
'accounts',
...
]
All this user model/django stuff is a bit new to me and i have no idea what the error "AttributeError: 'Manager' object has no attribute 'get_by_natural_key'" means.
Thanks :D
Edit: AttributeError: 'UserManager' object has no attribute 'normalize_username'
normalize_username belongs to AbstractBaseUser, you can try the code below.
In signup view, when you save the form you already get the user (form.save()). Because the reason from authentication is to verify a set of credentials and getting the user (but we already have the user)
In this line: user = authenticate(username=username, password=raw_password), the authenticate method takes request as the first argument, so it should be: user = authenticate(request, username=username, password=raw_password), therefore you got the Error 'AnonymousUser' object has no attribute '_meta'.
Try:
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('post_list')
Edit UserManager:
Reaname all created users to some other name (ex. my_user) because you have tow varibales with the same name (the USERNAME_FIELD and the user created)
Here is the signature of create_user and create_superuser
create_user(*username_field*, password=None, **other_fields)
create_superuser(*username_field*, password, **other_fields)
They take the USERNAME_FIELD as the first argument, and yours is user
class UserManager(BaseUserManager):
def create_user(self, user, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not user:
raise ValueError('Error: The User you want to create must have an username, try again')
my_user = self.model(
user=self.model.normalize_username(user),
)
my_user.set_password(password)
my_user.save(using=self._db)
return my_user
def create_staffuser(self, user, password):
"""
Creates and saves a staff user with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.save(using=self._db)
return my_user
def create_superuser(self, user, password):
"""
Creates and saves a superuser with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.admin = True
my_user.save(using=self._db)
return my_user
I hope this will help.
What was done
I have a custom User model called MyUser as it is described in an full example for an custom user model on the docs and a so called UserProfile that is connected to MyUser by an One-to-one relationship like it's described in the Django documentation about how to extend an existing user model.
In the documentation for Customizing authentication is an example for how to connect a post_save signal with the existing User model.
By following this, I put an testing receiver in a signals.py that is loaded by my apps.py file, like it's described in this SO answer.
Configuration
signal.py
def post_save_receiver(sender, instance, created, **kwargs):
send_mail('Testing', "Just testing...", 'hell#earth.tld', ['admin#heaven.tld'], fail_silently=False)
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
models.py
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
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):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
views.py
def UserLogin(request):
if request.user.is_authenticated():
return HttpResponseRedirect("http://www.heaven.tld/account")
else:
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("http://www.heaven.tld/account")
else:
error_msg = 'Please try again!'
return render(request, "development",
{'form':form,
'error_msg':error_msg,
})
else:
error_msg = "Please try again!"
return render(request, "development",
{'form':form,
'error_msg':error_msg,
})
else:
form = UserLoginForm()
return render(request, "development", {'form': form})
The Problem
Now if I log in I always get this mail, but I want it only if a user was created.
Logging in causes the last_login timestamp to be updated, which triggers a save.
As others have stated, you just need to use the created parameter, which your signal receives but you currently ignore.
try:
def post_save_receiver(sender, instance, created, **kwargs):
if created:
send_mail('Testing', "Just testing...", 'hell#earth.tld', ['admin#heaven.tld'], fail_silently=False)
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
I can't understand what will be saved when you login. You can use ipdb to trace it. By the way, if you set the created condition before send_mail function, the problem should be resolved.
if created:
send_mail(...)
i try to create a custom user model for adding some custom fields to a user. i used the in django 1.5 introduced new method based on AbstractBaseUser. Everything (login) works, except for the admin-panel. When logging into the admin-interface, i get the following error:
AttributeError at /admin/
'ShopUser' object has no attribute 'is_superuser'
here's my model:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.contrib import auth
class ShopUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("We need an e-mail here...")
user = self.model(
email = ShopUserManager.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_staff = True
user.save(using=self._db)
return user
class ShopUser(AbstractBaseUser):
email = models.EmailField(
verbose_name = 'e-mail address',
max_length = 255,
unique = True,
db_index = True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = ShopUserManager()
USERNAME_FIELD = 'email'
# REQUIRED_FIELDS = ['']
def __unicode__(self):
return self.email
def has_perms(self, perm_list, obj=None):
"""
Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user has all required perms for this
object.
"""
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, app_label):
"""
Returns True if the user has any permissions in the given app label.
Uses pretty much the same logic as has_perm, above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
any advice on this? thanks!
You don't have to let your class inherit from PermissionsMixin.
I had the same problem and I fixed it by adding a few required methods to my user class (in your case ShopUser).
class ShopUser(AbstractBaseUser):
...
def get_full_name(self):
return self.fullname
def get_short_name(self):
return self.shortname
#property
def is_superuser(self):
return self.is_admin
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
Let the class ShopUser inherit from PermissionsMixin like so:
class ShopUser(AbstractBaseUser, PermissionsMixin):
This will add the is_superuser field and should play nicely with the admin UI.
Your create_superuser method should set user.is_superuser = True.
And finally, you should implement get_full_name and get_short_name for your ShopUser class.
More info here: Customizing authentication in Django
I use django 1.5 with custom model MyUser. I want to make users profile page, where he can modify only one field - 'about'.
I tried something like that:
forms.py:
class UserSettingsForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ('about')
view.py:
class UserSettings(UpdateView):
form_class = UserSettingsForm
template_name = "user/settings.html"
def get_object(self, queryset=None):
return self.request.user
def get_success_url(self):
return reverse('user_detail', args=[self.request.user.username])
urls:
url(r'^settings/$', UserSettings.as_view(), name='user_settings')
model:
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
# date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
#date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
last_name=models.CharField(max_length=30)
first_name=models.CharField(max_length=30)
about=models.TextField(blank=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['last_name','first_name','about']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
But I got error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.MyUser' that has not been installed
How can I make users profile in django 1.5? Thx!
MyUser class should be under the application named 'app' in your settings file in order for the auth framework to pick it.