aboutsummaryrefslogtreecommitdiffstats
path: root/alphabetlearning/users/managers.py
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-10-15 21:01:31 +0100
committerMatthew Lemon <y@yulqen.org>2024-10-15 21:01:31 +0100
commiteeaddb27560d723ca7d61359744ceb2709fccd2d (patch)
tree04ddbc49ae7b73d5f5a9e1716d7227aecd3b9f85 /alphabetlearning/users/managers.py
parent7a3044c859043837e6c7c95bb4894d04e9b2cbc2 (diff)
Renamed from pyblackbird_cc to alphabetlearning - everywhere
Diffstat (limited to 'alphabetlearning/users/managers.py')
-rw-r--r--alphabetlearning/users/managers.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/alphabetlearning/users/managers.py b/alphabetlearning/users/managers.py
new file mode 100644
index 0000000..d8beaa4
--- /dev/null
+++ b/alphabetlearning/users/managers.py
@@ -0,0 +1,42 @@
+from typing import TYPE_CHECKING
+
+from django.contrib.auth.hashers import make_password
+from django.contrib.auth.models import UserManager as DjangoUserManager
+
+if TYPE_CHECKING:
+ from .models import User # noqa: F401
+
+
+class UserManager(DjangoUserManager["User"]):
+ """Custom manager for the User model."""
+
+ def _create_user(self, email: str, password: str | None, **extra_fields):
+ """
+ Create and save a user with the given email and password.
+ """
+ if not email:
+ msg = "The given email must be set"
+ raise ValueError(msg)
+ email = self.normalize_email(email)
+ user = self.model(email=email, **extra_fields)
+ user.password = make_password(password)
+ user.save(using=self._db)
+ return user
+
+ def create_user(self, email: str, password: str | None = None, **extra_fields): # type: ignore[override]
+ extra_fields.setdefault("is_staff", False)
+ extra_fields.setdefault("is_superuser", False)
+ return self._create_user(email, password, **extra_fields)
+
+ def create_superuser(self, email: str, password: str | None = None, **extra_fields): # type: ignore[override]
+ extra_fields.setdefault("is_staff", True)
+ extra_fields.setdefault("is_superuser", True)
+
+ if extra_fields.get("is_staff") is not True:
+ msg = "Superuser must have is_staff=True."
+ raise ValueError(msg)
+ if extra_fields.get("is_superuser") is not True:
+ msg = "Superuser must have is_superuser=True."
+ raise ValueError(msg)
+
+ return self._create_user(email, password, **extra_fields)