Make usernames case-insensitive.

This commit is contained in:
Casper V. Kristensen 2019-11-20 23:24:19 +01:00
parent d4341e5d0b
commit 39d423e437
Signed by: caspervk
GPG key ID: 289CA03790535054

View file

@ -1,4 +1,5 @@
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager as DjangoUserManager
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator, MinLengthValidator from django.core.validators import RegexValidator, MinLengthValidator
from django.db import models, transaction from django.db import models, transaction
@ -20,6 +21,11 @@ class Rank(models.Model):
return self.name return self.name
class UserManager(DjangoUserManager):
def get_by_natural_key(self, username):
return super().get_by_natural_key(self.model.normalize_username(username))
class User(AbstractUser): class User(AbstractUser):
first_name = None first_name = None
last_name = None last_name = None
@ -37,15 +43,25 @@ class User(AbstractUser):
blank=True blank=True
) )
objects = UserManager()
class Meta: class Meta:
ordering = ["rank", "username"] ordering = ["rank", "username"]
def clean(self): def clean(self):
self.username = self.normalize_username(self.username)
if not hasattr(self, "rank"): if not hasattr(self, "rank"):
self.rank = Rank.objects.last() self.rank = Rank.objects.last()
if hasattr(self, "main") and self.main.user != self: if hasattr(self, "main") and self.main.user != self:
raise ValidationError({"main": "Main character must be owned by user."}) raise ValidationError({"main": "Main character must be owned by user."})
@classmethod
def normalize_username(cls, username):
"""
Make username case-insensitive.
"""
return super().normalize_username(username).lower()
@transaction.atomic @transaction.atomic
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not hasattr(self, "main"): if not hasattr(self, "main"):