feat(kadenios): Update project

This commit is contained in:
Tom Hubrecht 2024-07-09 08:46:06 +02:00
parent 1d7bace777
commit 7ae43d4d7e
18 changed files with 226 additions and 302 deletions

1
.credentials/EMAIL_HOST Normal file
View file

@ -0,0 +1 @@
localhost

1
.credentials/FROM_EMAIL Normal file
View file

@ -0,0 +1 @@
Kadenios <kadenios@localhost>

1
.credentials/SECRET_KEY Normal file
View file

@ -0,0 +1 @@
insecure-secret-key

View file

@ -0,0 +1 @@
kadenios@localhost

View file

@ -1,5 +0,0 @@
from django.contrib.staticfiles.apps import StaticFilesConfig
class IgnoreSrcStaticFilesConfig(StaticFilesConfig):
ignore_patterns = StaticFilesConfig.ignore_patterns + ["src/**"]

208
app/settings.py Normal file
View file

@ -0,0 +1,208 @@
"""
Django settings for the kadenios project
"""
from pathlib import Path
from loadcredential import Credentials
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
credentials = Credentials(env_prefix="KADENIOS_")
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# WARNING: keep the secret key used in production secret!
SECRET_KEY = credentials["SECRET_KEY"]
# WARNING: don't run with debug turned on in production!
DEBUG = credentials.get_json("DEBUG", False)
ALLOWED_HOSTS = credentials.get_json("ALLOWED_HOSTS", [])
ADMINS = credentials.get_json("ADMINS", [])
###
# List the installed applications
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"shared.IgnoreSrcStaticFilesConfig",
"background_task",
"shared",
"elections",
"faqs",
"authens",
]
###
# List the installed middlewares
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",
]
###
# The main url configuration
ROOT_URLCONF = "app.urls"
###
# Template configuration:
# - Django Templating Language is used
# - Application directories can be used
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 configuration
WSGI_APPLICATION = "app.wsgi.application"
###
# E-Mail configuration
DEFAULT_FROM_EMAIL = credentials["FROM_EMAIL"]
EMAIL_HOST = credentials["EMAIL_HOST"]
SERVER_EMAIL = credentials["SERVER_EMAIL"]
if DEBUG:
# Otherwise, use the default smtp backend
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
###
# Default primary key field type
# -> https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
###
# Database configuration
# -> https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = credentials.get_json(
"DATABASES",
{
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
},
)
###
# Authentication configuration
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",
},
]
AUTH_USER_MODEL = "elections.User"
AUTHENTICATION_BACKENDS = [
"shared.auth.backends.PwdBackend",
"shared.auth.backends.CASBackend",
"shared.auth.backends.ElectionBackend",
]
LOGIN_URL = reverse_lazy("authens:login")
LOGIN_REDIRECT_URL = "/"
AUTHENS_USE_OLDCAS = False
###
# Internationalization configuration
# -> https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "fr-fr"
TIME_ZONE = "Europe/Paris"
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
("fr", _("Français")),
("en", _("Anglais")),
]
LOCALE_PATHS = [BASE_DIR / "shared" / "locale"]
###
# Static files (CSS, JavaScript, Images) configuration
# -> https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = credentials["STATIC_ROOT"]
###
# Background tasks configuration
# -> https://django4-background-tasks.readthedocs.io/en/latest/#settings
BACKGROUND_TASK_RUN_ASYNC = True
BACKGROUND_TASK_ASYNC_THREADS = 4
if DEBUG:
INSTALLED_APPS += [
"debug_toolbar",
"django_browser_reload",
]
MIDDLEWARE += [
"debug_toolbar.middleware.DebugToolbarMiddleware",
"django_browser_reload.middleware.BrowserReloadMiddleware",
]
INTERNAL_IPS = ["127.0.0.1"]
DEBUG_TOOLBAR_CONFIG = {"INSERT_BEFORE": "</footer>"}

View file

@ -1 +0,0 @@
secret.py

View file

@ -1,151 +0,0 @@
"""
Paramètres communs entre dev et prod
"""
import os
import sys
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
# #############################################################################
# Secrets
# #############################################################################
try:
from . import secret
except ImportError:
raise ImportError(
"The secret.py file is missing.\n"
"For a development environment, simply copy secret_example.py"
)
def import_secret(name):
"""
Shorthand for importing a value from the secret module and raising an
informative exception if a secret is missing.
"""
try:
return getattr(secret, name)
except AttributeError:
raise RuntimeError("Secret missing: {}".format(name))
SECRET_KEY = import_secret("SECRET_KEY")
ADMINS = import_secret("ADMINS")
SERVER_EMAIL = import_secret("SERVER_EMAIL")
EMAIL_HOST = import_secret("EMAIL_HOST")
# #############################################################################
# Paramètres par défaut pour Django
# #############################################################################
DEBUG = False
TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"kadenios.apps.IgnoreSrcStaticFilesConfig",
"background_task",
"shared",
"elections",
"faqs",
"authens",
]
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 = "kadenios.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 = "kadenios.wsgi.application"
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
DEFAULT_FROM_EMAIL = "Kadenios <cof-geek-sysadmin@ens.fr>"
# #############################################################################
# Paramètres d'authentification
# #############################################################################
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",
},
]
AUTH_USER_MODEL = "elections.User"
AUTHENTICATION_BACKENDS = [
"shared.auth.backends.PwdBackend",
"shared.auth.backends.CASBackend",
"shared.auth.backends.ElectionBackend",
]
LOGIN_URL = reverse_lazy("authens:login")
LOGIN_REDIRECT_URL = "/"
AUTHENS_USE_OLDCAS = False
# #############################################################################
# Paramètres de langage
# #############################################################################
LANGUAGE_CODE = "fr-fr"
TIME_ZONE = "Europe/Paris"
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
("fr", _("Français")),
("en", _("Anglais")),
]
LOCALE_PATHS = [os.path.join(BASE_DIR, "shared", "locale")]
# #############################################################################
# Paramètres des fichiers statiques
# #############################################################################
STATIC_URL = "/static/"

View file

@ -1,55 +0,0 @@
"""
Paramètre pour le développement local
"""
import os
from .common import * # noqa
from .common import BASE_DIR, INSTALLED_APPS, MIDDLEWARE, TESTING
# #############################################################################
# Paramètres Django
# #############################################################################
ALLOWED_HOSTS = []
DEBUG = True
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
STATIC_URL = "/static/"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
# Use the default cache backend for local development
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
# Pas besoin de sécurité en local
AUTH_PASSWORD_VALIDATORS = []
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# #############################################################################
# Paramètres pour la Django Debug Toolbar
# #############################################################################
def show_toolbar(request):
"""
On active la debug-toolbar en mode développement local sauf :
- dans l'admin où ça ne sert pas à grand chose;
- si la variable d'environnement DJANGO_NO_DDT est à 1 → ça permet de la désactiver
sans modifier ce fichier en exécutant `export DJANGO_NO_DDT=1` dans le terminal
qui lance `./manage.py runserver`.
"""
env_no_ddt = bool(os.environ.get("DJANGO_NO_DDT", None))
return DEBUG and not env_no_ddt and not request.path.startswith("/admin/")
if not TESTING:
INSTALLED_APPS = INSTALLED_APPS + ["debug_toolbar"]
MIDDLEWARE = ["debug_toolbar.middleware.DebugToolbarMiddleware"] + MIDDLEWARE
DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": show_toolbar}

View file

@ -1,70 +0,0 @@
"""
Paramètres pour la mise en production
"""
import os
from .common import * # noqa
from .common import BASE_DIR, import_secret
# #############################################################################
# Secrets de production
# #############################################################################
REDIS_PASSWD = import_secret("REDIS_PASSWD")
REDIS_DB = import_secret("REDIS_DB")
REDIS_HOST = import_secret("REDIS_HOST")
REDIS_PORT = import_secret("REDIS_PORT")
DBNAME = import_secret("DBNAME")
DBUSER = import_secret("DBUSER")
DBPASSWD = import_secret("DBPASSWD")
# #############################################################################
# À modifier possiblement lors de la mise en production
# #############################################################################
ALLOWED_HOSTS = ["vote.eleves.ens.fr"]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
SERVER_EMAIL = "kadenios@www.eleves.ens.fr"
# #############################################################################
# Paramètres du cache
# #############################################################################
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://:{passwd}@{host}:{port}/{db}".format(
passwd=REDIS_PASSWD, host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB
),
}
}
# #############################################################################
# Paramètres de la base de données
# #############################################################################
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": DBNAME,
"USER": DBUSER,
"PASSWORD": DBPASSWD,
"HOST": os.environ.get("DBHOST", ""),
}
}
# #############################################################################
# Paramètres Https
# #############################################################################
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True

View file

@ -1,14 +0,0 @@
SECRET_KEY = "f*!6tw8c74)&k_&4$toiw@e=8m00xv_(tmjf9_#wq30wg_7n^8"
ADMINS = None
SERVER_EMAIL = "root@localhost"
EMAIL_HOST = None
DBUSER = "kadenios"
DBNAME = "kadenios"
DBPASSWD = "O1LxCADDA6Px5SiKvifjvdp3DSjfbp"
REDIS_PASSWD = "dummy"
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_HOST = "127.0.0.1"

View file

@ -1,4 +1,5 @@
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
@ -16,7 +17,8 @@ urlpatterns = [
if settings.DEBUG:
urlpatterns += [
path("admin/", admin.site.urls),
]
path("__reload__/", include("django_browser_reload.urls")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if "debug_toolbar" in settings.INSTALLED_APPS:
from debug_toolbar import urls as djdt_urls

View file

@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kadenios.settings')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
application = get_wsgi_application()

View file

@ -51,8 +51,8 @@ in
env = {
CREDENTIALS_DIRECTORY = builtins.toString ./.credentials;
CE_DEBUG = true;
CE_STATIC_ROOT = builtins.toString ./.static;
KADENIOS_DEBUG = "true";
KADENIOS_STATIC_ROOT = builtins.toString ./.static;
};
shellHook = ''

View file

@ -5,7 +5,7 @@ import sys
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kadenios.settings.local")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:

View file

@ -0,0 +1,5 @@
from django.contrib.staticfiles.apps import StaticFilesConfig
class IgnoreSrcStaticFilesConfig(StaticFilesConfig):
ignore_patterns = StaticFilesConfig.ignore_patterns + ["src/**"]

View file

@ -1,6 +1,7 @@
from django.apps import apps
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered
if settings.DEBUG:
models = apps.get_models()
@ -8,5 +9,5 @@ if settings.DEBUG:
for model in models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
except AlreadyRegistered:
pass