|
| 1 | +from django.contrib.auth.models import ( |
| 2 | + AbstractBaseUser, |
| 3 | + BaseUserManager, |
| 4 | +) |
| 5 | +from django.db import models |
| 6 | + |
| 7 | + |
| 8 | +# The custom user uses email as the unique identifier, and requires |
| 9 | +# that every user provide a date of birth. This lets us test |
| 10 | +# changes in username datatype, and non-text required fields. |
| 11 | +class CustomUserManager(BaseUserManager): |
| 12 | + def create_user(self, email, date_of_birth, password=None, **fields): |
| 13 | + """ |
| 14 | + Creates and saves a User with the given email and password. |
| 15 | + """ |
| 16 | + if not email: |
| 17 | + raise ValueError("Users must have an email address") |
| 18 | + |
| 19 | + user = self.model( |
| 20 | + email=self.normalize_email(email), date_of_birth=date_of_birth, **fields |
| 21 | + ) |
| 22 | + |
| 23 | + user.set_password(password) |
| 24 | + user.save(using=self._db) |
| 25 | + return user |
| 26 | + |
| 27 | + async def acreate_user(self, email, date_of_birth, password=None, **fields): |
| 28 | + """See create_user()""" |
| 29 | + if not email: |
| 30 | + raise ValueError("Users must have an email address") |
| 31 | + |
| 32 | + user = self.model( |
| 33 | + email=self.normalize_email(email), date_of_birth=date_of_birth, **fields |
| 34 | + ) |
| 35 | + |
| 36 | + user.set_password(password) |
| 37 | + await user.asave(using=self._db) |
| 38 | + return user |
| 39 | + |
| 40 | + def create_superuser(self, email, password, date_of_birth, **fields): |
| 41 | + u = self.create_user( |
| 42 | + email, password=password, date_of_birth=date_of_birth, **fields |
| 43 | + ) |
| 44 | + u.is_admin = True |
| 45 | + u.save(using=self._db) |
| 46 | + return u |
| 47 | + |
| 48 | + |
| 49 | +class CustomUser(AbstractBaseUser): |
| 50 | + email = models.EmailField(verbose_name="email address", max_length=255, unique=True) |
| 51 | + is_active = models.BooleanField(default=True) |
| 52 | + is_admin = models.BooleanField(default=False) |
| 53 | + date_of_birth = models.DateField() |
| 54 | + first_name = models.CharField(max_length=50) |
| 55 | + |
| 56 | + custom_objects = CustomUserManager() |
| 57 | + |
| 58 | + USERNAME_FIELD = "email" |
| 59 | + REQUIRED_FIELDS = ["date_of_birth", "first_name"] |
| 60 | + |
| 61 | + def __str__(self): |
| 62 | + return self.email |
| 63 | + |
| 64 | + # Maybe required? |
| 65 | + def get_group_permissions(self, obj=None): |
| 66 | + return set() |
| 67 | + |
| 68 | + def get_all_permissions(self, obj=None): |
| 69 | + return set() |
| 70 | + |
| 71 | + def has_perm(self, perm, obj=None): |
| 72 | + return True |
| 73 | + |
| 74 | + def has_perms(self, perm_list, obj=None): |
| 75 | + return True |
| 76 | + |
| 77 | + def has_module_perms(self, app_label): |
| 78 | + return True |
| 79 | + |
| 80 | + # Admin required fields |
| 81 | + @property |
| 82 | + def is_staff(self): |
| 83 | + return self.is_admin |
0 commit comments