diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..7369480 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.editorconfig +.gitattributes +.github +.gitignore +.gitlab-ci.yml +.idea +.pre-commit-config.yaml +.readthedocs.yml +.travis.yml +venv +.git diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c0ce342 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.{html,css,scss,json,yml,xml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab + +[default.conf] +indent_style = space +indent_size = 2 diff --git a/.envs/.local/.django b/.envs/.local/.django new file mode 100644 index 0000000..bcde257 --- /dev/null +++ b/.envs/.local/.django @@ -0,0 +1,4 @@ +# General +# ------------------------------------------------------------------------------ +USE_DOCKER=yes +IPYTHONDIR=/app/.ipython diff --git a/.envs/.local/.postgres b/.envs/.local/.postgres new file mode 100644 index 0000000..4dcf22f --- /dev/null +++ b/.envs/.local/.postgres @@ -0,0 +1,7 @@ +# PostgreSQL +# ------------------------------------------------------------------------------ +POSTGRES_HOST=postgres +POSTGRES_PORT=5432 +POSTGRES_DB=flamerelay +POSTGRES_USER=WoQBkuTicxdqzZQnFKTjAmTbBoDalbmW +POSTGRES_PASSWORD=GogoUeguUn8RETooJHKLAIhmMm4HUrmp7QTJKiLGUoNxo0QDoGbrAPNG2JZMpqhf diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9e2dcb0 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,91 @@ +# Config for Dependabot updates. See Documentation here: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + # Update GitHub actions in workflows + - package-ecosystem: 'github-actions' + directory: '/' + # Every weekday + schedule: + interval: 'daily' + + # Enable version updates for Docker + # We need to specify each Dockerfile in a separate entry because Dependabot doesn't + # support wildcards or recursively checking subdirectories. Check this issue for updates: + # https://github.com/dependabot/dependabot-core/issues/2178 + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/local/django` directory + directory: 'compose/local/django/' + # Every weekday + schedule: + interval: 'daily' + # Ignore minor version updates (3.10 -> 3.11) but update patch versions + ignore: + - dependency-name: '*' + update-types: + - 'version-update:semver-major' + - 'version-update:semver-minor' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/local/docs` directory + directory: 'compose/local/docs/' + # Every weekday + schedule: + interval: 'daily' + # Ignore minor version updates (3.10 -> 3.11) but update patch versions + ignore: + - dependency-name: '*' + update-types: + - 'version-update:semver-major' + - 'version-update:semver-minor' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/local/node` directory + directory: 'compose/local/node/' + # Every weekday + schedule: + interval: 'daily' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/production/aws` directory + directory: 'compose/production/aws/' + # Every weekday + schedule: + interval: 'daily' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/production/django` directory + directory: 'compose/production/django/' + # Every weekday + schedule: + interval: 'daily' + # Ignore minor version updates (3.10 -> 3.11) but update patch versions + ignore: + - dependency-name: '*' + update-types: + - 'version-update:semver-major' + - 'version-update:semver-minor' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/production/postgres` directory + directory: 'compose/production/postgres/' + # Every weekday + schedule: + interval: 'daily' + + - package-ecosystem: 'docker' + # Look for a `Dockerfile` in the `compose/production/traefik` directory + directory: 'compose/production/traefik/' + # Every weekday + schedule: + interval: 'daily' + + # Enable version updates for Python/Pip - Production + - package-ecosystem: 'pip' + # Look for a `requirements.txt` in the `root` directory + # also 'setup.cfg', 'runtime.txt' and 'requirements/*.txt' + directory: '/' + # Every weekday + schedule: + interval: 'daily' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b45a33e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +# Enable Buildkit and let compose use it to speed up image building +env: + DOCKER_BUILDKIT: 1 + COMPOSE_DOCKER_CLI_BUILD: 1 + +on: + pull_request: + branches: ['master', 'main'] + paths-ignore: ['docs/**'] + + push: + branches: ['master', 'main'] + paths-ignore: ['docs/**'] + +concurrency: + group: ${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + linter: + runs-on: ubuntu-latest + steps: + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.11' + # Consider using pre-commit.ci for open source project + - name: Run pre-commit + uses: pre-commit/action@v3.0.0 + + # With no caching at all the entire ci process takes 4m 30s to complete! + pytest: + runs-on: ubuntu-latest + + steps: + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Build the Stack + run: docker-compose -f local.yml build + + - name: Run DB Migrations + run: docker-compose -f local.yml run --rm django python manage.py migrate + + - name: Run Django Tests + run: docker-compose -f local.yml run django pytest + + - name: Tear down the Stack + run: docker-compose -f local.yml down diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a72f3f --- /dev/null +++ b/.gitignore @@ -0,0 +1,281 @@ +### Python template +# 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/ +*.egg-info/ +.installed.cfg +*.egg + +# 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/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +staticfiles/ + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# pyenv +.python-version + + + +# Environments +.venv +venv/ +ENV/ + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +### Node template +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + + +### Linux template +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + + +### VisualStudioCode template +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + + + + + +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### macOS template +# General +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### SublimeText template +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + + +### Vim template +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] + +# Session +Session.vim + +# Temporary +.netrwhist + +# Auto-generated tag files +tags + +# Redis dump file +dump.rdb + +### Project template +flamerelay/media/ + +.pytest_cache/ +.ipython/ +.env +.envs/* +!.envs/.local/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e3ba250 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,58 @@ +exclude: '^docs/|/migrations/' +default_stages: [commit] + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-json + - id: check-toml + - id: check-xml + - id: check-yaml + - id: debug-statements + - id: check-builtin-literals + - id: check-case-conflict + - id: check-docstring-first + - id: detect-private-key + + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v3.0.0-alpha.9-for-vscode + hooks: + - id: prettier + args: ['--tab-width', '2', '--single-quote'] + exclude: 'flamerelay/templates/' + + - repo: https://github.com/adamchainz/django-upgrade + rev: "1.13.0" + hooks: + - id: django-upgrade + args: ["--target-version", "4.1"] + + - repo: https://github.com/asottile/pyupgrade + rev: v3.3.2 + hooks: + - id: pyupgrade + args: [--py311-plus] + + - repo: https://github.com/psf/black + rev: 23.3.0 + hooks: + - id: black + + - repo: https://github.com/PyCQA/isort + rev: 5.12.0 + hooks: + - id: isort + + - repo: https://github.com/PyCQA/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + +# sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date +ci: + autoupdate_schedule: weekly + skip: [] + submodules: false diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..d5a8ef6 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,20 @@ +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the version of Python and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: '3.11' + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: docs/conf.py + +# Python requirements required to build your docs +python: + install: + - requirements: requirements/local.txt diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt new file mode 100644 index 0000000..d68af72 --- /dev/null +++ b/CONTRIBUTORS.txt @@ -0,0 +1 @@ +Jonas Vacek diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d9af8f3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ + +The MIT License (MIT) +Copyright (c) 2023, Jonas Vacek + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..3394cdb --- /dev/null +++ b/Procfile @@ -0,0 +1,2 @@ +release: python manage.py migrate +web: gunicorn config.wsgi:application diff --git a/README.md b/README.md new file mode 100644 index 0000000..2d2282c --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# FlameRelay + +A silly little Django project for tracking the journey of many lighters + +[![Built with Cookiecutter Django](https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg?logo=cookiecutter)](https://github.com/cookiecutter/cookiecutter-django/) +[![Black code style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) + +License: MIT + +## Settings + +Moved to [settings](http://cookiecutter-django.readthedocs.io/en/latest/settings.html). + +## Basic Commands + +### Setting Up Your Users + +- To create a **normal user account**, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go. + +- To create a **superuser account**, use this command: + + $ python manage.py createsuperuser + +For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users. + +### Type checks + +Running type checks with mypy: + + $ mypy flamerelay + +### Test coverage + +To run the tests, check your test coverage, and generate an HTML coverage report: + + $ coverage run -m pytest + $ coverage html + $ open htmlcov/index.html + +#### Running tests with pytest + + $ pytest + +### Live reloading and Sass CSS compilation + +Moved to [Live reloading and SASS compilation](https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html#sass-compilation-live-reloading). + +### Email Server + +In development, it is often nice to be able to see emails that are being sent from your application. For that reason local SMTP server [MailHog](https://github.com/mailhog/MailHog) with a web interface is available as docker container. + +Container mailhog will start automatically when you will run all docker containers. +Please check [cookiecutter-django Docker documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html) for more details how to start all containers. + +With MailHog running, to view messages that are sent by your application, open your browser and go to `http://127.0.0.1:8025` + +### Sentry + +Sentry is an error logging aggregator service. You can sign up for a free account at or download and host it yourself. +The system is set up with reasonable defaults, including 404 logging and integration with the WSGI application. + +You must set the DSN url in production. + +## Deployment + +The following details how to deploy this application. + +### Heroku + +See detailed [cookiecutter-django Heroku documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html). + +### Docker + +See detailed [cookiecutter-django Docker documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html). diff --git a/compose/local/django/Dockerfile b/compose/local/django/Dockerfile new file mode 100644 index 0000000..d3b947c --- /dev/null +++ b/compose/local/django/Dockerfile @@ -0,0 +1,67 @@ +# define an alias for the specific python version used in this file. +FROM python:3.11.3-slim-bullseye as python + +# Python build stage +FROM python as python-build-stage + +ARG BUILD_ENVIRONMENT=local + +# Install apt packages +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements . + +# Create Python Dependency and Sub-Dependency Wheels. +RUN pip wheel --wheel-dir /usr/src/app/wheels \ + -r ${BUILD_ENVIRONMENT}.txt + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT=local +ARG APP_HOME=/app + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 +ENV BUILD_ENV ${BUILD_ENVIRONMENT} + +WORKDIR ${APP_HOME} + +# Install required system dependencies +RUN apt-get update && apt-get install --no-install-recommends -y \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels/ + +# use wheels to install python dependencies +RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ + && rm -rf /wheels/ + +COPY ./compose/production/django/entrypoint /entrypoint +RUN sed -i 's/\r$//g' /entrypoint +RUN chmod +x /entrypoint + +COPY ./compose/local/django/start /start +RUN sed -i 's/\r$//g' /start +RUN chmod +x /start + + + +# copy application code to WORKDIR +COPY . ${APP_HOME} + +ENTRYPOINT ["/entrypoint"] diff --git a/compose/local/django/start b/compose/local/django/start new file mode 100644 index 0000000..13d412f --- /dev/null +++ b/compose/local/django/start @@ -0,0 +1,9 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python manage.py migrate +exec python manage.py runserver 0.0.0.0:8000 diff --git a/compose/local/docs/Dockerfile b/compose/local/docs/Dockerfile new file mode 100644 index 0000000..8239a66 --- /dev/null +++ b/compose/local/docs/Dockerfile @@ -0,0 +1,62 @@ +# define an alias for the specific python version used in this file. +FROM python:3.11.3-slim-bullseye as python + + +# Python build stage +FROM python as python-build-stage + +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements /requirements + +# create python dependency wheels +RUN pip wheel --no-cache-dir --wheel-dir /usr/src/app/wheels \ + -r /requirements/local.txt -r /requirements/production.txt \ + && rm -rf /requirements + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update && apt-get install --no-install-recommends -y \ + # To run the Makefile + make \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # Uncomment below lines to enable Sphinx output to latex and pdf + # texlive-latex-recommended \ + # texlive-fonts-recommended \ + # texlive-latex-extra \ + # latexmk \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels + +# use wheels to install python dependencies +RUN pip install --no-cache /wheels/* \ + && rm -rf /wheels + +COPY ./compose/local/docs/start /start-docs +RUN sed -i 's/\r$//g' /start-docs +RUN chmod +x /start-docs + +WORKDIR /docs diff --git a/compose/local/docs/start b/compose/local/docs/start new file mode 100644 index 0000000..96a94f5 --- /dev/null +++ b/compose/local/docs/start @@ -0,0 +1,7 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + +exec make livehtml diff --git a/compose/production/django/Dockerfile b/compose/production/django/Dockerfile new file mode 100644 index 0000000..2313342 --- /dev/null +++ b/compose/production/django/Dockerfile @@ -0,0 +1,78 @@ + +# define an alias for the specific python version used in this file. +FROM python:3.11.3-slim-bullseye as python + +# Python build stage +FROM python as python-build-stage + +ARG BUILD_ENVIRONMENT=production + +# Install apt packages +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements . + +# Create Python Dependency and Sub-Dependency Wheels. +RUN pip wheel --wheel-dir /usr/src/app/wheels \ + -r ${BUILD_ENVIRONMENT}.txt + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT=production +ARG APP_HOME=/app + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 +ENV BUILD_ENV ${BUILD_ENVIRONMENT} + +WORKDIR ${APP_HOME} + +RUN addgroup --system django \ + && adduser --system --ingroup django django + + +# Install required system dependencies +RUN apt-get update && apt-get install --no-install-recommends -y \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels/ + +# use wheels to install python dependencies +RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ + && rm -rf /wheels/ + + +COPY --chown=django:django ./compose/production/django/entrypoint /entrypoint +RUN sed -i 's/\r$//g' /entrypoint +RUN chmod +x /entrypoint + + +COPY --chown=django:django ./compose/production/django/start /start +RUN sed -i 's/\r$//g' /start +RUN chmod +x /start + + +# copy application code to WORKDIR +COPY --chown=django:django . ${APP_HOME} + +# make django owner of the WORKDIR directory as well. +RUN chown django:django ${APP_HOME} + +USER django + +ENTRYPOINT ["/entrypoint"] diff --git a/compose/production/django/entrypoint b/compose/production/django/entrypoint new file mode 100644 index 0000000..0382a89 --- /dev/null +++ b/compose/production/django/entrypoint @@ -0,0 +1,46 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + + + +if [ -z "${POSTGRES_USER}" ]; then + base_postgres_image_default_user='postgres' + export POSTGRES_USER="${base_postgres_image_default_user}" +fi +export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}" + +python << END +import sys +import time + +import psycopg2 + +suggest_unrecoverable_after = 30 +start = time.time() + +while True: + try: + psycopg2.connect( + dbname="${POSTGRES_DB}", + user="${POSTGRES_USER}", + password="${POSTGRES_PASSWORD}", + host="${POSTGRES_HOST}", + port="${POSTGRES_PORT}", + ) + break + except psycopg2.OperationalError as error: + sys.stderr.write("Waiting for PostgreSQL to become available...\n") + + if time.time() - start > suggest_unrecoverable_after: + sys.stderr.write(" This is taking longer than expected. The following exception may be indicative of an unrecoverable error: '{}'\n".format(error)) + + time.sleep(1) +END + +>&2 echo 'PostgreSQL is available' + +exec "$@" diff --git a/compose/production/django/start b/compose/production/django/start new file mode 100644 index 0000000..97216fa --- /dev/null +++ b/compose/production/django/start @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python /app/manage.py collectstatic --noinput + +exec /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app diff --git a/compose/production/nginx/Dockerfile b/compose/production/nginx/Dockerfile new file mode 100644 index 0000000..911b16f --- /dev/null +++ b/compose/production/nginx/Dockerfile @@ -0,0 +1,2 @@ +FROM nginx:1.17.8-alpine +COPY ./compose/production/nginx/default.conf /etc/nginx/conf.d/default.conf diff --git a/compose/production/nginx/default.conf b/compose/production/nginx/default.conf new file mode 100644 index 0000000..562dba8 --- /dev/null +++ b/compose/production/nginx/default.conf @@ -0,0 +1,7 @@ +server { + listen 80; + server_name localhost; + location /media/ { + alias /usr/share/nginx/media/; + } +} diff --git a/compose/production/postgres/Dockerfile b/compose/production/postgres/Dockerfile new file mode 100644 index 0000000..101aa81 --- /dev/null +++ b/compose/production/postgres/Dockerfile @@ -0,0 +1,6 @@ +FROM postgres:14 + +COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance +RUN chmod +x /usr/local/bin/maintenance/* +RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ + && rmdir /usr/local/bin/maintenance diff --git a/compose/production/postgres/maintenance/_sourced/constants.sh b/compose/production/postgres/maintenance/_sourced/constants.sh new file mode 100644 index 0000000..6ca4f0c --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/constants.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + + +BACKUP_DIR_PATH='/backups' +BACKUP_FILE_PREFIX='backup' diff --git a/compose/production/postgres/maintenance/_sourced/countdown.sh b/compose/production/postgres/maintenance/_sourced/countdown.sh new file mode 100644 index 0000000..e6cbfb6 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/countdown.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + + +countdown() { + declare desc="A simple countdown. Source: https://superuser.com/a/611582" + local seconds="${1}" + local d=$(($(date +%s) + "${seconds}")) + while [ "$d" -ge `date +%s` ]; do + echo -ne "$(date -u --date @$(($d - `date +%s`)) +%H:%M:%S)\r"; + sleep 0.1 + done +} diff --git a/compose/production/postgres/maintenance/_sourced/messages.sh b/compose/production/postgres/maintenance/_sourced/messages.sh new file mode 100644 index 0000000..f6be756 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/messages.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + + +message_newline() { + echo +} + +message_debug() +{ + echo -e "DEBUG: ${@}" +} + +message_welcome() +{ + echo -e "\e[1m${@}\e[0m" +} + +message_warning() +{ + echo -e "\e[33mWARNING\e[0m: ${@}" +} + +message_error() +{ + echo -e "\e[31mERROR\e[0m: ${@}" +} + +message_info() +{ + echo -e "\e[37mINFO\e[0m: ${@}" +} + +message_suggestion() +{ + echo -e "\e[33mSUGGESTION\e[0m: ${@}" +} + +message_success() +{ + echo -e "\e[32mSUCCESS\e[0m: ${@}" +} diff --git a/compose/production/postgres/maintenance/_sourced/yes_no.sh b/compose/production/postgres/maintenance/_sourced/yes_no.sh new file mode 100644 index 0000000..fd9cae1 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/yes_no.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + + +yes_no() { + declare desc="Prompt for confirmation. \$\"\{1\}\": confirmation message." + local arg1="${1}" + + local response= + read -r -p "${arg1} (y/[n])? " response + if [[ "${response}" =~ ^[Yy]$ ]] + then + exit 0 + else + exit 1 + fi +} diff --git a/compose/production/postgres/maintenance/backup b/compose/production/postgres/maintenance/backup new file mode 100644 index 0000000..ee0c9d6 --- /dev/null +++ b/compose/production/postgres/maintenance/backup @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + + +### Create a database backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backup + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "Backing up the '${POSTGRES_DB}' database..." + + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Backing up as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +backup_filename="${BACKUP_FILE_PREFIX}_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz" +pg_dump | gzip > "${BACKUP_DIR_PATH}/${backup_filename}" + + +message_success "'${POSTGRES_DB}' database backup '${backup_filename}' has been created and placed in '${BACKUP_DIR_PATH}'." diff --git a/compose/production/postgres/maintenance/backups b/compose/production/postgres/maintenance/backups new file mode 100644 index 0000000..0484ccf --- /dev/null +++ b/compose/production/postgres/maintenance/backups @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + + +### View backups. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backups + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "These are the backups you have got:" + +ls -lht "${BACKUP_DIR_PATH}" diff --git a/compose/production/postgres/maintenance/restore b/compose/production/postgres/maintenance/restore new file mode 100644 index 0000000..9661ca7 --- /dev/null +++ b/compose/production/postgres/maintenance/restore @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + + +### Restore database from a backup. +### +### Parameters: +### <1> filename of an existing backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres restore <1> + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +if [[ -z ${1+x} ]]; then + message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again." + exit 1 +fi +backup_filename="${BACKUP_DIR_PATH}/${1}" +if [[ ! -f "${backup_filename}" ]]; then + message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again." + exit 1 +fi + +message_welcome "Restoring the '${POSTGRES_DB}' database from the '${backup_filename}' backup..." + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Restoring as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +message_info "Dropping the database..." +dropdb "${PGDATABASE}" + +message_info "Creating a new database..." +createdb --owner="${POSTGRES_USER}" + +message_info "Applying the backup to the new database..." +gunzip -c "${backup_filename}" | psql "${POSTGRES_DB}" + +message_success "The '${POSTGRES_DB}' database has been restored from the '${backup_filename}' backup." diff --git a/compose/production/traefik/Dockerfile b/compose/production/traefik/Dockerfile new file mode 100644 index 0000000..30470d0 --- /dev/null +++ b/compose/production/traefik/Dockerfile @@ -0,0 +1,5 @@ +FROM traefik:2.10.0 +RUN mkdir -p /etc/traefik/acme \ + && touch /etc/traefik/acme/acme.json \ + && chmod 600 /etc/traefik/acme/acme.json +COPY ./compose/production/traefik/traefik.yml /etc/traefik diff --git a/compose/production/traefik/traefik.yml b/compose/production/traefik/traefik.yml new file mode 100644 index 0000000..365458f --- /dev/null +++ b/compose/production/traefik/traefik.yml @@ -0,0 +1,73 @@ +log: + level: INFO + +entryPoints: + web: + # http + address: ':80' + http: + # https://docs.traefik.io/routing/entrypoints/#entrypoint + redirections: + entryPoint: + to: web-secure + + web-secure: + # https + address: ':443' + +certificatesResolvers: + letsencrypt: + # https://docs.traefik.io/master/https/acme/#lets-encrypt + acme: + email: 'jvacek@pm.me' + storage: /etc/traefik/acme/acme.json + # https://docs.traefik.io/master/https/acme/#httpchallenge + httpChallenge: + entryPoint: web + +http: + routers: + web-secure-router: + rule: 'Host(`flamerelay.org`) || Host(`www.flamerelay.org`)' + entryPoints: + - web-secure + middlewares: + - csrf + service: django + tls: + # https://docs.traefik.io/master/routing/routers/#certresolver + certResolver: letsencrypt + + web-media-router: + rule: '(Host(`flamerelay.org`) || Host(`www.flamerelay.org`)) && PathPrefix(`/media/`)' + entryPoints: + - web-secure + middlewares: + - csrf + service: django-media + tls: + certResolver: letsencrypt + + middlewares: + csrf: + # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders + # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax + headers: + hostsProxyHeaders: ['X-CSRFToken'] + + services: + django: + loadBalancer: + servers: + - url: http://django:5000 + + django-media: + loadBalancer: + servers: + - url: http://nginx:80 + +providers: + # https://docs.traefik.io/master/providers/file/ + file: + filename: /etc/traefik/traefik.yml + watch: true diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/api_router.py b/config/api_router.py new file mode 100644 index 0000000..b0ffd42 --- /dev/null +++ b/config/api_router.py @@ -0,0 +1,15 @@ +from django.conf import settings +from rest_framework.routers import DefaultRouter, SimpleRouter + +from flamerelay.users.api.views import UserViewSet + +if settings.DEBUG: + router = DefaultRouter() +else: + router = SimpleRouter() + +router.register("users", UserViewSet) + + +app_name = "api" +urlpatterns = router.urls diff --git a/config/settings/__init__.py b/config/settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings/base.py b/config/settings/base.py new file mode 100644 index 0000000..bd7fd59 --- /dev/null +++ b/config/settings/base.py @@ -0,0 +1,297 @@ +""" +Base settings to build other settings files upon. +""" +from pathlib import Path + +import environ + +BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent +# flamerelay/ +APPS_DIR = BASE_DIR / "flamerelay" +env = environ.Env() + +READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False) +if READ_DOT_ENV_FILE: + # OS environment variables take precedence over variables from .env + env.read_env(str(BASE_DIR / ".env")) + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#debug +DEBUG = env.bool("DJANGO_DEBUG", False) +# Local time zone. Choices are +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# though not all of them may be available with every OS. +# In Windows, this must be set to your system time zone. +TIME_ZONE = "UTC" +# https://docs.djangoproject.com/en/dev/ref/settings/#language-code +LANGUAGE_CODE = "en-us" +# https://docs.djangoproject.com/en/dev/ref/settings/#site-id +SITE_ID = 1 +# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n +USE_I18N = True +# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz +USE_TZ = True +# https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths +LOCALE_PATHS = [str(BASE_DIR / "locale")] + +# DATABASES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#databases +DATABASES = {"default": env.db("DATABASE_URL")} +DATABASES["default"]["ATOMIC_REQUESTS"] = True +# https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DEFAULT_AUTO_FIELD +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# URLS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf +ROOT_URLCONF = "config.urls" +# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application +WSGI_APPLICATION = "config.wsgi.application" + +# APPS +# ------------------------------------------------------------------------------ +DJANGO_APPS = [ + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.sites", + "django.contrib.messages", + "django.contrib.staticfiles", + # "django.contrib.humanize", # Handy template tags + "django.contrib.admin", + "django.forms", +] +THIRD_PARTY_APPS = [ + "crispy_forms", + "crispy_bootstrap5", + "allauth", + "allauth.account", + "allauth.socialaccount", + "rest_framework", + "rest_framework.authtoken", + "corsheaders", + "drf_spectacular", +] + +LOCAL_APPS = [ + "flamerelay.users", + # Your stuff: custom apps go here +] +# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps +INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS + +# MIGRATIONS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules +MIGRATION_MODULES = {"sites": "flamerelay.contrib.sites.migrations"} + +# AUTHENTICATION +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends +AUTHENTICATION_BACKENDS = [ + "django.contrib.auth.backends.ModelBackend", + "allauth.account.auth_backends.AuthenticationBackend", +] +# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model +AUTH_USER_MODEL = "users.User" +# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url +LOGIN_REDIRECT_URL = "users:redirect" +# https://docs.djangoproject.com/en/dev/ref/settings/#login-url +LOGIN_URL = "account_login" + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = [ + # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django + "django.contrib.auth.hashers.Argon2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", + "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", +] +# https://docs.djangoproject.com/en/dev/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"}, +] + +# MIDDLEWARE +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#middleware +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "corsheaders.middleware.CorsMiddleware", + "whitenoise.middleware.WhiteNoiseMiddleware", + "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", +] + +# STATIC +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#static-root +STATIC_ROOT = str(BASE_DIR / "staticfiles") +# https://docs.djangoproject.com/en/dev/ref/settings/#static-url +STATIC_URL = "/static/" +# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS +STATICFILES_DIRS = [str(APPS_DIR / "static")] +# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders +STATICFILES_FINDERS = [ + "django.contrib.staticfiles.finders.FileSystemFinder", + "django.contrib.staticfiles.finders.AppDirectoriesFinder", +] + +# MEDIA +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#media-root +MEDIA_ROOT = str(APPS_DIR / "media") +# https://docs.djangoproject.com/en/dev/ref/settings/#media-url +MEDIA_URL = "/media/" + +# TEMPLATES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#templates +TEMPLATES = [ + { + # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND + "BACKEND": "django.template.backends.django.DjangoTemplates", + # https://docs.djangoproject.com/en/dev/ref/settings/#dirs + "DIRS": [str(APPS_DIR / "templates")], + # https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs + "APP_DIRS": True, + "OPTIONS": { + # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.template.context_processors.i18n", + "django.template.context_processors.media", + "django.template.context_processors.static", + "django.template.context_processors.tz", + "django.contrib.messages.context_processors.messages", + "flamerelay.users.context_processors.allauth_settings", + ], + }, + } +] + +# https://docs.djangoproject.com/en/dev/ref/settings/#form-renderer +FORM_RENDERER = "django.forms.renderers.TemplatesSetting" + +# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs +CRISPY_TEMPLATE_PACK = "bootstrap5" +CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" + +# FIXTURES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs +FIXTURE_DIRS = (str(APPS_DIR / "fixtures"),) + +# SECURITY +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly +SESSION_COOKIE_HTTPONLY = True +# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly +CSRF_COOKIE_HTTPONLY = True +# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options +X_FRAME_OPTIONS = "DENY" + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend +EMAIL_BACKEND = env( + "DJANGO_EMAIL_BACKEND", + default="django.core.mail.backends.smtp.EmailBackend", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#email-timeout +EMAIL_TIMEOUT = 5 + +# ADMIN +# ------------------------------------------------------------------------------ +# Django Admin URL. +ADMIN_URL = "admin/" +# https://docs.djangoproject.com/en/dev/ref/settings/#admins +ADMINS = [("""Jonas Vacek""", "jvacek@pm.me")] +# https://docs.djangoproject.com/en/dev/ref/settings/#managers +MANAGERS = ADMINS + +# LOGGING +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#logging +# See https://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s", + }, + }, + "handlers": { + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + } + }, + "root": {"level": "INFO", "handlers": ["console"]}, +} + + +# django-allauth +# ------------------------------------------------------------------------------ +ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_AUTHENTICATION_METHOD = "email" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_REQUIRED = True +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_USERNAME_REQUIRED = False +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_USER_MODEL_USERNAME_FIELD = None +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_VERIFICATION = "mandatory" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_ADAPTER = "flamerelay.users.adapters.AccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/forms.html +ACCOUNT_FORMS = {"signup": "flamerelay.users.forms.UserSignupForm"} +# https://django-allauth.readthedocs.io/en/latest/configuration.html +SOCIALACCOUNT_ADAPTER = "flamerelay.users.adapters.SocialAccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/forms.html +SOCIALACCOUNT_FORMS = {"signup": "flamerelay.users.forms.UserSocialSignupForm"} + +# django-rest-framework +# ------------------------------------------------------------------------------- +# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/ +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": ( + "rest_framework.authentication.SessionAuthentication", + "rest_framework.authentication.TokenAuthentication", + ), + "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), + "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", +} + +# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup +CORS_URLS_REGEX = r"^/api/.*$" + +# By Default swagger ui is available only to admin user(s). You can change permission classes to change that +# See more configuration options at https://drf-spectacular.readthedocs.io/en/latest/settings.html#settings +SPECTACULAR_SETTINGS = { + "TITLE": "FlameRelay API", + "DESCRIPTION": "Documentation of API endpoints of FlameRelay", + "VERSION": "1.0.0", + "SERVE_PERMISSIONS": ["rest_framework.permissions.IsAdminUser"], +} +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/local.py b/config/settings/local.py new file mode 100644 index 0000000..e064a75 --- /dev/null +++ b/config/settings/local.py @@ -0,0 +1,64 @@ +from .base import * # noqa +from .base import env + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#debug +DEBUG = True +# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +SECRET_KEY = env( + "DJANGO_SECRET_KEY", + default="9kMmghj6oXl5x0awKDdG8jL0fibbdWyBBHfNJQ7S45zArSzYS7nL10EHmpVOphvP", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"] + +# CACHES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#caches +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "", + } +} + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-host +EMAIL_HOST = env("EMAIL_HOST", default="mailhog") +# https://docs.djangoproject.com/en/dev/ref/settings/#email-port +EMAIL_PORT = 1025 + +# WhiteNoise +# ------------------------------------------------------------------------------ +# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development +INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS # noqa: F405 + + +# django-debug-toolbar +# ------------------------------------------------------------------------------ +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites +INSTALLED_APPS += ["debug_toolbar"] # noqa: F405 +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware +MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa: F405 +# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config +DEBUG_TOOLBAR_CONFIG = { + "DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"], + "SHOW_TEMPLATE_CONTEXT": True, +} +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips +INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"] +if env("USE_DOCKER") == "yes": + import socket + + hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) + INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips] + +# django-extensions +# ------------------------------------------------------------------------------ +# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration +INSTALLED_APPS += ["django_extensions"] # noqa: F405 + +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/production.py b/config/settings/production.py new file mode 100644 index 0000000..9db9d5e --- /dev/null +++ b/config/settings/production.py @@ -0,0 +1,160 @@ +import logging + +import sentry_sdk +from sentry_sdk.integrations.django import DjangoIntegration +from sentry_sdk.integrations.logging import LoggingIntegration +from sentry_sdk.integrations.redis import RedisIntegration + +from .base import * # noqa +from .base import env + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +SECRET_KEY = env("DJANGO_SECRET_KEY") +# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["flamerelay.org"]) + +# DATABASES +# ------------------------------------------------------------------------------ +DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60) # noqa: F405 + +# CACHES +# ------------------------------------------------------------------------------ +CACHES = { + "default": { + "BACKEND": "django_redis.cache.RedisCache", + "LOCATION": env("REDIS_URL"), + "OPTIONS": { + "CLIENT_CLASS": "django_redis.client.DefaultClient", + # Mimicing memcache behavior. + # https://github.com/jazzband/django-redis#memcached-exceptions-behavior + "IGNORE_EXCEPTIONS": True, + }, + } +} + +# SECURITY +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect +SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) +# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure +SESSION_COOKIE_SECURE = True +# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure +CSRF_COOKIE_SECURE = True +# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds +# TODO: set this to 60 seconds first and then to 518400 once you prove the former works +SECURE_HSTS_SECONDS = 60 +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains +SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload +SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) +# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff +SECURE_CONTENT_TYPE_NOSNIFF = env.bool("DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True) + +# STATIC +# ------------------------ +STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" +# MEDIA +# ------------------------------------------------------------------------------ + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email +DEFAULT_FROM_EMAIL = env( + "DJANGO_DEFAULT_FROM_EMAIL", + default="FlameRelay ", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#server-email +SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL) +# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix +EMAIL_SUBJECT_PREFIX = env( + "DJANGO_EMAIL_SUBJECT_PREFIX", + default="[FlameRelay]", +) + +# ADMIN +# ------------------------------------------------------------------------------ +# Django Admin URL regex. +ADMIN_URL = env("DJANGO_ADMIN_URL") + +# Anymail +# ------------------------------------------------------------------------------ +# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail +INSTALLED_APPS += ["anymail"] # noqa: F405 +# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend +# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference +# https://anymail.readthedocs.io/en/stable/esps/sendgrid/ +EMAIL_BACKEND = "anymail.backends.sendgrid.EmailBackend" +ANYMAIL = { + "SENDGRID_API_KEY": env("SENDGRID_API_KEY"), + "SENDGRID_API_URL": env("SENDGRID_API_URL", default="https://api.sendgrid.com/v3/"), +} + + +# LOGGING +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#logging +# See https://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. + +LOGGING = { + "version": 1, + "disable_existing_loggers": True, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s", + }, + }, + "handlers": { + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + } + }, + "root": {"level": "INFO", "handlers": ["console"]}, + "loggers": { + "django.db.backends": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + # Errors logged by the SDK itself + "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, + "django.security.DisallowedHost": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + }, +} + +# Sentry +# ------------------------------------------------------------------------------ +SENTRY_DSN = env("SENTRY_DSN") +SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) + +sentry_logging = LoggingIntegration( + level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs + event_level=logging.ERROR, # Send errors as events +) +integrations = [sentry_logging, DjangoIntegration(), RedisIntegration()] +sentry_sdk.init( + dsn=SENTRY_DSN, + integrations=integrations, + environment=env("SENTRY_ENVIRONMENT", default="production"), + traces_sample_rate=env.float("SENTRY_TRACES_SAMPLE_RATE", default=0.0), +) + +# django-rest-framework +# ------------------------------------------------------------------------------- +# Tools that generate code samples can use SERVERS to point to the correct domain +SPECTACULAR_SETTINGS["SERVERS"] = [ # noqa: F405 + {"url": "https://flamerelay.org", "description": "Production server"}, +] +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/test.py b/config/settings/test.py new file mode 100644 index 0000000..61bd79e --- /dev/null +++ b/config/settings/test.py @@ -0,0 +1,32 @@ +""" +With these settings, tests run faster. +""" + +from .base import * # noqa +from .base import env + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +SECRET_KEY = env( + "DJANGO_SECRET_KEY", + default="RXdFPZ23ukKHvX81fD9yY9x27Tg2vVjS119gU7oAl38yyVnRtlSAebN1xxS0LVdZ", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner +TEST_RUNNER = "django.test.runner.DiscoverRunner" + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend +EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" + +# DEBUGGING FOR TEMPLATES +# ------------------------------------------------------------------------------ +TEMPLATES[0]["OPTIONS"]["debug"] = True # type: ignore # noqa: F405 +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..4abc977 --- /dev/null +++ b/config/urls.py @@ -0,0 +1,59 @@ +from django.conf import settings +from django.conf.urls.static import static +from django.contrib import admin +from django.urls import include, path +from django.views import defaults as default_views +from django.views.generic import TemplateView +from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView +from rest_framework.authtoken.views import obtain_auth_token + +urlpatterns = [ + path("", TemplateView.as_view(template_name="pages/home.html"), name="home"), + path("about/", TemplateView.as_view(template_name="pages/about.html"), name="about"), + # Django Admin, use {% url 'admin:index' %} + path(settings.ADMIN_URL, admin.site.urls), + # User management + path("users/", include("flamerelay.users.urls", namespace="users")), + path("accounts/", include("allauth.urls")), + # Your stuff: custom urls includes go here +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +# API URLS +urlpatterns += [ + # API base url + path("api/", include("config.api_router")), + # DRF auth token + path("auth-token/", obtain_auth_token), + path("api/schema/", SpectacularAPIView.as_view(), name="api-schema"), + path( + "api/docs/", + SpectacularSwaggerView.as_view(url_name="api-schema"), + name="api-docs", + ), +] + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + path( + "400/", + default_views.bad_request, + kwargs={"exception": Exception("Bad Request!")}, + ), + path( + "403/", + default_views.permission_denied, + kwargs={"exception": Exception("Permission Denied")}, + ), + path( + "404/", + default_views.page_not_found, + kwargs={"exception": Exception("Page not Found")}, + ), + path("500/", default_views.server_error), + ] + if "debug_toolbar" in settings.INSTALLED_APPS: + import debug_toolbar + + urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..ff2704f --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,38 @@ +""" +WSGI config for FlameRelay project. + +This module contains the WSGI application used by Django's development server +and any production WSGI deployments. It should expose a module-level variable +named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover +this application via the ``WSGI_APPLICATION`` setting. + +Usually you will have the standard Django WSGI application here, but it also +might make sense to replace the whole Django WSGI application with a custom one +that later delegates to the Django one. For example, you could introduce WSGI +middleware here, or combine a Django application with an application of another +framework. + +""" +import os +import sys +from pathlib import Path + +from django.core.wsgi import get_wsgi_application + +# This allows easy placement of apps within the interior +# flamerelay directory. +BASE_DIR = Path(__file__).resolve(strict=True).parent.parent +sys.path.append(str(BASE_DIR / "flamerelay")) +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +application = get_wsgi_application() +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..6957700 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,29 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = ./_build +APP = /app + +.PHONY: help livehtml apidocs Makefile + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c . + +# Build, watch and serve docs with live reload +livehtml: + sphinx-autobuild -b html --host 0.0.0.0 --port 9000 --watch $(APP) -c . $(SOURCEDIR) $(BUILDDIR)/html + +# Outputs rst files from django application code +apidocs: + sphinx-apidoc -o $(SOURCEDIR)/api $(APP) + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c . diff --git a/docs/__init__.py b/docs/__init__.py new file mode 100644 index 0000000..8772c82 --- /dev/null +++ b/docs/__init__.py @@ -0,0 +1 @@ +# Included so that Django's startproject comment runs against the docs directory diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..16b1084 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,62 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +import os +import sys +import django + +if os.getenv("READTHEDOCS", default=False) == "True": + sys.path.insert(0, os.path.abspath("..")) + os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" + os.environ["USE_DOCKER"] = "no" +else: + sys.path.insert(0, os.path.abspath("/app")) +os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") +django.setup() + +# -- Project information ----------------------------------------------------- + +project = "FlameRelay" +copyright = """2023, Jonas Vacek""" +author = "Jonas Vacek" + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", +] + +# Add any paths that contain templates here, relative to this directory. +# templates_path = ["_templates"] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "alabaster" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ["_static"] diff --git a/docs/howto.rst b/docs/howto.rst new file mode 100644 index 0000000..738aeca --- /dev/null +++ b/docs/howto.rst @@ -0,0 +1,38 @@ +How To - Project Documentation +====================================================================== + +Get Started +---------------------------------------------------------------------- + +Documentation can be written as rst files in `flamerelay/docs`. + + +To build and serve docs, use the commands:: + + docker-compose -f local.yml up docs + + + +Changes to files in `docs/_source` will be picked up and reloaded automatically. + +`Sphinx `_ is the tool used to build documentation. + +Docstrings to Documentation +---------------------------------------------------------------------- + +The sphinx extension `apidoc `_ is used to automatically document code using signatures and docstrings. + +Numpy or Google style docstrings will be picked up from project files and available for documentation. See the `Napoleon `_ extension for details. + +For an in-use example, see the `page source <_sources/users.rst.txt>`_ for :ref:`users`. + +To compile all docstrings automatically into documentation source files, use the command: + :: + + make apidocs + + +This can be done in the docker container: + :: + + docker run --rm docs make apidocs diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..a666cc4 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,23 @@ +.. FlameRelay documentation master file, created by + sphinx-quickstart. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to FlameRelay's documentation! +====================================================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + howto + users + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..1f99dd2 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,46 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build -c . +) +set SOURCEDIR=_source +set BUILDDIR=_build +set APP=..\flamerelay + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.Install sphinx-autobuild for live serving. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -b %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:livehtml +sphinx-autobuild -b html --open-browser -p 9000 --watch %APP% -c . %SOURCEDIR% %BUILDDIR%/html +GOTO :EOF + +:apidocs +sphinx-apidoc -o %SOURCEDIR%/api %APP% +GOTO :EOF + +:help +%SPHINXBUILD% -b help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/users.rst b/docs/users.rst new file mode 100644 index 0000000..ce0556f --- /dev/null +++ b/docs/users.rst @@ -0,0 +1,15 @@ + .. _users: + +Users +====================================================================== + +Starting a new project, it’s highly recommended to set up a custom user model, +even if the default User model is sufficient for you. + +This model behaves identically to the default user model, +but you’ll be able to customize it in the future if the need arises. + +.. automodule:: flamerelay.users.models + :members: + :noindex: + diff --git a/flamerelay/__init__.py b/flamerelay/__init__.py new file mode 100644 index 0000000..9c9b953 --- /dev/null +++ b/flamerelay/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.1.0" +__version_info__ = tuple(int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".")) diff --git a/flamerelay/conftest.py b/flamerelay/conftest.py new file mode 100644 index 0000000..31af38a --- /dev/null +++ b/flamerelay/conftest.py @@ -0,0 +1,14 @@ +import pytest + +from flamerelay.users.models import User +from flamerelay.users.tests.factories import UserFactory + + +@pytest.fixture(autouse=True) +def media_storage(settings, tmpdir): + settings.MEDIA_ROOT = tmpdir.strpath + + +@pytest.fixture +def user(db) -> User: + return UserFactory() diff --git a/flamerelay/contrib/__init__.py b/flamerelay/contrib/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/flamerelay/contrib/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/flamerelay/contrib/sites/__init__.py b/flamerelay/contrib/sites/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/flamerelay/contrib/sites/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/flamerelay/contrib/sites/migrations/0001_initial.py b/flamerelay/contrib/sites/migrations/0001_initial.py new file mode 100644 index 0000000..304cd6d --- /dev/null +++ b/flamerelay/contrib/sites/migrations/0001_initial.py @@ -0,0 +1,42 @@ +import django.contrib.sites.models +from django.contrib.sites.models import _simple_domain_name_validator +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [] + + operations = [ + migrations.CreateModel( + name="Site", + fields=[ + ( + "id", + models.AutoField( + verbose_name="ID", + serialize=False, + auto_created=True, + primary_key=True, + ), + ), + ( + "domain", + models.CharField( + max_length=100, + verbose_name="domain name", + validators=[_simple_domain_name_validator], + ), + ), + ("name", models.CharField(max_length=50, verbose_name="display name")), + ], + options={ + "ordering": ("domain",), + "db_table": "django_site", + "verbose_name": "site", + "verbose_name_plural": "sites", + }, + bases=(models.Model,), + managers=[("objects", django.contrib.sites.models.SiteManager())], + ) + ] diff --git a/flamerelay/contrib/sites/migrations/0002_alter_domain_unique.py b/flamerelay/contrib/sites/migrations/0002_alter_domain_unique.py new file mode 100644 index 0000000..2c8d6da --- /dev/null +++ b/flamerelay/contrib/sites/migrations/0002_alter_domain_unique.py @@ -0,0 +1,20 @@ +import django.contrib.sites.models +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [("sites", "0001_initial")] + + operations = [ + migrations.AlterField( + model_name="site", + name="domain", + field=models.CharField( + max_length=100, + unique=True, + validators=[django.contrib.sites.models._simple_domain_name_validator], + verbose_name="domain name", + ), + ) + ] diff --git a/flamerelay/contrib/sites/migrations/0003_set_site_domain_and_name.py b/flamerelay/contrib/sites/migrations/0003_set_site_domain_and_name.py new file mode 100644 index 0000000..518e935 --- /dev/null +++ b/flamerelay/contrib/sites/migrations/0003_set_site_domain_and_name.py @@ -0,0 +1,63 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" +from django.conf import settings +from django.db import migrations + + +def _update_or_create_site_with_sequence(site_model, connection, domain, name): + """Update or create the site with default ID and keep the DB sequence in sync.""" + site, created = site_model.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + "domain": domain, + "name": name, + }, + ) + if created: + # We provided the ID explicitly when creating the Site entry, therefore the DB + # sequence to auto-generate them wasn't used and is now out of sync. If we + # don't do anything, we'll get a unique constraint violation the next time a + # site is created. + # To avoid this, we need to manually update DB sequence and make sure it's + # greater than the maximum value. + max_id = site_model.objects.order_by('-id').first().id + with connection.cursor() as cursor: + cursor.execute("SELECT last_value from django_site_id_seq") + (current_id,) = cursor.fetchone() + if current_id <= max_id: + cursor.execute( + "alter sequence django_site_id_seq restart with %s", + [max_id + 1], + ) + + +def update_site_forward(apps, schema_editor): + """Set site domain and name.""" + Site = apps.get_model("sites", "Site") + _update_or_create_site_with_sequence( + Site, + schema_editor.connection, + "flamerelay.org", + "FlameRelay", + ) + + +def update_site_backward(apps, schema_editor): + """Revert site domain and name to default.""" + Site = apps.get_model("sites", "Site") + _update_or_create_site_with_sequence( + Site, + schema_editor.connection, + "example.com", + "example.com", + ) + + +class Migration(migrations.Migration): + + dependencies = [("sites", "0002_alter_domain_unique")] + + operations = [migrations.RunPython(update_site_forward, update_site_backward)] diff --git a/flamerelay/contrib/sites/migrations/0004_alter_options_ordering_domain.py b/flamerelay/contrib/sites/migrations/0004_alter_options_ordering_domain.py new file mode 100644 index 0000000..f7118ca --- /dev/null +++ b/flamerelay/contrib/sites/migrations/0004_alter_options_ordering_domain.py @@ -0,0 +1,21 @@ +# Generated by Django 3.1.7 on 2021-02-04 14:49 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ("sites", "0003_set_site_domain_and_name"), + ] + + operations = [ + migrations.AlterModelOptions( + name="site", + options={ + "ordering": ["domain"], + "verbose_name": "site", + "verbose_name_plural": "sites", + }, + ), + ] diff --git a/flamerelay/contrib/sites/migrations/__init__.py b/flamerelay/contrib/sites/migrations/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/flamerelay/contrib/sites/migrations/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/flamerelay/static/css/project.css b/flamerelay/static/css/project.css new file mode 100644 index 0000000..f1d543d --- /dev/null +++ b/flamerelay/static/css/project.css @@ -0,0 +1,13 @@ +/* These styles are generated from project.scss. */ + +.alert-debug { + color: black; + background-color: white; + border-color: #d6e9c6; +} + +.alert-error { + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; +} diff --git a/flamerelay/static/fonts/.gitkeep b/flamerelay/static/fonts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/flamerelay/static/images/favicons/favicon.ico b/flamerelay/static/images/favicons/favicon.ico new file mode 100644 index 0000000..e1c1dd1 Binary files /dev/null and b/flamerelay/static/images/favicons/favicon.ico differ diff --git a/flamerelay/static/js/project.js b/flamerelay/static/js/project.js new file mode 100644 index 0000000..d26d23b --- /dev/null +++ b/flamerelay/static/js/project.js @@ -0,0 +1 @@ +/* Project specific Javascript goes here. */ diff --git a/flamerelay/templates/403.html b/flamerelay/templates/403.html new file mode 100644 index 0000000..4356d93 --- /dev/null +++ b/flamerelay/templates/403.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Forbidden (403){% endblock %} + +{% block content %} +

Forbidden (403)

+ +

{% if exception %}{{ exception }}{% else %}You're not allowed to access this page.{% endif %}

+{% endblock content %} diff --git a/flamerelay/templates/404.html b/flamerelay/templates/404.html new file mode 100644 index 0000000..31c0f2b --- /dev/null +++ b/flamerelay/templates/404.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Page not found{% endblock %} + +{% block content %} +

Page not found

+ +

{% if exception %}{{ exception }}{% else %}This is not the page you were looking for.{% endif %}

+{% endblock content %} diff --git a/flamerelay/templates/500.html b/flamerelay/templates/500.html new file mode 100644 index 0000000..46e43a9 --- /dev/null +++ b/flamerelay/templates/500.html @@ -0,0 +1,11 @@ +{% extends "base.html" %} + +{% block title %}Server Error{% endblock %} + +{% block content %} +

Ooops!!! 500

+ +

Looks like something went wrong!

+ +

We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.

+{% endblock content %} diff --git a/flamerelay/templates/account/account_inactive.html b/flamerelay/templates/account/account_inactive.html new file mode 100644 index 0000000..07175e4 --- /dev/null +++ b/flamerelay/templates/account/account_inactive.html @@ -0,0 +1,11 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% translate "Account Inactive" %}{% endblock %} + +{% block inner %} +

{% translate "Account Inactive" %}

+ +

{% translate "This account is inactive." %}

+{% endblock %} diff --git a/flamerelay/templates/account/base.html b/flamerelay/templates/account/base.html new file mode 100644 index 0000000..8e1f260 --- /dev/null +++ b/flamerelay/templates/account/base.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %} + +{% block content %} +
+
+ {% block inner %}{% endblock %} +
+
+{% endblock %} diff --git a/flamerelay/templates/account/email.html b/flamerelay/templates/account/email.html new file mode 100644 index 0000000..f7fa9b2 --- /dev/null +++ b/flamerelay/templates/account/email.html @@ -0,0 +1,78 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Account" %}{% endblock %} + +{% block inner %} +

{% translate "E-mail Addresses" %}

+ +{% if user.emailaddress_set.all %} +

{% translate 'The following e-mail addresses are associated with your account:' %}

+ + + +{% else %} +

{% translate 'Warning:'%} {% translate "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}

+ +{% endif %} + + +

{% translate "Add E-mail Address" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +{% endblock %} + + +{% block inline_javascript %} +{{ block.super }} + +{% endblock %} diff --git a/flamerelay/templates/account/email_confirm.html b/flamerelay/templates/account/email_confirm.html new file mode 100644 index 0000000..525c0f3 --- /dev/null +++ b/flamerelay/templates/account/email_confirm.html @@ -0,0 +1,31 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% translate "Confirm E-mail Address" %}{% endblock %} + + +{% block inner %} +

{% translate "Confirm E-mail Address" %}

+ +{% if confirmation %} + +{% user_display confirmation.email_address.user as user_display %} + +

{% blocktranslate with confirmation.email_address.email as email %}Please confirm that {{ email }} is an e-mail address for user {{ user_display }}.{% endblocktranslate %}

+ +
+{% csrf_token %} + +
+ +{% else %} + +{% url 'account_email' as email_url %} + +

{% blocktranslate %}This e-mail confirmation link expired or is invalid. Please issue a new e-mail confirmation request.{% endblocktranslate %}

+ +{% endif %} + +{% endblock %} diff --git a/flamerelay/templates/account/login.html b/flamerelay/templates/account/login.html new file mode 100644 index 0000000..838ed11 --- /dev/null +++ b/flamerelay/templates/account/login.html @@ -0,0 +1,59 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account socialaccount %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Sign In" %}{% endblock %} + +{% block inner %} + +

{% translate "Sign In" %}

+ +{% get_providers as socialaccount_providers %} + +{% if socialaccount_providers %} +

+ {% translate "Please sign in with one of your existing third party accounts:" %} + {% if ACCOUNT_ALLOW_REGISTRATION %} + {% blocktranslate trimmed %} + Or, sign up + for a {{ site_name }} account and sign in below: + {% endblocktranslate %} + {% endif %} +

+ +
+ +
    + {% include "socialaccount/snippets/provider_list.html" with process="login" %} +
+ + + +
+ + {% include "socialaccount/snippets/login_extra.html" %} + +{% else %} + {% if ACCOUNT_ALLOW_REGISTRATION %} +

+ {% blocktranslate trimmed %} + If you have not created an account yet, then please + sign up first. + {% endblocktranslate %} +

+ {% endif %} +{% endif %} + + + +{% endblock %} diff --git a/flamerelay/templates/account/logout.html b/flamerelay/templates/account/logout.html new file mode 100644 index 0000000..d41824e --- /dev/null +++ b/flamerelay/templates/account/logout.html @@ -0,0 +1,19 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% translate "Sign Out" %}{% endblock %} + +{% block inner %} +

{% translate "Sign Out" %}

+ +

{% translate 'Are you sure you want to sign out?' %}

+ +
+ {% csrf_token %} + {% if redirect_field_value %} + + {% endif %} + +
+{% endblock %} diff --git a/flamerelay/templates/account/password_change.html b/flamerelay/templates/account/password_change.html new file mode 100644 index 0000000..5182a7a --- /dev/null +++ b/flamerelay/templates/account/password_change.html @@ -0,0 +1,16 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Change Password" %}{% endblock %} + +{% block inner %} +

{% translate "Change Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} diff --git a/flamerelay/templates/account/password_reset.html b/flamerelay/templates/account/password_reset.html new file mode 100644 index 0000000..8a2b7a5 --- /dev/null +++ b/flamerelay/templates/account/password_reset.html @@ -0,0 +1,25 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Password Reset" %}{% endblock %} + +{% block inner %} + +

{% translate "Password Reset" %}

+ {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% translate "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +

{% blocktranslate %}Please contact us if you have any trouble resetting your password.{% endblocktranslate %}

+{% endblock %} diff --git a/flamerelay/templates/account/password_reset_done.html b/flamerelay/templates/account/password_reset_done.html new file mode 100644 index 0000000..f682ee8 --- /dev/null +++ b/flamerelay/templates/account/password_reset_done.html @@ -0,0 +1,16 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% translate "Password Reset" %}{% endblock %} + +{% block inner %} +

{% translate "Password Reset" %}

+ + {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% blocktranslate %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktranslate %}

+{% endblock %} diff --git a/flamerelay/templates/account/password_reset_from_key.html b/flamerelay/templates/account/password_reset_from_key.html new file mode 100644 index 0000000..dd836b4 --- /dev/null +++ b/flamerelay/templates/account/password_reset_from_key.html @@ -0,0 +1,24 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} +{% block head_title %}{% translate "Change Password" %}{% endblock %} + +{% block inner %} +

{% if token_fail %}{% translate "Bad Token" %}{% else %}{% translate "Change Password" %}{% endif %}

+ + {% if token_fail %} + {% url 'account_reset_password' as passwd_reset_url %} +

{% blocktranslate %}The password reset link was invalid, possibly because it has already been used. Please request a new password reset.{% endblocktranslate %}

+ {% else %} + {% if form %} +
+ {% csrf_token %} + {{ form|crispy }} + +
+ {% else %} +

{% translate 'Your password is now changed.' %}

+ {% endif %} + {% endif %} +{% endblock %} diff --git a/flamerelay/templates/account/password_reset_from_key_done.html b/flamerelay/templates/account/password_reset_from_key_done.html new file mode 100644 index 0000000..7a58b44 --- /dev/null +++ b/flamerelay/templates/account/password_reset_from_key_done.html @@ -0,0 +1,9 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% block head_title %}{% translate "Change Password" %}{% endblock %} + +{% block inner %} +

{% translate "Change Password" %}

+

{% translate 'Your password is now changed.' %}

+{% endblock %} diff --git a/flamerelay/templates/account/password_set.html b/flamerelay/templates/account/password_set.html new file mode 100644 index 0000000..a748eb9 --- /dev/null +++ b/flamerelay/templates/account/password_set.html @@ -0,0 +1,16 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Set Password" %}{% endblock %} + +{% block inner %} +

{% translate "Set Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} diff --git a/flamerelay/templates/account/signup.html b/flamerelay/templates/account/signup.html new file mode 100644 index 0000000..189ab9e --- /dev/null +++ b/flamerelay/templates/account/signup.html @@ -0,0 +1,22 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Signup" %}{% endblock %} + +{% block inner %} +

{% translate "Sign Up" %}

+ +

{% blocktranslate %}Already have an account? Then please sign in.{% endblocktranslate %}

+ + + +{% endblock %} diff --git a/flamerelay/templates/account/signup_closed.html b/flamerelay/templates/account/signup_closed.html new file mode 100644 index 0000000..fcea1f0 --- /dev/null +++ b/flamerelay/templates/account/signup_closed.html @@ -0,0 +1,11 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% translate "Sign Up Closed" %}{% endblock %} + +{% block inner %} +

{% translate "Sign Up Closed" %}

+ +

{% translate "We are sorry, but the sign up is currently closed." %}

+{% endblock %} diff --git a/flamerelay/templates/account/verification_sent.html b/flamerelay/templates/account/verification_sent.html new file mode 100644 index 0000000..acf81be --- /dev/null +++ b/flamerelay/templates/account/verification_sent.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% translate "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% translate "Verify Your E-mail Address" %}

+ +

{% blocktranslate %}We have sent an e-mail to you for verification. Follow the link provided to finalize the signup process. Please contact us if you do not receive it within a few minutes.{% endblocktranslate %}

+ +{% endblock %} diff --git a/flamerelay/templates/account/verified_email_required.html b/flamerelay/templates/account/verified_email_required.html new file mode 100644 index 0000000..beefcea --- /dev/null +++ b/flamerelay/templates/account/verified_email_required.html @@ -0,0 +1,21 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% translate "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% translate "Verify Your E-mail Address" %}

+ +{% url 'account_email' as email_url %} + +

{% blocktranslate %}This part of the site requires us to verify that +you are who you claim to be. For this purpose, we require that you +verify ownership of your e-mail address. {% endblocktranslate %}

+ +

{% blocktranslate %}We have sent an e-mail to you for +verification. Please click on the link inside this e-mail. Please +contact us if you do not receive it within a few minutes.{% endblocktranslate %}

+ +

{% blocktranslate %}Note: you can still change your e-mail address.{% endblocktranslate %}

+{% endblock %} diff --git a/flamerelay/templates/base.html b/flamerelay/templates/base.html new file mode 100644 index 0000000..85c5a87 --- /dev/null +++ b/flamerelay/templates/base.html @@ -0,0 +1,111 @@ +{% load static i18n %} +{% get_current_language as LANGUAGE_CODE %} + + + + + {% block title %}FlameRelay{% endblock title %} + + + + + + + {% block css %} + + + + + + + {% endblock %} + + {# Placed at the top of the document so pages load faster with defer #} + {% block javascript %} + + + + + + + + {% endblock javascript %} + + + + + +
+ + +
+ +
+ + {% if messages %} + {% for message in messages %} +
+ {{ message }} + +
+ {% endfor %} + {% endif %} + + {% block content %} +

Use this document as a way to quick start any new project.

+ {% endblock content %} + +
+ + {% block modal %}{% endblock modal %} + + {% block inline_javascript %} + {% comment %} + Script tags with only code, no src (defer by default). To run + with a "defer" so that you run inline code: + + {% endcomment %} + {% endblock inline_javascript %} + + diff --git a/flamerelay/templates/pages/about.html b/flamerelay/templates/pages/about.html new file mode 100644 index 0000000..94d9808 --- /dev/null +++ b/flamerelay/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/flamerelay/templates/pages/home.html b/flamerelay/templates/pages/home.html new file mode 100644 index 0000000..94d9808 --- /dev/null +++ b/flamerelay/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/flamerelay/templates/users/user_detail.html b/flamerelay/templates/users/user_detail.html new file mode 100644 index 0000000..810e84b --- /dev/null +++ b/flamerelay/templates/users/user_detail.html @@ -0,0 +1,34 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}User: {{ object.name }}{% endblock %} + +{% block content %} +
+ +
+
+ +

{{ object.name }}

+ {% if object.name %} +

{{ object.name }}

+ {% endif %} +
+
+ +{% if object == request.user %} + +
+ +
+ My Info + E-Mail + +
+ +
+ +{% endif %} + +
+{% endblock content %} diff --git a/flamerelay/templates/users/user_form.html b/flamerelay/templates/users/user_form.html new file mode 100644 index 0000000..42b5ff4 --- /dev/null +++ b/flamerelay/templates/users/user_form.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% load crispy_forms_tags %} + +{% block title %}{{ user.name }}{% endblock %} + +{% block content %} +

{{ user.name }}

+
+ {% csrf_token %} + {{ form|crispy }} +
+
+ +
+
+
+{% endblock %} diff --git a/flamerelay/users/__init__.py b/flamerelay/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/flamerelay/users/adapters.py b/flamerelay/users/adapters.py new file mode 100644 index 0000000..0d206fa --- /dev/null +++ b/flamerelay/users/adapters.py @@ -0,0 +1,16 @@ +from typing import Any + +from allauth.account.adapter import DefaultAccountAdapter +from allauth.socialaccount.adapter import DefaultSocialAccountAdapter +from django.conf import settings +from django.http import HttpRequest + + +class AccountAdapter(DefaultAccountAdapter): + def is_open_for_signup(self, request: HttpRequest): + return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) + + +class SocialAccountAdapter(DefaultSocialAccountAdapter): + def is_open_for_signup(self, request: HttpRequest, sociallogin: Any): + return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) diff --git a/flamerelay/users/admin.py b/flamerelay/users/admin.py new file mode 100644 index 0000000..2c7d3ca --- /dev/null +++ b/flamerelay/users/admin.py @@ -0,0 +1,43 @@ +from django.contrib import admin +from django.contrib.auth import admin as auth_admin +from django.contrib.auth import get_user_model +from django.utils.translation import gettext_lazy as _ + +from flamerelay.users.forms import UserAdminChangeForm, UserAdminCreationForm + +User = get_user_model() + + +@admin.register(User) +class UserAdmin(auth_admin.UserAdmin): + form = UserAdminChangeForm + add_form = UserAdminCreationForm + fieldsets = ( + (None, {"fields": ("email", "password")}), + (_("Personal info"), {"fields": ("name",)}), + ( + _("Permissions"), + { + "fields": ( + "is_active", + "is_staff", + "is_superuser", + "groups", + "user_permissions", + ), + }, + ), + (_("Important dates"), {"fields": ("last_login", "date_joined")}), + ) + list_display = ["email", "name", "is_superuser"] + search_fields = ["name"] + ordering = ["id"] + add_fieldsets = ( + ( + None, + { + "classes": ("wide",), + "fields": ("email", "password1", "password2"), + }, + ), + ) diff --git a/flamerelay/users/api/serializers.py b/flamerelay/users/api/serializers.py new file mode 100644 index 0000000..48e5856 --- /dev/null +++ b/flamerelay/users/api/serializers.py @@ -0,0 +1,14 @@ +from django.contrib.auth import get_user_model +from rest_framework import serializers + +User = get_user_model() + + +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ["name", "url"] + + extra_kwargs = { + "url": {"view_name": "api:user-detail", "lookup_field": "pk"}, + } diff --git a/flamerelay/users/api/views.py b/flamerelay/users/api/views.py new file mode 100644 index 0000000..fa82214 --- /dev/null +++ b/flamerelay/users/api/views.py @@ -0,0 +1,25 @@ +from django.contrib.auth import get_user_model +from rest_framework import status +from rest_framework.decorators import action +from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin +from rest_framework.response import Response +from rest_framework.viewsets import GenericViewSet + +from .serializers import UserSerializer + +User = get_user_model() + + +class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): + serializer_class = UserSerializer + queryset = User.objects.all() + lookup_field = "pk" + + def get_queryset(self, *args, **kwargs): + assert isinstance(self.request.user.id, int) + return self.queryset.filter(id=self.request.user.id) + + @action(detail=False) + def me(self, request): + serializer = UserSerializer(request.user, context={"request": request}) + return Response(status=status.HTTP_200_OK, data=serializer.data) diff --git a/flamerelay/users/apps.py b/flamerelay/users/apps.py new file mode 100644 index 0000000..d0d9f08 --- /dev/null +++ b/flamerelay/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class UsersConfig(AppConfig): + name = "flamerelay.users" + verbose_name = _("Users") + + def ready(self): + try: + import flamerelay.users.signals # noqa: F401 + except ImportError: + pass diff --git a/flamerelay/users/context_processors.py b/flamerelay/users/context_processors.py new file mode 100644 index 0000000..e2633ae --- /dev/null +++ b/flamerelay/users/context_processors.py @@ -0,0 +1,8 @@ +from django.conf import settings + + +def allauth_settings(request): + """Expose some settings from django-allauth in templates.""" + return { + "ACCOUNT_ALLOW_REGISTRATION": settings.ACCOUNT_ALLOW_REGISTRATION, + } diff --git a/flamerelay/users/forms.py b/flamerelay/users/forms.py new file mode 100644 index 0000000..604b32b --- /dev/null +++ b/flamerelay/users/forms.py @@ -0,0 +1,45 @@ +from allauth.account.forms import SignupForm +from allauth.socialaccount.forms import SignupForm as SocialSignupForm +from django.contrib.auth import forms as admin_forms +from django.contrib.auth import get_user_model +from django.forms import EmailField +from django.utils.translation import gettext_lazy as _ + +User = get_user_model() + + +class UserAdminChangeForm(admin_forms.UserChangeForm): + class Meta(admin_forms.UserChangeForm.Meta): + model = User + field_classes = {"email": EmailField} + + +class UserAdminCreationForm(admin_forms.UserCreationForm): + """ + Form for User Creation in the Admin Area. + To change user signup, see UserSignupForm and UserSocialSignupForm. + """ + + class Meta(admin_forms.UserCreationForm.Meta): + model = User + fields = ("email",) + field_classes = {"email": EmailField} + error_messages = { + "email": {"unique": _("This email has already been taken.")}, + } + + +class UserSignupForm(SignupForm): + """ + Form that will be rendered on a user sign up section/screen. + Default fields will be added automatically. + Check UserSocialSignupForm for accounts created from social. + """ + + +class UserSocialSignupForm(SocialSignupForm): + """ + Renders the form when user has signed up using social accounts. + Default fields will be added automatically. + See UserSignupForm otherwise. + """ diff --git a/flamerelay/users/managers.py b/flamerelay/users/managers.py new file mode 100644 index 0000000..017ab14 --- /dev/null +++ b/flamerelay/users/managers.py @@ -0,0 +1,34 @@ +from django.contrib.auth.hashers import make_password +from django.contrib.auth.models import UserManager as DjangoUserManager + + +class UserManager(DjangoUserManager): + """Custom manager for the User model.""" + + def _create_user(self, email: str, password: str | None, **extra_fields): + """ + Create and save a user with the given email and password. + """ + if not email: + raise ValueError("The given email must be set") + email = self.normalize_email(email) + user = self.model(email=email, **extra_fields) + user.password = make_password(password) + user.save(using=self._db) + return user + + def create_user(self, email: str, password: str | None = None, **extra_fields): + extra_fields.setdefault("is_staff", False) + extra_fields.setdefault("is_superuser", False) + return self._create_user(email, password, **extra_fields) + + def create_superuser(self, email: str, password: str | None = None, **extra_fields): + extra_fields.setdefault("is_staff", True) + extra_fields.setdefault("is_superuser", True) + + if extra_fields.get("is_staff") is not True: + raise ValueError("Superuser must have is_staff=True.") + if extra_fields.get("is_superuser") is not True: + raise ValueError("Superuser must have is_superuser=True.") + + return self._create_user(email, password, **extra_fields) diff --git a/flamerelay/users/migrations/0001_initial.py b/flamerelay/users/migrations/0001_initial.py new file mode 100644 index 0000000..0939eec --- /dev/null +++ b/flamerelay/users/migrations/0001_initial.py @@ -0,0 +1,111 @@ +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + +import flamerelay.users.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ("auth", "0012_alter_user_first_name_max_length"), + ] + + 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" + ), + ), + ( + "is_superuser", + models.BooleanField( + default=False, + help_text="Designates that this user has all permissions without explicitly assigning them.", + verbose_name="superuser status", + ), + ), + ( + "email", + models.EmailField( + unique=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", + ), + ), + ( + "date_joined", + models.DateTimeField( + default=django.utils.timezone.now, verbose_name="date joined" + ), + ), + ( + "name", + models.CharField( + blank=True, max_length=255, verbose_name="Name of User" + ), + ), + ( + "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", flamerelay.users.models.UserManager()), + ], + ), + ] diff --git a/flamerelay/users/migrations/__init__.py b/flamerelay/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/flamerelay/users/models.py b/flamerelay/users/models.py new file mode 100644 index 0000000..4fa58de --- /dev/null +++ b/flamerelay/users/models.py @@ -0,0 +1,35 @@ +from django.contrib.auth.models import AbstractUser +from django.db.models import CharField, EmailField +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ + +from flamerelay.users.managers import UserManager + + +class User(AbstractUser): + """ + Default custom user model for FlameRelay. + If adding fields that need to be filled at user signup, + check forms.SignupForm and forms.SocialSignupForms accordingly. + """ + + # First and last name do not cover name patterns around the globe + name = CharField(_("Name of User"), blank=True, max_length=255) + first_name = None # type: ignore + last_name = None # type: ignore + email = EmailField(_("email address"), unique=True) + username = None # type: ignore + + USERNAME_FIELD = "email" + REQUIRED_FIELDS = [] + + objects = UserManager() + + def get_absolute_url(self) -> str: + """Get URL for user's detail view. + + Returns: + str: URL for user detail. + + """ + return reverse("users:detail", kwargs={"pk": self.id}) diff --git a/flamerelay/users/tests/__init__.py b/flamerelay/users/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/flamerelay/users/tests/factories.py b/flamerelay/users/tests/factories.py new file mode 100644 index 0000000..caa14cf --- /dev/null +++ b/flamerelay/users/tests/factories.py @@ -0,0 +1,31 @@ +from collections.abc import Sequence +from typing import Any + +from django.contrib.auth import get_user_model +from factory import Faker, post_generation +from factory.django import DjangoModelFactory + + +class UserFactory(DjangoModelFactory): + email = Faker("email") + name = Faker("name") + + @post_generation + def password(self, create: bool, extracted: Sequence[Any], **kwargs): + password = ( + extracted + if extracted + else Faker( + "password", + length=42, + special_chars=True, + digits=True, + upper_case=True, + lower_case=True, + ).evaluate(None, None, extra={"locale": None}) + ) + self.set_password(password) + + class Meta: + model = get_user_model() + django_get_or_create = ["email"] diff --git a/flamerelay/users/tests/test_admin.py b/flamerelay/users/tests/test_admin.py new file mode 100644 index 0000000..baa4830 --- /dev/null +++ b/flamerelay/users/tests/test_admin.py @@ -0,0 +1,37 @@ +from django.urls import reverse + +from flamerelay.users.models import User + + +class TestUserAdmin: + def test_changelist(self, admin_client): + url = reverse("admin:users_user_changelist") + response = admin_client.get(url) + assert response.status_code == 200 + + def test_search(self, admin_client): + url = reverse("admin:users_user_changelist") + response = admin_client.get(url, data={"q": "test"}) + assert response.status_code == 200 + + def test_add(self, admin_client): + url = reverse("admin:users_user_add") + response = admin_client.get(url) + assert response.status_code == 200 + + response = admin_client.post( + url, + data={ + "email": "new-admin@example.com", + "password1": "My_R@ndom-P@ssw0rd", + "password2": "My_R@ndom-P@ssw0rd", + }, + ) + assert response.status_code == 302 + assert User.objects.filter(email="new-admin@example.com").exists() + + def test_view_user(self, admin_client): + user = User.objects.get(email="admin@example.com") + url = reverse("admin:users_user_change", kwargs={"object_id": user.pk}) + response = admin_client.get(url) + assert response.status_code == 200 diff --git a/flamerelay/users/tests/test_drf_urls.py b/flamerelay/users/tests/test_drf_urls.py new file mode 100644 index 0000000..8fabce6 --- /dev/null +++ b/flamerelay/users/tests/test_drf_urls.py @@ -0,0 +1,18 @@ +from django.urls import resolve, reverse + +from flamerelay.users.models import User + + +def test_user_detail(user: User): + assert reverse("api:user-detail", kwargs={"pk": user.pk}) == f"/api/users/{user.pk}/" + assert resolve(f"/api/users/{user.pk}/").view_name == "api:user-detail" + + +def test_user_list(): + assert reverse("api:user-list") == "/api/users/" + assert resolve("/api/users/").view_name == "api:user-list" + + +def test_user_me(): + assert reverse("api:user-me") == "/api/users/me/" + assert resolve("/api/users/me/").view_name == "api:user-me" diff --git a/flamerelay/users/tests/test_drf_views.py b/flamerelay/users/tests/test_drf_views.py new file mode 100644 index 0000000..dd0a0c9 --- /dev/null +++ b/flamerelay/users/tests/test_drf_views.py @@ -0,0 +1,34 @@ +import pytest +from rest_framework.test import APIRequestFactory + +from flamerelay.users.api.views import UserViewSet +from flamerelay.users.models import User + + +class TestUserViewSet: + @pytest.fixture + def api_rf(self) -> APIRequestFactory: + return APIRequestFactory() + + def test_get_queryset(self, user: User, api_rf: APIRequestFactory): + view = UserViewSet() + request = api_rf.get("/fake-url/") + request.user = user + + view.request = request + + assert user in view.get_queryset() + + def test_me(self, user: User, api_rf: APIRequestFactory): + view = UserViewSet() + request = api_rf.get("/fake-url/") + request.user = user + + view.request = request + + response = view.me(request) # type: ignore + + assert response.data == { + "url": f"http://testserver/api/users/{user.pk}/", + "name": user.name, + } diff --git a/flamerelay/users/tests/test_forms.py b/flamerelay/users/tests/test_forms.py new file mode 100644 index 0000000..cc98113 --- /dev/null +++ b/flamerelay/users/tests/test_forms.py @@ -0,0 +1,36 @@ +""" +Module for all Form Tests. +""" +from django.utils.translation import gettext_lazy as _ + +from flamerelay.users.forms import UserAdminCreationForm +from flamerelay.users.models import User + + +class TestUserAdminCreationForm: + """ + Test class for all tests related to the UserAdminCreationForm + """ + + def test_username_validation_error_msg(self, user: User): + """ + Tests UserAdminCreation Form's unique validator functions correctly by testing: + 1) A new user with an existing username cannot be added. + 2) Only 1 error is raised by the UserCreation Form + 3) The desired error message is raised + """ + + # The user already exists, + # hence cannot be created. + form = UserAdminCreationForm( + { + "email": user.email, + "password1": user.password, + "password2": user.password, + } + ) + + assert not form.is_valid() + assert len(form.errors) == 1 + assert "email" in form.errors + assert form.errors["email"][0] == _("This email has already been taken.") diff --git a/flamerelay/users/tests/test_managers.py b/flamerelay/users/tests/test_managers.py new file mode 100644 index 0000000..b3c2e89 --- /dev/null +++ b/flamerelay/users/tests/test_managers.py @@ -0,0 +1,55 @@ +from io import StringIO + +import pytest +from django.core.management import call_command + +from flamerelay.users.models import User + + +@pytest.mark.django_db +class TestUserManager: + def test_create_user(self): + user = User.objects.create_user( + email="john@example.com", + password="something-r@nd0m!", + ) + assert user.email == "john@example.com" + assert not user.is_staff + assert not user.is_superuser + assert user.check_password("something-r@nd0m!") + assert user.username is None + + def test_create_superuser(self): + user = User.objects.create_superuser( + email="admin@example.com", + password="something-r@nd0m!", + ) + assert user.email == "admin@example.com" + assert user.is_staff + assert user.is_superuser + assert user.username is None + + def test_create_superuser_username_ignored(self): + user = User.objects.create_superuser( + email="test@example.com", + password="something-r@nd0m!", + ) + assert user.username is None + + +@pytest.mark.django_db +def test_createsuperuser_command(): + """Ensure createsuperuser command works with our custom manager.""" + out = StringIO() + command_result = call_command( + "createsuperuser", + "--email", + "henry@example.com", + interactive=False, + stdout=out, + ) + + assert command_result is None + assert out.getvalue() == "Superuser created successfully.\n" + user = User.objects.get(email="henry@example.com") + assert not user.has_usable_password() diff --git a/flamerelay/users/tests/test_models.py b/flamerelay/users/tests/test_models.py new file mode 100644 index 0000000..badb935 --- /dev/null +++ b/flamerelay/users/tests/test_models.py @@ -0,0 +1,5 @@ +from flamerelay.users.models import User + + +def test_user_get_absolute_url(user: User): + assert user.get_absolute_url() == f"/users/{user.pk}/" diff --git a/flamerelay/users/tests/test_swagger.py b/flamerelay/users/tests/test_swagger.py new file mode 100644 index 0000000..f97658b --- /dev/null +++ b/flamerelay/users/tests/test_swagger.py @@ -0,0 +1,21 @@ +import pytest +from django.urls import reverse + + +def test_swagger_accessible_by_admin(admin_client): + url = reverse("api-docs") + response = admin_client.get(url) + assert response.status_code == 200 + + +@pytest.mark.django_db +def test_swagger_ui_not_accessible_by_normal_user(client): + url = reverse("api-docs") + response = client.get(url) + assert response.status_code == 403 + + +def test_api_schema_generated_successfully(admin_client): + url = reverse("api-schema") + response = admin_client.get(url) + assert response.status_code == 200 diff --git a/flamerelay/users/tests/test_urls.py b/flamerelay/users/tests/test_urls.py new file mode 100644 index 0000000..1cfa226 --- /dev/null +++ b/flamerelay/users/tests/test_urls.py @@ -0,0 +1,18 @@ +from django.urls import resolve, reverse + +from flamerelay.users.models import User + + +def test_detail(user: User): + assert reverse("users:detail", kwargs={"pk": user.pk}) == f"/users/{user.pk}/" + assert resolve(f"/users/{user.pk}/").view_name == "users:detail" + + +def test_update(): + assert reverse("users:update") == "/users/~update/" + assert resolve("/users/~update/").view_name == "users:update" + + +def test_redirect(): + assert reverse("users:redirect") == "/users/~redirect/" + assert resolve("/users/~redirect/").view_name == "users:redirect" diff --git a/flamerelay/users/tests/test_views.py b/flamerelay/users/tests/test_views.py new file mode 100644 index 0000000..70414bd --- /dev/null +++ b/flamerelay/users/tests/test_views.py @@ -0,0 +1,99 @@ +import pytest +from django.conf import settings +from django.contrib import messages +from django.contrib.auth.models import AnonymousUser +from django.contrib.messages.middleware import MessageMiddleware +from django.contrib.sessions.middleware import SessionMiddleware +from django.http import HttpRequest, HttpResponseRedirect +from django.test import RequestFactory +from django.urls import reverse + +from flamerelay.users.forms import UserAdminChangeForm +from flamerelay.users.models import User +from flamerelay.users.tests.factories import UserFactory +from flamerelay.users.views import ( + UserRedirectView, + UserUpdateView, + user_detail_view, +) + +pytestmark = pytest.mark.django_db + + +class TestUserUpdateView: + """ + TODO: + extracting view initialization code as class-scoped fixture + would be great if only pytest-django supported non-function-scoped + fixture db access -- this is a work-in-progress for now: + https://github.com/pytest-dev/pytest-django/pull/258 + """ + + def dummy_get_response(self, request: HttpRequest): + return None + + def test_get_success_url(self, user: User, rf: RequestFactory): + view = UserUpdateView() + request = rf.get("/fake-url/") + request.user = user + + view.request = request + assert view.get_success_url() == f"/users/{user.pk}/" + + def test_get_object(self, user: User, rf: RequestFactory): + view = UserUpdateView() + request = rf.get("/fake-url/") + request.user = user + + view.request = request + + assert view.get_object() == user + + def test_form_valid(self, user: User, rf: RequestFactory): + view = UserUpdateView() + request = rf.get("/fake-url/") + + # Add the session/message middleware to the request + SessionMiddleware(self.dummy_get_response).process_request(request) + MessageMiddleware(self.dummy_get_response).process_request(request) + request.user = user + + view.request = request + + # Initialize the form + form = UserAdminChangeForm() + form.cleaned_data = {} + form.instance = user + view.form_valid(form) + + messages_sent = [m.message for m in messages.get_messages(request)] + assert messages_sent == ["Information successfully updated"] + + +class TestUserRedirectView: + def test_get_redirect_url(self, user: User, rf: RequestFactory): + view = UserRedirectView() + request = rf.get("/fake-url") + request.user = user + + view.request = request + assert view.get_redirect_url() == f"/users/{user.pk}/" + + +class TestUserDetailView: + def test_authenticated(self, user: User, rf: RequestFactory): + request = rf.get("/fake-url/") + request.user = UserFactory() + response = user_detail_view(request, pk=user.pk) + + assert response.status_code == 200 + + def test_not_authenticated(self, user: User, rf: RequestFactory): + request = rf.get("/fake-url/") + request.user = AnonymousUser() + response = user_detail_view(request, pk=user.pk) + login_url = reverse(settings.LOGIN_URL) + + assert isinstance(response, HttpResponseRedirect) + assert response.status_code == 302 + assert response.url == f"{login_url}?next=/fake-url/" diff --git a/flamerelay/users/urls.py b/flamerelay/users/urls.py new file mode 100644 index 0000000..86d4e80 --- /dev/null +++ b/flamerelay/users/urls.py @@ -0,0 +1,14 @@ +from django.urls import path + +from flamerelay.users.views import ( + user_detail_view, + user_redirect_view, + user_update_view, +) + +app_name = "users" +urlpatterns = [ + path("~redirect/", view=user_redirect_view, name="redirect"), + path("~update/", view=user_update_view, name="update"), + path("/", view=user_detail_view, name="detail"), +] diff --git a/flamerelay/users/views.py b/flamerelay/users/views.py new file mode 100644 index 0000000..a6d8475 --- /dev/null +++ b/flamerelay/users/views.py @@ -0,0 +1,43 @@ +from django.contrib.auth import get_user_model +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.messages.views import SuccessMessageMixin +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from django.views.generic import DetailView, RedirectView, UpdateView + +User = get_user_model() + + +class UserDetailView(LoginRequiredMixin, DetailView): + model = User + slug_field = "id" + slug_url_kwarg = "id" + + +user_detail_view = UserDetailView.as_view() + + +class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): + model = User + fields = ["name"] + success_message = _("Information successfully updated") + + def get_success_url(self): + assert self.request.user.is_authenticated # for mypy to know that the user is authenticated + return self.request.user.get_absolute_url() + + def get_object(self): + return self.request.user + + +user_update_view = UserUpdateView.as_view() + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + permanent = False + + def get_redirect_url(self): + return reverse("users:detail", kwargs={"pk": self.request.user.pk}) + + +user_redirect_view = UserRedirectView.as_view() diff --git a/flamerelay/utils/__init__.py b/flamerelay/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/flamerelay/utils/storages.py b/flamerelay/utils/storages.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/flamerelay/utils/storages.py @@ -0,0 +1 @@ + diff --git a/local.yml b/local.yml new file mode 100644 index 0000000..ff29e3b --- /dev/null +++ b/local.yml @@ -0,0 +1,58 @@ +version: '3' + +volumes: + flamerelay_local_postgres_data: {} + flamerelay_local_postgres_data_backups: {} + +services: + django: + build: + context: . + dockerfile: ./compose/local/django/Dockerfile + image: flamerelay_local_django + container_name: flamerelay_local_django + depends_on: + - postgres + - mailhog + volumes: + - .:/app:z + env_file: + - ./.envs/.local/.django + - ./.envs/.local/.postgres + ports: + - '8000:8000' + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: flamerelay_production_postgres + container_name: flamerelay_local_postgres + volumes: + - flamerelay_local_postgres_data:/var/lib/postgresql/data + - flamerelay_local_postgres_data_backups:/backups + env_file: + - ./.envs/.local/.postgres + + docs: + image: flamerelay_local_docs + container_name: flamerelay_local_docs + build: + context: . + dockerfile: ./compose/local/docs/Dockerfile + env_file: + - ./.envs/.local/.django + volumes: + - ./docs:/docs:z + - ./config:/app/config:z + - ./flamerelay:/app/flamerelay:z + ports: + - '9000:9000' + command: /start-docs + + mailhog: + image: mailhog/mailhog:v1.0.0 + container_name: flamerelay_local_mailhog + ports: + - "8025:8025" diff --git a/locale/README.rst b/locale/README.rst new file mode 100644 index 0000000..c2f1dcd --- /dev/null +++ b/locale/README.rst @@ -0,0 +1,6 @@ +Translations +============ + +Translations will be placed in this folder when running:: + + python manage.py makemessages diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..a6f037c --- /dev/null +++ b/manage.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +import os +import sys +from pathlib import Path + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") + + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django # noqa + except ImportError: + 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?" + ) + + raise + + # This allows easy placement of apps within the interior + # flamerelay directory. + current_path = Path(__file__).parent.resolve() + sys.path.append(str(current_path / "flamerelay")) + + execute_from_command_line(sys.argv) diff --git a/merge_production_dotenvs_in_dotenv.py b/merge_production_dotenvs_in_dotenv.py new file mode 100644 index 0000000..35139fb --- /dev/null +++ b/merge_production_dotenvs_in_dotenv.py @@ -0,0 +1,26 @@ +import os +from collections.abc import Sequence +from pathlib import Path + +BASE_DIR = Path(__file__).parent.resolve() +PRODUCTION_DOTENVS_DIR = BASE_DIR / ".envs" / ".production" +PRODUCTION_DOTENV_FILES = [ + PRODUCTION_DOTENVS_DIR / ".django", + PRODUCTION_DOTENVS_DIR / ".postgres", +] +DOTENV_FILE = BASE_DIR / ".env" + + +def merge( + output_file: Path, + files_to_merge: Sequence[Path], +) -> None: + merged_content = "" + for merge_file in files_to_merge: + merged_content += merge_file.read_text() + merged_content += os.linesep + output_file.write_text(merged_content) + + +if __name__ == "__main__": + merge(DOTENV_FILE, PRODUCTION_DOTENV_FILES) diff --git a/production.yml b/production.yml new file mode 100644 index 0000000..4c5012f --- /dev/null +++ b/production.yml @@ -0,0 +1,61 @@ +version: '3' + +volumes: + production_postgres_data: {} + production_postgres_data_backups: {} + production_traefik: {} + production_django_media: {} + +services: + django: + build: + context: . + dockerfile: ./compose/production/django/Dockerfile + + image: flamerelay_production_django + volumes: + - production_django_media:/app/flamerelay/media + depends_on: + - postgres + - redis + env_file: + - ./.envs/.production/.django + - ./.envs/.production/.postgres + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: flamerelay_production_postgres + volumes: + - production_postgres_data:/var/lib/postgresql/data + - production_postgres_data_backups:/backups + env_file: + - ./.envs/.production/.postgres + + traefik: + build: + context: . + dockerfile: ./compose/production/traefik/Dockerfile + image: flamerelay_production_traefik + depends_on: + - django + volumes: + - production_traefik:/etc/traefik/acme + ports: + - '0.0.0.0:80:80' + - '0.0.0.0:443:443' + + redis: + image: redis:6 + + nginx: + build: + context: . + dockerfile: ./compose/production/nginx/Dockerfile + image: flamerelay_local_nginx + depends_on: + - django + volumes: + - production_django_media:/usr/share/nginx/media:ro diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..206a151 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,84 @@ +# ==== pytest ==== +[tool.pytest.ini_options] +minversion = "6.0" +addopts = "--ds=config.settings.test --reuse-db" +python_files = [ + "tests.py", + "test_*.py", +] + +# ==== Coverage ==== +[tool.coverage.run] +include = ["flamerelay/**"] +omit = ["*/migrations/*", "*/tests/*"] +plugins = ["django_coverage_plugin"] + + +# ==== black ==== +[tool.black] +line-length = 119 +target-version = ['py311'] + + +# ==== isort ==== +[tool.isort] +profile = "black" +line_length = 119 +known_first_party = [ + "flamerelay", + "config", +] +skip = ["venv/"] +skip_glob = ["**/migrations/*.py"] + + +# ==== mypy ==== +[tool.mypy] +python_version = "3.11" +check_untyped_defs = true +ignore_missing_imports = true +warn_unused_ignores = true +warn_redundant_casts = true +warn_unused_configs = true +plugins = [ + "mypy_django_plugin.main", + "mypy_drf_plugin.main", +] + +[[tool.mypy.overrides]] +# Django migrations should not produce any errors: +module = "*.migrations.*" +ignore_errors = true + +[tool.django-stubs] +django_settings_module = "config.settings.test" + + +# ==== PyLint ==== +[tool.pylint.MASTER] +load-plugins = [ + "pylint_django", +] +django-settings-module = "config.settings.local" + +[tool.pylint.FORMAT] +max-line-length = 119 + +[tool.pylint."MESSAGES CONTROL"] +disable = [ + "missing-docstring", + "invalid-name", +] + +[tool.pylint.DESIGN] +max-parents = 13 + +[tool.pylint.TYPECHECK] +generated-members = [ + "REQUEST", + "acl_users", + "aq_parent", + "[a-zA-Z]+_set{1,2}", + "save", + "delete", +] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c1b500c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +# This file is expected by Heroku. + +-r requirements/production.txt diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000..d4b53e6 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,22 @@ +pytz==2023.3 # https://github.com/stub42/pytz +python-slugify==8.0.1 # https://github.com/un33k/python-slugify +Pillow==9.5.0 # https://github.com/python-pillow/Pillow +argon2-cffi==21.3.0 # https://github.com/hynek/argon2_cffi +whitenoise==6.4.0 # https://github.com/evansd/whitenoise +redis==4.5.4 # https://github.com/redis/redis-py +hiredis==2.2.2 # https://github.com/redis/hiredis-py + +# Django +# ------------------------------------------------------------------------------ +django==4.1.8 # pyup: < 4.2 # https://www.djangoproject.com/ +django-environ==0.10.0 # https://github.com/joke2k/django-environ +django-model-utils==4.3.1 # https://github.com/jazzband/django-model-utils +django-allauth==0.54.0 # https://github.com/pennersr/django-allauth +django-crispy-forms==2.0 # https://github.com/django-crispy-forms/django-crispy-forms +crispy-bootstrap5==0.7 # https://github.com/django-crispy-forms/crispy-bootstrap5 +django-redis==5.2.0 # https://github.com/jazzband/django-redis +# Django REST Framework +djangorestframework==3.14.0 # https://github.com/encode/django-rest-framework +django-cors-headers==3.14.0 # https://github.com/adamchainz/django-cors-headers +# DRF-spectacular for api documentation +drf-spectacular==0.26.2 # https://github.com/tfranzel/drf-spectacular diff --git a/requirements/local.txt b/requirements/local.txt new file mode 100644 index 0000000..0cf74a9 --- /dev/null +++ b/requirements/local.txt @@ -0,0 +1,36 @@ +-r base.txt + +Werkzeug[watchdog]==2.3.1 # https://github.com/pallets/werkzeug +ipdb==0.13.13 # https://github.com/gotcha/ipdb +psycopg2==2.9.6 # https://github.com/psycopg/psycopg2 + +# Testing +# ------------------------------------------------------------------------------ +mypy==1.2.0 # https://github.com/python/mypy +django-stubs==4.2.0 # https://github.com/typeddjango/django-stubs +pytest==7.3.1 # https://github.com/pytest-dev/pytest +pytest-sugar==0.9.7 # https://github.com/Frozenball/pytest-sugar +djangorestframework-stubs==3.14.0 # https://github.com/typeddjango/djangorestframework-stubs + +# Documentation +# ------------------------------------------------------------------------------ +sphinx==6.2.1 # https://github.com/sphinx-doc/sphinx +sphinx-autobuild==2021.3.14 # https://github.com/GaretJax/sphinx-autobuild + +# Code quality +# ------------------------------------------------------------------------------ +flake8==6.0.0 # https://github.com/PyCQA/flake8 +flake8-isort==6.0.0 # https://github.com/gforcada/flake8-isort +coverage==7.2.3 # https://github.com/nedbat/coveragepy +black==23.3.0 # https://github.com/psf/black +pylint-django==2.5.3 # https://github.com/PyCQA/pylint-django +pre-commit==3.2.2 # https://github.com/pre-commit/pre-commit + +# Django +# ------------------------------------------------------------------------------ +factory-boy==3.2.1 # https://github.com/FactoryBoy/factory_boy + +django-debug-toolbar==4.0.0 # https://github.com/jazzband/django-debug-toolbar +django-extensions==3.2.1 # https://github.com/django-extensions/django-extensions +django-coverage-plugin==3.0.0 # https://github.com/nedbat/django_coverage_plugin +pytest-django==4.5.2 # https://github.com/pytest-dev/pytest-django diff --git a/requirements/production.txt b/requirements/production.txt new file mode 100644 index 0000000..51b04b8 --- /dev/null +++ b/requirements/production.txt @@ -0,0 +1,11 @@ +# PRECAUTION: avoid production dependencies that aren't in development + +-r base.txt + +gunicorn==20.1.0 # https://github.com/benoitc/gunicorn +psycopg2==2.9.6 # https://github.com/psycopg/psycopg2 +sentry-sdk==1.21.0 # https://github.com/getsentry/sentry-python + +# Django +# ------------------------------------------------------------------------------ +django-anymail[sendgrid]==9.1 # https://github.com/anymail/django-anymail diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..afe12ad --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.11.3 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..8290642 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,10 @@ +# flake8 and pycodestyle don't support pyproject.toml +# https://github.com/PyCQA/flake8/issues/234 +# https://github.com/PyCQA/pycodestyle/issues/813 +[flake8] +max-line-length = 119 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules,venv,.venv + +[pycodestyle] +max-line-length = 119 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules,venv,.venv diff --git a/tests/test_merge_production_dotenvs_in_dotenv.py b/tests/test_merge_production_dotenvs_in_dotenv.py new file mode 100644 index 0000000..c0e68f6 --- /dev/null +++ b/tests/test_merge_production_dotenvs_in_dotenv.py @@ -0,0 +1,34 @@ +from pathlib import Path + +import pytest + +from merge_production_dotenvs_in_dotenv import merge + + +@pytest.mark.parametrize( + ("input_contents", "expected_output"), + [ + ([], ""), + ([""], "\n"), + (["JANE=doe"], "JANE=doe\n"), + (["SEP=true", "AR=ator"], "SEP=true\nAR=ator\n"), + (["A=0", "B=1", "C=2"], "A=0\nB=1\nC=2\n"), + (["X=x\n", "Y=y", "Z=z\n"], "X=x\n\nY=y\nZ=z\n\n"), + ], +) +def test_merge( + tmp_path: Path, + input_contents: list[str], + expected_output: str, +): + output_file = tmp_path / ".env" + + files_to_merge = [] + for num, input_content in enumerate(input_contents, start=1): + merge_file = tmp_path / f".service{num}" + merge_file.write_text(input_content) + files_to_merge.append(merge_file) + + merge(output_file, files_to_merge) + + assert output_file.read_text() == expected_output