Dynavera/apps/users/managers.py

28 lines
1.2 KiB
Python
Raw Normal View History

2025-11-19 12:55:15 +00:00
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import BaseUserManager
from typing import TYPE_CHECKING
2025-11-19 12:55:15 +00:00
if TYPE_CHECKING:
2025-12-07 15:19:59 +00:00
from apps.users.models import User
2025-11-19 12:55:15 +00:00
class UserManager(BaseUserManager["User"]):
def _create_user(self, email_address: str, password: str | None, **extra_fields):
if not email_address:
raise ValueError("The given email must be set")
2025-11-19 12:55:15 +00:00
email_address = self.normalize_email(email_address)
user: User = self.model(email_address=email_address, **extra_fields)
user.password = make_password(password)
user.save(using=self._db)
return user
2025-12-07 15:19:59 +00:00
def create_user(self, email_address: str, password: str | None = None, **extra_fields):
2025-11-19 12:55:15 +00:00
extra_fields.setdefault("is_staff", False)
return self._create_user(email_address, password, **extra_fields)
2025-12-07 15:19:59 +00:00
def create_superuser(self, email_address: str, password: str | None = None, **extra_fields):
2025-11-19 12:55:15 +00:00
extra_fields.setdefault("is_staff", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
2025-11-19 12:55:15 +00:00
return self._create_user(email_address, password, **extra_fields)