Initial commit

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

20
.env.sample Normal file
View file

@ -0,0 +1,20 @@
SECRET_KEY = "SECRET_KEY_HERE"
DEBUG = "True"
PROJECT_NAME = "Document Manager Backend"
TIMEZONE = "Asia/Manila"
BACKEND_PORT = 8000
FRONTEND_ADDRESS = 'localhost'
FRONTEND_PORT = 4200
USE_HTTPS = 'False' # Set this to 443 in production (HTTPS)
# SMTP (Email)
EMAIL_HOST = 'inbucket'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = '1025'
EMAIL_USE_TLS = 'False'
EMAIL_ADDRESS = 'noreply.dev@mehdns.06222001.xyz'
# Admin Credentials
ADMIN_EMAIL = 'admin@test.com'
ADMIN_PASSWORD = ''

167
.gitignore vendored Normal file
View file

@ -0,0 +1,167 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
db.sqlite3
db.sqlite3-journal
.env
media/
static/
TODO.md
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
**/__pycache__/
.vscode/

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).")

View file

View file

@ -0,0 +1,22 @@
from config.settings import MEDIA_ROOT
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include, path
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
urlpatterns = [
path("accounts/", include("accounts.urls")),
path("admin/", admin.site.urls),
path("schema/", SpectacularAPIView.as_view(), name="schema"),
path(
"swagger/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"
),
path("redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static("media/", document_root=MEDIA_ROOT)

View file

View file

@ -0,0 +1,16 @@
"""
ASGI config for docmanager_backend project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
application = get_asgi_application()

View file

@ -0,0 +1,231 @@
"""
Django settings for docmanager_backend project.
Generated by "django-admin startproject" using Django 5.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
from pathlib import Path
import os
from datetime import timedelta
from dotenv import find_dotenv, load_dotenv # Python dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
# Backend folder (/docmanager_backend)
BASE_DIR = Path(__file__).resolve().parent.parent
# Root folder where .env is located
ROOT_DIR = Path(__file__).resolve().parent.parent.parent
load_dotenv(find_dotenv())
def get_secret(secret_name):
# Read from .env
secret_value = os.getenv(secret_name)
if secret_value is None:
raise ValueError(f"Secret '{secret_name}' not found.")
else:
# Parse Boolean values
if secret_value == "True":
secret_value = True
elif secret_value == "False":
secret_value = False
return secret_value
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_secret("SECRET_KEY")
# SECURITY WARNING: don"t run with debug turned on in production!
DEBUG = get_secret("DEBUG")
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
"unfold",
"unfold.contrib.filters",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework_simplejwt",
"djoser",
"corsheaders",
"drf_spectacular",
"drf_spectacular_sidecar",
"accounts",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "config.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
"OPTIONS": {
"min_length": 8,
},
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
# Additional password validators
{
"NAME": "accounts.validators.SpecialCharacterValidator",
},
{
"NAME": "accounts.validators.LowercaseValidator",
},
{
"NAME": "accounts.validators.UppercaseValidator",
},
{
"NAME": "accounts.validators.NumberValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = get_secret("TIMEZONE")
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
MEDIA_URL = "api/v1/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
ROOT_URLCONF = "config.urls"
STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {"anon": "360/min", "user": "1440/min"},
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
SPECTACULAR_SETTINGS = {
"TITLE": get_secret("PROJECT_NAME"),
"VERSION": "1.0.0",
"SERVE_INCLUDE_SCHEMA": False,
}
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
}
DJOSER = {
"SEND_ACTIVATION_EMAIL": True,
"SEND_CONFIRMATION_EMAIL": True,
"PASSWORD_RESET_CONFIRM_URL": "reset_password_confirm/{uid}/{token}",
"ACTIVATION_URL": "activation/{uid}/{token}",
"USER_AUTHENTICATION_RULES": ["djoser.authentication.TokenAuthenticationRule"],
"SERIALIZERS": {
"user": "accounts.serializers.CustomUserSerializer",
"current_user": "accounts.serializers.CustomUserSerializer",
"user_create": "accounts.serializers.CustomUserRegistrationSerializer",
},
"PERMISSIONS": {
# Disable some unneeded endpoints by setting them to admin only
"username_reset": ["rest_framework.permissions.IsAdminUser"],
"username_reset_confirm": ["rest_framework.permissions.IsAdminUser"],
"set_username": ["rest_framework.permissions.IsAdminUser"],
"set_password": ["rest_framework.permissions.IsAdminUser"],
},
}
# SMTP (Email)
EMAIL_HOST = get_secret("EMAIL_HOST")
EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD")
EMAIL_PORT = get_secret("EMAIL_PORT")
EMAIL_USE_TLS = get_secret("EMAIL_USE_TLS")
EMAIL_ADDRESS = get_secret("EMAIL_ADDRESS")
DEFAULT_FROM_EMAIL = EMAIL_ADDRESS
AUTH_USER_MODEL = "accounts.CustomUser"
DATA_UPLOAD_MAX_NUMBER_FIELDS = 20480

View file

@ -0,0 +1,5 @@
from django.urls import path, include
urlpatterns = [
path("api/v1/", include("api.urls")),
]

View file

@ -0,0 +1,16 @@
"""
WSGI config for docmanager_backend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
application = get_wsgi_application()

View file

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

45
requirements.txt Normal file
View file

@ -0,0 +1,45 @@
asgiref==3.8.1
attrs==24.2.0
black==24.10.0
certifi==2024.8.30
cffi==1.17.1
charset-normalizer==3.4.0
click==8.1.7
colorama==0.4.6
cryptography==43.0.3
defusedxml==0.8.0rc2
Django==5.1.3
django-cors-headers==4.6.0
django-rest-framework==0.1.0
django-unfold==0.41.0
djangorestframework==3.15.2
djangorestframework-simplejwt==5.3.1
djoser==2.3.1
drf-spectacular==0.27.2
drf-spectacular-sidecar==2024.11.1
gunicorn==23.0.0
idna==3.10
inflection==0.5.1
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
mypy-extensions==1.0.0
oauthlib==3.2.2
packaging==24.2
pathspec==0.12.1
platformdirs==4.3.6
pycparser==2.22
PyJWT==2.10.0
python-dotenv==1.0.1
python3-openid==3.2.0
PyYAML==6.0.2
referencing==0.35.1
requests==2.32.3
requests-oauthlib==2.0.0
rpds-py==0.21.0
social-auth-app-django==5.4.2
social-auth-core==4.5.4
sqlparse==0.5.2
tzdata==2024.2
uritemplate==4.1.1
urllib3==2.2.3
whitenoise==6.8.2