From a38d324bdba634cfc3fd0e681441164babe972ae Mon Sep 17 00:00:00 2001 From: Kumi Date: Sat, 21 May 2022 17:06:18 +0200 Subject: [PATCH] Initial commit Custom user model Preparations for module/template discovery --- .gitignore | 5 + config.dist.ini | 2 + core/__init__.py | 0 core/admin/__init__.py | 9 ++ core/admin/user.py | 10 ++ core/apps.py | 6 ++ core/forms/__init__.py | 0 core/forms/admin/__init__.py | 0 core/forms/admin/user.py | 12 +++ core/managers.py | 42 ++++++++ core/migrations/0001_initial.py | 28 ++++++ core/migrations/__init__.py | 0 core/models/__init__.py | 1 + core/models/auth.py | 55 +++++++++++ core/modules/__init__.py | 0 core/modules/discovery.py | 17 ++++ core/templates/__init__.py | 0 core/templates/discovery.py | 17 ++++ core/tests.py | 3 + core/views.py | 3 + doc/database.dbs | 107 +++++++++++++++++++++ manage.py | 22 +++++ modules/__init__.py | 0 requirements.txt | 4 + restoroo/__init__.py | 0 restoroo/asgi.py | 16 ++++ restoroo/settings.py | 165 ++++++++++++++++++++++++++++++++ restoroo/urls.py | 21 ++++ restoroo/wsgi.py | 16 ++++ templates/__init__.py | 0 30 files changed, 561 insertions(+) create mode 100644 .gitignore create mode 100644 config.dist.ini create mode 100644 core/__init__.py create mode 100644 core/admin/__init__.py create mode 100644 core/admin/user.py create mode 100644 core/apps.py create mode 100644 core/forms/__init__.py create mode 100644 core/forms/admin/__init__.py create mode 100644 core/forms/admin/user.py create mode 100644 core/managers.py create mode 100644 core/migrations/0001_initial.py create mode 100644 core/migrations/__init__.py create mode 100644 core/models/__init__.py create mode 100644 core/models/auth.py create mode 100644 core/modules/__init__.py create mode 100644 core/modules/discovery.py create mode 100644 core/templates/__init__.py create mode 100644 core/templates/discovery.py create mode 100644 core/tests.py create mode 100644 core/views.py create mode 100644 doc/database.dbs create mode 100755 manage.py create mode 100644 modules/__init__.py create mode 100644 requirements.txt create mode 100644 restoroo/__init__.py create mode 100644 restoroo/asgi.py create mode 100644 restoroo/settings.py create mode 100644 restoroo/urls.py create mode 100644 restoroo/wsgi.py create mode 100644 templates/__init__.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..540f05e --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +venv/ +*.pyc +__pycache__/ +config.ini +db.sqlite3 \ No newline at end of file diff --git a/config.dist.ini b/config.dist.ini new file mode 100644 index 0000000..d9bf612 --- /dev/null +++ b/config.dist.ini @@ -0,0 +1,2 @@ +[RESTOROO] +Debug = 1 # Do not run with debug turned on in production! \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/admin/__init__.py b/core/admin/__init__.py new file mode 100644 index 0000000..24aeb6f --- /dev/null +++ b/core/admin/__init__.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from django.contrib.auth.models import Group + +from ..models import User +from .user import UserAdmin + + +admin.site.register(User, UserAdmin) +admin.site.unregister(Group) \ No newline at end of file diff --git a/core/admin/user.py b/core/admin/user.py new file mode 100644 index 0000000..c47f319 --- /dev/null +++ b/core/admin/user.py @@ -0,0 +1,10 @@ +from django.contrib.admin import ModelAdmin + +from ..forms.admin.user import AdminUserForm + + +class UserAdmin(ModelAdmin): + """ + Admin page for Restoroo User objects in the (original) Django admin + """ + form = AdminUserForm \ No newline at end of file diff --git a/core/apps.py b/core/apps.py new file mode 100644 index 0000000..8115ae6 --- /dev/null +++ b/core/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'core' diff --git a/core/forms/__init__.py b/core/forms/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/forms/admin/__init__.py b/core/forms/admin/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/forms/admin/user.py b/core/forms/admin/user.py new file mode 100644 index 0000000..f711931 --- /dev/null +++ b/core/forms/admin/user.py @@ -0,0 +1,12 @@ +from django.forms import ModelForm, PasswordInput + +from ...models.auth import User + + +class AdminUserForm(ModelForm): + """ + Form for Restoroo User objects in the (original) Django admin backend + """ + class Meta: + model = User + fields = ["email"] diff --git a/core/managers.py b/core/managers.py new file mode 100644 index 0000000..e0778d0 --- /dev/null +++ b/core/managers.py @@ -0,0 +1,42 @@ +from django.contrib.auth.base_user import BaseUserManager +from django.utils.translation import gettext_lazy as _ + + +class UserManager(BaseUserManager): + """ + Custom user manager for Restoroo + """ + + def create_user(self, email: str, password: str, **extra_fields): + """ + Create new User object with given email and password + + Args: + email (str): Email address to use for the User object – must be unique + password (str): Password to use for the User object + """ + + if not email: + raise ValueError(_("%{variable} must be set") % + {"variable": "email"}) + + email = self.normalize_email(email) + + user = self.model(email=email, **extra_fields) + user.set_password(password) + user.save() + + return user + + def create_superuser(self, email: str, password: str, **extra_fields): + """ + Create new User with is_superuser set to True + + Args: + email (str): Email address to use for the User object – must be unique + password (str): Password to use for the User object + """ + + extra_fields["is_superuser"] = True + + return self.create_user(email, password, **extra_fields) diff --git a/core/migrations/0001_initial.py b/core/migrations/0001_initial.py new file mode 100644 index 0000000..72b7b46 --- /dev/null +++ b/core/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 4.0.4 on 2022-05-21 11:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='User', + 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')), + ('email', models.EmailField(max_length=254, unique=True, verbose_name='email')), + ('is_superuser', models.BooleanField(default=False)), + ('is_active', models.BooleanField(default=True)), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/core/migrations/__init__.py b/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/models/__init__.py b/core/models/__init__.py new file mode 100644 index 0000000..611c4d8 --- /dev/null +++ b/core/models/__init__.py @@ -0,0 +1 @@ +from .auth import User \ No newline at end of file diff --git a/core/models/auth.py b/core/models/auth.py new file mode 100644 index 0000000..ece830a --- /dev/null +++ b/core/models/auth.py @@ -0,0 +1,55 @@ +from django.db import models +from django.contrib.auth.models import AbstractBaseUser +from django.utils.translation import gettext_lazy as _ + +from ..managers import UserManager + + +class User(AbstractBaseUser): + """ + Custom user model for Restoroo + """ + + email = models.EmailField(_("email"), unique=True) + is_superuser = models.BooleanField(default=False) + is_active = models.BooleanField(default=True) + + USERNAME_FIELD = "email" + REQUIRED_FIELDS = [] + + objects = UserManager() + + @property + def is_staff(self) -> bool: + """ + Returns value of is_superuser - required by Django admin backend + + TODO - Remove this after implementing custom admin backend + + Returns: + bool: Value of is_superuser + """ + return self.is_superuser + + def has_module_perms(self, *args, **kwargs) -> bool: + """ + Returns value of is_superuser - required by Django admin backend + + TODO - Remove this after implementing custom admin backend + + Returns: + bool: Value of is_superuser + """ + + return self.is_superuser + + has_perm = has_module_perms + + def __str__(self): + """ + Returns string representation for User object + + Returns: + str: Value of email + """ + return self.email diff --git a/core/modules/__init__.py b/core/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/modules/discovery.py b/core/modules/discovery.py new file mode 100644 index 0000000..6f5e6fd --- /dev/null +++ b/core/modules/discovery.py @@ -0,0 +1,17 @@ +from importlib import import_module +from logging import Logger + +from django.conf import settings + + +logger = Logger("core.modules.discovery") + +modules = [] + +for f in (settings.BASE_DIR / "modules").glob("*"): + if f.is_dir() and f.name.isalnum(): + try: + import_module("modules." + f.name) + modules.append(f.name) + except Exception as e: + logger.info(f"Could not import module {f.name}: {e}") \ No newline at end of file diff --git a/core/templates/__init__.py b/core/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/templates/discovery.py b/core/templates/discovery.py new file mode 100644 index 0000000..8fdcf47 --- /dev/null +++ b/core/templates/discovery.py @@ -0,0 +1,17 @@ +from importlib import import_module +from logging import Logger + +from django.conf import settings + + +logger = Logger("core.templates.discovery") + +templates = [] + +for f in (settings.BASE_DIR / "templates").glob("*"): + if f.is_dir() and f.name.isalnum(): + try: + import_module("templates." + f.name) + templates.append(f.name) + except Exception as e: + logger.info(f"Could not import template {f.name}: {e}") \ No newline at end of file diff --git a/core/tests.py b/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/core/views.py b/core/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/core/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/doc/database.dbs b/doc/database.dbs new file mode 100644 index 0000000..ccd7e35 --- /dev/null +++ b/doc/database.dbs @@ -0,0 +1,107 @@ + + + + + + +
+ +
+ + + +
+ + + + +
+ +
+ + + +
+ + + +
+ + + +
+ + + + + +
+ + +
+ + + + + +
+ + + +
+ + + + + + + +
+ +
+
+
+ + + + + + + + + + + + + +
+ +
+ + + +
+
+ + + + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..bcf2475 --- /dev/null +++ b/manage.py @@ -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', 'restoroo.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() diff --git a/modules/__init__.py b/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3b646ad --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +Django +django-autosecretkey +dbsettings +argon2-cffi \ No newline at end of file diff --git a/restoroo/__init__.py b/restoroo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/restoroo/asgi.py b/restoroo/asgi.py new file mode 100644 index 0000000..cabc0a3 --- /dev/null +++ b/restoroo/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for restoroo 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/4.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restoroo.settings') + +application = get_asgi_application() diff --git a/restoroo/settings.py b/restoroo/settings.py new file mode 100644 index 0000000..a2e913a --- /dev/null +++ b/restoroo/settings.py @@ -0,0 +1,165 @@ +import os + +from pathlib import Path + +from autosecretkey import AutoSecretKey + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +CONFIG_FILE = AutoSecretKey(BASE_DIR / "config.ini", + template=BASE_DIR / "config.dist.ini") + +SECRET_KEY = CONFIG_FILE.secret_key +DEBUG = CONFIG_FILE.config["RESTOROO"]["Debug"] + +ALLOWED_HOSTS = ["*"] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + 'core', +] + +AUTH_USER_MODEL = "core.User" + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'restoroo.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 = 'restoroo.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.Argon2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', + 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', + 'django.contrib.auth.hashers.ScryptPasswordHasher', +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +# L10N / I18N settings + +LANGUAGE_COOKIE_NAME = "restoroo_language" +LOCALE_PATHS = [BASE_DIR / "locale"] + +# Logging settings + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'formatter': 'default', + }, + }, + 'root': { + 'handlers': ['console'], + 'level': 'WARNING', + }, + 'loggers': { + 'django.server': { + 'handlers': ['console'], + 'level': 'ERROR', + 'propagate': False, + }, + 'django': { + 'handlers': ['console'], + 'level': os.getenv('RESTOROO_LOG_LEVEL', 'INFO'), + 'propagate': False, + }, + }, + 'formatters': { + 'default': { + 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', + 'style': '{', + } + }, +} diff --git a/restoroo/urls.py b/restoroo/urls.py new file mode 100644 index 0000000..cd0320f --- /dev/null +++ b/restoroo/urls.py @@ -0,0 +1,21 @@ +"""restoroo URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/restoroo/wsgi.py b/restoroo/wsgi.py new file mode 100644 index 0000000..1948dc0 --- /dev/null +++ b/restoroo/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for restoroo 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/4.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restoroo.settings') + +application = get_wsgi_application() diff --git a/templates/__init__.py b/templates/__init__.py new file mode 100644 index 0000000..e69de29