Initial commit

Custom user model
Preparations for module/template discovery
This commit is contained in:
Kumi 2022-05-21 17:06:18 +02:00
commit a38d324bdb
30 changed files with 561 additions and 0 deletions

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
venv/
*.pyc
__pycache__/
config.ini
db.sqlite3

2
config.dist.ini Normal file
View file

@ -0,0 +1,2 @@
[RESTOROO]
Debug = 1 # Do not run with debug turned on in production!

0
core/__init__.py Normal file
View file

9
core/admin/__init__.py Normal file
View file

@ -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)

10
core/admin/user.py Normal file
View file

@ -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

6
core/apps.py Normal file
View file

@ -0,0 +1,6 @@
from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'

0
core/forms/__init__.py Normal file
View file

View file

12
core/forms/admin/user.py Normal file
View file

@ -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"]

42
core/managers.py Normal file
View file

@ -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)

View file

@ -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,
},
),
]

View file

1
core/models/__init__.py Normal file
View file

@ -0,0 +1 @@
from .auth import User

55
core/models/auth.py Normal file
View file

@ -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

0
core/modules/__init__.py Normal file
View file

17
core/modules/discovery.py Normal file
View file

@ -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}")

View file

View file

@ -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}")

3
core/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
core/views.py Normal file
View file

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

107
doc/database.dbs Normal file
View file

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8" ?>
<project name="Restoroo" id="Project-8d5" database="LogicalDesign" >
<schema name="INSTANCE" catalogname="Restoroo" >
<table name="Chain" prior="entity" >
<column name="name" type="VARCHAR" length="100" jt="12" />
<column name="logo" type="BLOB" jt="1111" />
</table>
<table name="Commission Invoice" prior="entity" />
<table name="Delivery Area" prior="entity" >
<column name="area_definition" type="TEXT" jt="-1" />
<column name="minimum_order" type="DECIMAL" jt="3" />
<column name="price" type="DECIMAL" jt="3" />
</table>
<table name="Extras" prior="entity" >
<column name="name" type="VARCHAR" length="100" jt="12" />
<column name="description" type="TEXT" jt="-1" />
<column name="price" type="DECIMAL" jt="3" />
</table>
<table name="Media" prior="entity" />
<table name="Menu Item" prior="entity" >
<column name="name" type="VARCHAR" length="100" jt="12" />
<column name="description" type="TEXT" jt="-1" />
<column name="price" type="DECIMAL" jt="3" />
</table>
<table name="Order" prior="entity" >
<column name="status" type="CHAR" length="1" jt="1" />
<column name="remarks" type="TEXT" jt="-1" />
</table>
<table name="Order Item" prior="entity" >
<column name="remarks" type="TEXT" jt="-1" />
<column name="price" type="DECIMAL" jt="3" />
</table>
<table name="Payment" prior="entity" >
<column name="amount" type="DECIMAL" jt="3" />
<column name="transaction_id" type="VARCHAR" length="100" jt="12" />
<column name="gateway" type="VARCHAR" length="100" jt="12" />
<column name="fee" type="DECIMAL" jt="3" />
</table>
<table name="Permission" prior="entity" >
<column name="permission_type" type="VARCHAR" length="20" jt="12" />
</table>
<table name="Profile" prior="Provile" >
<column name="first_name" type="VARCHAR" length="100" jt="12" />
<column name="last_name" type="VARCHAR" length="100" jt="12" />
<column name="display_name" type="VARCHAR" length="100" jt="12" />
<column name="profile_image" type="BLOB" jt="1111" />
</table>
<table name="Reservation" prior="entity" >
<column name="persons" type="INT" jt="4" />
<column name="remarks" type="TEXT" jt="-1" />
</table>
<table name="Restaurant" prior="entity" >
<column name="name" type="VARCHAR" length="100" jt="12" />
<column name="address*" type="TEXT" length="100" jt="-1" />
<column name="email" type="VARCHAR" length="100" jt="12" />
<column name="phone" type="VARCHAR" length="100" jt="12" />
<column name="logo" type="BLOB" jt="1111" />
<column name="coordinates*" type="DECIMAL" jt="3" />
</table>
<table name="Restaurant Area" prior="Restaurant Areas" />
<table name="Restaurant Setting" prior="entity" />
<table name="Review" prior="review" />
<table name="Schedule" prior="Delivery Schedule" >
<column name="priority" type="DECIMAL" jt="3" />
<column name="valid_from" type="DATE" jt="91" mandatory="y" >
<defo><![CDATA[sysdate]]></defo>
</column>
<column name="valid_until" type="DATE" jt="91" />
<column name="opening" type="INT" jt="4" />
<column name="closing" type="INT" jt="4" />
<column name="day_of_week" type="ENUM" jt="12" >
<enumeration><![CDATA[0,1,2,3,4,5,6]]></enumeration>
</column>
<column name="schedule_type" type="ENUM" jt="12" >
<enumeration><![CDATA["delivery","pickup","open"]]></enumeration>
</column>
</table>
<table name="Table" prior="entity" />
<table name="User" prior="entity" >
<column name="username" type="VARCHAR" length="100" jt="12" />
<column name="email" type="VARCHAR" length="100" jt="12" />
<column name="password" type="VARCHAR" length="100" jt="12" />
</table>
</schema>
<connector name="MyDb" database="MySql" host="localhost" port="3306" user="root" />
<layout name="Default Layout" id="Layout-55f" show_relation="columns" >
<entity schema="Restoroo.INSTANCE" name="Chain" color="C1D8EE" x="656" y="240" />
<entity schema="Restoroo.INSTANCE" name="Commission Invoice" color="C1D8EE" x="656" y="96" />
<entity schema="Restoroo.INSTANCE" name="Delivery Area" color="C1D8EE" x="512" y="656" />
<entity schema="Restoroo.INSTANCE" name="Extras" color="C1D8EE" x="80" y="720" />
<entity schema="Restoroo.INSTANCE" name="Media" color="C1D8EE" x="816" y="240" />
<entity schema="Restoroo.INSTANCE" name="Menu Item" color="C1D8EE" x="80" y="576" />
<entity schema="Restoroo.INSTANCE" name="Order" color="C1D8EE" x="224" y="240" />
<entity schema="Restoroo.INSTANCE" name="Order Item" color="C1D8EE" x="208" y="400" />
<entity schema="Restoroo.INSTANCE" name="Payment" color="C1D8EE" x="48" y="240" />
<entity schema="Restoroo.INSTANCE" name="Permission" color="C1D8EE" x="416" y="224" />
<entity schema="Restoroo.INSTANCE" name="Profile" color="C1D8EE" x="416" y="48" />
<entity schema="Restoroo.INSTANCE" name="Reservation" color="C1D8EE" x="304" y="560" />
<entity schema="Restoroo.INSTANCE" name="Restaurant" color="C1D8EE" x="432" y="384" />
<entity schema="Restoroo.INSTANCE" name="Restaurant Area" color="C1D8EE" x="448" y="576" />
<entity schema="Restoroo.INSTANCE" name="Restaurant Setting" color="C1D8EE" x="736" y="432" />
<entity schema="Restoroo.INSTANCE" name="Review" color="C1D8EE" x="96" y="416" />
<entity schema="Restoroo.INSTANCE" name="Schedule" color="C1D8EE" x="720" y="592" />
<entity schema="Restoroo.INSTANCE" name="Table" color="C1D8EE" x="400" y="656" />
<entity schema="Restoroo.INSTANCE" name="User" color="C1D8EE" x="176" y="48" />
</layout>
</project>

22
manage.py Executable file
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', '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()

0
modules/__init__.py Normal file
View file

4
requirements.txt Normal file
View file

@ -0,0 +1,4 @@
Django
django-autosecretkey
dbsettings
argon2-cffi

0
restoroo/__init__.py Normal file
View file

16
restoroo/asgi.py Normal file
View file

@ -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()

165
restoroo/settings.py Normal file
View file

@ -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': '{',
}
},
}

21
restoroo/urls.py Normal file
View file

@ -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),
]

16
restoroo/wsgi.py Normal file
View file

@ -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()

0
templates/__init__.py Normal file
View file