Feat/monolith auth (#15)

* feat: add monolith, auth check

* chore: tasks, lint

* feat: login portal via django

* fix: url redirect

fix: monolith settings gaps
This commit is contained in:
Marc 2022-12-04 23:26:37 -05:00
parent d2f97a867d
commit 3de891d537
Signed by: marc
GPG key ID: 048E042F22B5DC79
27 changed files with 345 additions and 8 deletions

3
services/monolith/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
*.sqlite3
spadinaistan-monolith.venv
__pycache__

View file

@ -0,0 +1 @@
3.9.15

View file

@ -0,0 +1,11 @@
FROM python:3.9.15
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY ./requirements.txt ./requirements.txt
RUN pip install -r ./requirements.txt
CMD ["python", "src/manage.py", "runserver", "0.0.0.0:8000"]

View file

@ -0,0 +1,22 @@
version: "3.7"
services:
monolith:
build: .
ports:
- "8000:8000"
environment:
- SPADINAISTAN_ENV=prod
volumes:
- ./src:/app/src
labels:
- traefik.http.routers.monolith.rule=Host(`spadinaistan.karnov.club`) && PathPrefix(`/app/`)
- traefik.http.routers.monolith.tls=true
- traefik.http.routers.monolith.tls.certresolver=lets-encrypt
- traefik.http.services.monolith.loadbalancer.server.port=8000
- traefik.enable=true
networks:
default:
name: web
external: true

View file

@ -0,0 +1,2 @@
django
django-extensions

View file

@ -0,0 +1,16 @@
#
# This file is autogenerated by pip-compile with python 3.9
# To update, run:
#
# pip-compile ./requirements.in
#
asgiref==3.5.2
# via django
django==4.1.3
# via
# -r ./requirements.in
# django-extensions
django-extensions==3.2.1
# via -r ./requirements.in
sqlparse==0.4.3
# via django

View file

@ -0,0 +1,14 @@
#!/bin/bash
VENV="spadinaistan-monolith.venv"
python -m pip install pip==22.3 pip-tools==6.9.0 --no-cache
if [ ! -d "./$VENV" ]; then
python -m venv ./$VENV
fi
source ./$VENV/bin/activate
pip-sync ./requirements.txt

View file

@ -0,0 +1,4 @@
#!/bin/bash
pip-compile ./requirements.in

View file

View file

View file

@ -0,0 +1,16 @@
"""
ASGI config for monolith 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")
application = get_asgi_application()

View file

@ -0,0 +1,126 @@
import os
from pathlib import Path
ENVIRONMENT = os.getenv("SPADINAISTAN_ENV", "dev")
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-_=k!twt-5o^rw$&fishn18n8pcw2(!z3#k(+$e)=ehorx7!q^("
DEBUG = ENVIRONMENT == "dev"
ALLOWED_HOSTS_PROD = ["spadinaistan.karnov.club"]
ALLOWED_HOSTS_DEV = ["localhost.karnov.club", "monolith", "localhost"]
ALLOWED_HOSTS = ALLOWED_HOSTS_PROD if ENVIRONMENT == "prod" else ALLOWED_HOSTS_DEV
BASE_HOST = ALLOWED_HOSTS[0]
CSRF_TRUSTED_ORIGINS=["https://spadinaistan.karnov.club"]
USE_X_FORWARDED_HOST = True
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_extensions",
"base",
"identity",
]
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 = "base.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 = "base.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/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",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/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.1/howto/static-files/
STATIC_URL = "app/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

View file

@ -0,0 +1,24 @@
"""monolith URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/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, include
import identity.urls
urlpatterns = [path("app/", include([
path("admin/", admin.site.urls),
path("identity/", include(identity.urls.url_patterns)),
]))]

View file

@ -0,0 +1,16 @@
"""
WSGI config for monolith 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")
application = get_wsgi_application()

View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View file

@ -0,0 +1,6 @@
from django.apps import AppConfig
class IdentityConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "identity"

View file

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View file

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

View file

@ -0,0 +1,5 @@
import django.urls
import identity.views
url_patterns = [django.urls.path("me/", identity.views.identity_check)]

View file

@ -0,0 +1,13 @@
import django.http
import django.shortcuts
import django.conf
def identity_check(request: django.http.HttpRequest) -> django.http.HttpResponse:
"""
Verifies if the requesting user is logged in.
"""
if request.user.is_authenticated:
return django.http.HttpResponse(status=200)
return django.shortcuts.redirect("https://spadinaistan.karnov.club/app/admin/")

22
services/monolith/src/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", "base.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()

View file

@ -0,0 +1,29 @@
import invoke
import pathlib
PATH = pathlib.Path(__file__).parent
@invoke.task()
def start(ctx):
with ctx.cd(PATH):
ctx.run("docker-compose up -d")
@invoke.task()
def stop(ctx):
with ctx.cd(PATH):
ctx.run("docker-compose down")
@invoke.task()
def restart(ctx):
with ctx.cd(PATH):
ctx.run("docker-compose restart")
ns = invoke.Collection("monolith")
ns.add_task(start)
ns.add_task(restart)
ns.add_task(stop)

View file

@ -21,7 +21,7 @@
[providers.docker]
watch = true
useBindPortIP = true
network = "kong-net"
network = "web"
exposedByDefault = false
[providers.file]

View file

@ -1,14 +1,11 @@
[http.routers.api]
rule = "Host(`spadinaistan.karnov.club`)"
entrypoints = ["websecure"]
middlewares = ["simpleAuth"]
middlewares = ["monolith-auth"]
service = "api@internal"
[http.routers.api.tls]
certResolver = "lets-encrypt"
[http.middlewares.simpleAuth.basicAuth]
users = [
"admin:$apr1$rKQCDINk$Q2eQm14Xi/tzIoXi/UsKq/"
]
[http.middlewares.monolith-auth.forwardauth]
address = "http://monolith:8000/app/identity/me/"

View file

@ -3,6 +3,7 @@ import invoke
import services.plex.tasks
import services.deluge.tasks
import services.traefik.tasks
import services.monolith.tasks
ns = invoke.Collection()
@ -26,7 +27,7 @@ server.add_task(system_reboot, name="reboot")
ns.add_collection(server)
ns.add_collection(services.monolith.tasks.ns)
ns.add_collection(services.plex.tasks.ns)
ns.add_collection(services.traefik.tasks.ns)
ns.add_collection(services.deluge.tasks.ns)