Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom user model #971

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions backend/seismic_site/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
"django_q",
"whitenoise.runserver_nostatic",
# project apps
"users",
"utils",
"buildings",
"static_custom",
Expand Down Expand Up @@ -224,6 +225,9 @@
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


AUTH_USER_MODEL = "users.User"


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

Expand Down Expand Up @@ -305,12 +309,8 @@
STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "static"))
MEDIA_ROOT = os.path.abspath(os.path.join(BASE_DIR, "media"))

DEV_DEPENDECIES_LOCATION = "bower_components"
STATICFILES_DIRS = []

STATICFILES_DIRS = [
os.path.abspath(os.path.join(DEV_DEPENDECIES_LOCATION)),
os.path.abspath(os.path.join("static_extras")),
]

default_storage_options = {}

Expand Down
2 changes: 1 addition & 1 deletion backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ def test_user(db, django_user_model, basic_user_data):

@pytest.fixture
def basic_user_data():
return {"username": "testuser", "password": "testpassword"}
return {"email": "testuser", "password": "testpassword"}
Empty file added backend/users/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions backend/users/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions backend/users/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class UsersConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "users"
106 changes: 106 additions & 0 deletions backend/users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Generated by Django 4.2.11 on 2024-03-30 11:00

from django.db import migrations, models
import django.db.models.functions.text
import django.utils.timezone
import users.models
import uuid


class Migration(migrations.Migration):

initial = True

dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]

operations = [
migrations.CreateModel(
name="User",
fields=[
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(blank=True, null=True, verbose_name="last login")),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
("first_name", models.CharField(blank=True, max_length=150, verbose_name="first name")),
("last_name", models.CharField(blank=True, max_length=150, verbose_name="last name")),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
("date_joined", models.DateTimeField(default=django.utils.timezone.now, verbose_name="date joined")),
(
"id",
models.UUIDField(
default=uuid.uuid4,
editable=False,
primary_key=True,
serialize=False,
unique=True,
verbose_name="ID",
),
),
(
"username",
models.CharField(
blank=True,
editable=False,
help_text="Field reserved for future use",
max_length=150,
null=True,
unique=True,
verbose_name="username",
),
),
("email", models.EmailField(max_length=254, unique=True, verbose_name="email address")),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.permission",
verbose_name="user permissions",
),
),
],
managers=[
("objects", users.models.CustomUserManager()),
],
),
migrations.AddConstraint(
model_name="user",
constraint=models.UniqueConstraint(django.db.models.functions.text.Lower("email"), name="email_unique"),
),
]
Empty file.
71 changes: 71 additions & 0 deletions backend/users/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import uuid

from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.db.models.functions import Lower
from django.utils import timezone
from django.utils.translation import gettext_lazy as _


class CustomUserManager(UserManager):
def _create_user(self, email, password, **extra_fields):
"""
Create and save a user with the given email and password.
"""
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=None, password=None, **extra_fields):
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=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)

if extra_fields.get("is_staff") is not True:
raise ValueError(_("Superuser must have is_staff=True."))
if extra_fields.get("is_superuser") is not True:
raise ValueError(_("Superuser must have is_superuser=True."))

return self._create_user(email, password, **extra_fields)


class User(AbstractUser):
"""
The default Django user model, but change it to use the email address
instead of the username
"""

id = models.UUIDField(verbose_name="ID", primary_key=True, unique=True, default=uuid.uuid4, editable=False)

# We ignore the "username" field because the authentication
# will be done by email + password
username = models.CharField(
verbose_name=_("username"),
max_length=150,
unique=True,
help_text=_("Field reserved for future use"),
validators=[],
blank=True,
null=True,
editable=False,
)

email = models.EmailField(verbose_name=_("email address"), blank=False, null=False, unique=True)

objects = CustomUserManager()

USERNAME_FIELD = "email"
REQUIRED_FIELDS = []

class Meta:
constraints = [
models.UniqueConstraint(Lower("email"), name="email_unique"),
]

3 changes: 3 additions & 0 deletions backend/users/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions backend/users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
6 changes: 2 additions & 4 deletions backend/utils/management/commands/_private/seed_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
class CommonCreateUserCommand(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--username",
"--email",
type=str,
help="Username of the superuser (default: email)",
help="Email of the superuser",
required=False,
)
parser.add_argument(
Expand All @@ -34,7 +34,6 @@ def _create_user(
password: str,
is_superuser: bool,
is_staff: bool,
username: str = None,
first_name: str = "Admin",
last_name: str = "Admin",
):
Expand All @@ -49,7 +48,6 @@ def _create_user(

user = user_model(
email=admin_email,
username=username or admin_email,
first_name=first_name,
last_name=last_name,
is_active=True,
Expand Down
Loading