Initial commit

This commit is contained in:
Keannu Christian Bernasol 2024-11-23 21:55:32 +08:00
commit ccd7c5873c
22 changed files with 921 additions and 0 deletions

View file

View file

@ -0,0 +1,16 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
model = CustomUser
list_display = ("id", "full_name", "role", "is_active")
readonly_fields = ("date_joined",)
# Add this line to include the role field in the admin form
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("role",)}),)
admin.site.register(CustomUser, CustomUserAdmin)

View file

@ -0,0 +1,11 @@
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "accounts"
def ready(self):
import accounts.signals
return super().ready()

View file

@ -0,0 +1,146 @@
# Generated by Django 5.1.3 on 2024-11-23 13:04
import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]
operations = [
migrations.CreateModel(
name="CustomUser",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("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",
),
),
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"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"
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
(
"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",
),
),
(
"role",
models.CharField(
choices=[
("head", "Head"),
("admin", "Admin"),
("client", "Client"),
("planning", "Planning"),
("staff", "Staff"),
],
default="client",
max_length=32,
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, editable=False
),
),
(
"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",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]

View file

@ -0,0 +1,18 @@
# Generated by Django 5.1.3 on 2024-11-23 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("accounts", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="customuser",
name="email",
field=models.EmailField(max_length=254, unique=True),
),
]

View file

@ -0,0 +1,39 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.timezone import now
class CustomUser(AbstractUser):
# first_name inherited from base user class
# last_name inherited from base user class
# username inherited from base user class
# password inherited from base user class
# is_admin inherited from base user class
email = models.EmailField(blank=False, unique=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
ROLE_CHOICES = (
("head", "Head"),
("admin", "Admin"),
("client", "Client"),
("planning", "Planning"),
("staff", "Staff"),
)
role = models.CharField(max_length=32, choices=ROLE_CHOICES, default="client")
date_joined = models.DateTimeField(default=now, editable=False)
@property
def full_name(self):
return f"{self.first_name} {self.last_name}"
def save(self, **kwargs):
self.username = self.email
if self.is_staff:
self.role = "staff"
elif self.is_superuser:
self.role = "admin"
super().save(**kwargs)

View file

@ -0,0 +1,65 @@
from .models import CustomUser
from rest_framework import serializers
from django.contrib.auth.password_validation import validate_password
from django.core import exceptions as django_exceptions
from rest_framework.settings import api_settings
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = [
"id",
"username",
"email",
"first_name",
"last_name",
"full_name",
"role",
]
read_only_fields = ["id", "username", "email", "full_name", "role"]
class CustomUserRegistrationSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
password = serializers.CharField(
write_only=True, style={"input_type": "password", "placeholder": "Password"}
)
first_name = serializers.CharField(
required=True, allow_blank=False, allow_null=False
)
last_name = serializers.CharField(
required=True, allow_blank=False, allow_null=False
)
class Meta:
model = CustomUser
fields = ["email", "password", "first_name", "last_name"]
def validate(self, attrs):
user_attrs = attrs.copy()
user = self.Meta.model(**user_attrs)
password = attrs.get("password")
try:
validate_password(password, user)
except django_exceptions.ValidationError as e:
serializer_error = serializers.as_serializer_error(e)
errors = serializer_error[api_settings.NON_FIELD_ERRORS_KEY]
if len(errors) > 1:
raise serializers.ValidationError({"password": errors[0]})
else:
raise serializers.ValidationError({"password": errors})
if self.Meta.model.objects.filter(username=attrs.get("username")).exists():
raise serializers.ValidationError(
"A user with that username already exists."
)
return super().validate(attrs)
def create(self, validated_data):
user = self.Meta.model(**validated_data)
user.is_active = False
user.set_password(validated_data["password"])
user.save()
return user

View file

@ -0,0 +1,23 @@
from config.settings import get_secret
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from .models import CustomUser
@receiver(post_migrate)
def create_admin_user(sender, **kwargs):
# Programatically creates the administrator account
if sender.name == "accounts":
ADMIN_USER = CustomUser.objects.filter(email=get_secret("ADMIN_EMAIL")).first()
if not ADMIN_USER:
ADMIN_USER = CustomUser.objects.create_superuser(
username=get_secret("ADMIN_EMAIL"),
email=get_secret("ADMIN_EMAIL"),
password=get_secret("ADMIN_PASSWORD"),
)
print("Created administrator account:", ADMIN_USER.email)
ADMIN_USER.first_name = "Administrator"
ADMIN_USER.is_active = True
ADMIN_USER.save()

View file

@ -0,0 +1,7 @@
from django.urls import include, path
urlpatterns = [
path("", include("djoser.urls")),
path("", include("djoser.urls.jwt")),
]

View file

@ -0,0 +1,52 @@
import re
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
class UppercaseValidator(object):
def validate(self, password, user=None):
if not re.findall("[A-Z]", password):
raise ValidationError(
_("The password must contain at least 1 uppercase letter (A-Z).")
)
def get_help_text(self):
return _("Your password must contain at least 1 uppercase letter (A-Z).")
class LowercaseValidator(object):
def validate(self, password, user=None):
if not re.findall("[a-z]", password):
raise ValidationError(
_("The password must contain at least 1 lowercase letter (a-z).")
)
def get_help_text(self):
return _("Your password must contain at least 1 lowercase letter (a-z).")
class SpecialCharacterValidator(object):
def validate(self, password, user=None):
if not re.findall("[@#$%^&*()_+/\<>;:!?]", password):
raise ValidationError(
_(
"The password must contain at least 1 special character (@, #, $, etc.)."
)
)
def get_help_text(self):
return _(
"Your password must contain at least 1 special character (@, #, $, etc.)."
)
class NumberValidator(object):
def validate(self, password, user=None):
if not any(char.isdigit() for char in password):
raise ValidationError(
_("The password must contain at least one numerical digit (0-9).")
)
def get_help_text(self):
return _("Your password must contain at least numerical digit (0-9).")