Skip to content

Commit 1e36145

Browse files
committed
Add EmailBasedUserManager
1 parent 0c75b1d commit 1e36145

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

django_utils_lib/auth.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from django.contrib.auth import get_user_model
2+
from django.contrib.auth.base_user import BaseUserManager
3+
from django.contrib.auth.password_validation import validate_password
4+
from typing_extensions import NotRequired, TypedDict
5+
6+
7+
class BaseUserCreationArgs(TypedDict):
8+
"""
9+
A starting point for strongly-typing the creation parameters associated with creating
10+
a new user.
11+
"""
12+
13+
is_staff: NotRequired[bool]
14+
is_active: NotRequired[bool]
15+
is_superuser: NotRequired[bool]
16+
17+
18+
class EmailBasedUserManager(BaseUserManager):
19+
"""
20+
It is commonly useful to change the default Django User model to use emails instead of usernames
21+
22+
This is a custom user manager that helps to facilitate this.
23+
24+
NOTE: This manager assumes that you have registered your custom User (for use with this manager,
25+
and as as the User "creator") in `settings.py`, with `AUTH_USER_MODEL = "your.model.path"`
26+
"""
27+
28+
use_in_migrations = True
29+
30+
def _create_user(self, email: str, password: str, **extra_fields):
31+
if not email:
32+
raise ValueError("The given email must be set")
33+
email = self.normalize_email(email)
34+
validate_password(password)
35+
user = get_user_model().objects.create(email=email, password=password, **extra_fields)
36+
user.set_password(password)
37+
user.save()
38+
return user
39+
40+
def create_user(self, email: str, password: str, **extra_fields):
41+
extra_fields.setdefault("is_active", True)
42+
extra_fields.setdefault("is_staff", False)
43+
extra_fields.setdefault("is_superuser", False)
44+
return self._create_user(email, password, **extra_fields)
45+
46+
def create_superuser(self, email: str, password: str, **extra_fields):
47+
extra_fields.setdefault("is_active", True)
48+
extra_fields.setdefault("is_staff", True)
49+
extra_fields.setdefault("is_superuser", True)
50+
51+
if extra_fields.get("is_staff") is not True:
52+
raise ValueError("Superuser must have is_staff=True.")
53+
if extra_fields.get("is_superuser") is not True:
54+
raise ValueError("Superuser must have is_superuser=True.")
55+
56+
return self._create_user(email, password, **extra_fields)

0 commit comments

Comments
 (0)