diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8e8ac86 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: + # Update Github actions in workflows + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml new file mode 100644 index 0000000..9d4aaff --- /dev/null +++ b/.github/workflows/backend-ci.yml @@ -0,0 +1,61 @@ +name: CI + +# Enable Buildkit and let compose use it to speed up image building +env: + DOCKER_BUILDKIT: 1 + COMPOSE_DOCKER_CLI_BUILD: 1 + DATABASE_URL: pgsql://XDwVOJDPZWeKGECmAgdQMlsrrHgJFiir:EfhBcfu9MS0MNUboMvw7AOOvabRvO2jwDJEACSxXUslei0Me5WmJQE9JXV8oavo3@postgres:5432/personal_website + +on: + pull_request: + branches: ["master"] + paths-ignore: ["docs/**"] + + push: + branches: ["master"] + paths-ignore: ["docs/**"] + +defaults: + run: + working-directory: backend + +jobs: + flake8: + runs-on: ubuntu-latest + steps: + - name: Checkout Code Repository + uses: actions/checkout@v2 + + - name: Set up Python 3.8 + uses: actions/setup-python@v2 + with: + python-version: 3.8 + + - name: Install flake8 + run: | + python -m pip install --upgrade pip + pip install flake8 + + - name: Lint with flake8 + run: flake8 + + # 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@v2 + - name: Build the Stack + run: docker-compose -f docker-compose.yml build + + - name: Make DB Migrations + run: docker-compose -f docker-compose.yml run --rm django python manage.py migrate + + - name: Run the Stack + run: docker-compose -f docker-compose.yml up -d + + - name: Run Django Tests + run: docker-compose -f docker-compose.yml exec -e DATABASE_URL=${DATABASE_URL} -T django pytest + + - name: Tear down the Stack + run: docker-compose down diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..e63c0c1 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,4 @@ +.* +!.coveragerc +!.env +!.pylintrc diff --git a/backend/.editorconfig b/backend/.editorconfig new file mode 100644 index 0000000..4f1010e --- /dev/null +++ b/backend/.editorconfig @@ -0,0 +1,39 @@ +# 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 + +[*.py] +line_length = 88 +known_first_party = personal_website,config +multi_line_output = 3 +default_section = THIRDPARTY +recursive = true +skip = venv/ +skip_glob = **/migrations/*.py +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true + +[*.{html,css,scss,json,yml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab + +[nginx.conf] +indent_style = space +indent_size = 2 diff --git a/backend/.envs/.local/.django b/backend/.envs/.local/.django new file mode 100644 index 0000000..bcde257 --- /dev/null +++ b/backend/.envs/.local/.django @@ -0,0 +1,4 @@ +# General +# ------------------------------------------------------------------------------ +USE_DOCKER=yes +IPYTHONDIR=/app/.ipython diff --git a/backend/.envs/.local/.postgres b/backend/.envs/.local/.postgres new file mode 100644 index 0000000..575ae7e --- /dev/null +++ b/backend/.envs/.local/.postgres @@ -0,0 +1,7 @@ +# PostgreSQL +# ------------------------------------------------------------------------------ +POSTGRES_HOST=postgres +POSTGRES_PORT=5432 +POSTGRES_DB=personal_website +POSTGRES_USER=XDwVOJDPZWeKGECmAgdQMlsrrHgJFiir +POSTGRES_PASSWORD=EfhBcfu9MS0MNUboMvw7AOOvabRvO2jwDJEACSxXUslei0Me5WmJQE9JXV8oavo3 diff --git a/backend/.gitattributes b/backend/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/backend/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..cce5346 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,277 @@ +### 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 + + + + + +### 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 + +### Project template + +personal_website/media/ + +.pytest_cache/ + + +.ipython/ +.env +.envs/* +!.envs/.local/ diff --git a/backend/.pre-commit-config.yaml b/backend/.pre-commit-config.yaml new file mode 100644 index 0000000..55368bb --- /dev/null +++ b/backend/.pre-commit-config.yaml @@ -0,0 +1,29 @@ +exclude: 'docs|node_modules|migrations|.git|.tox' +default_stages: [commit] +fail_fast: true + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.3.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + + - repo: https://github.com/psf/black + rev: 20.8b1 + hooks: + - id: black + + - repo: https://github.com/timothycrosley/isort + rev: 5.6.4 + hooks: + - id: isort + + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.4 + hooks: + - id: flake8 + args: ['--config=setup.cfg'] + additional_dependencies: [flake8-isort] + diff --git a/backend/.pylintrc b/backend/.pylintrc new file mode 100644 index 0000000..e0faac0 --- /dev/null +++ b/backend/.pylintrc @@ -0,0 +1,14 @@ +[MASTER] +load-plugins=pylint_django + +[FORMAT] +max-line-length=120 + +[MESSAGES CONTROL] +disable=missing-docstring,invalid-name + +[DESIGN] +max-parents=13 + +[TYPECHECK] +generated-members=REQUEST,acl_users,aq_parent,"[a-zA-Z]+_set{1,2}",save,delete diff --git a/backend/LICENSE b/backend/LICENSE new file mode 100644 index 0000000..35835f8 --- /dev/null +++ b/backend/LICENSE @@ -0,0 +1,10 @@ + +The MIT License (MIT) +Copyright (c) 2020, Tom Vo + +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/backend/README.rst b/backend/README.rst new file mode 100644 index 0000000..07a0e91 --- /dev/null +++ b/backend/README.rst @@ -0,0 +1,89 @@ +Personal Website +================ + +Tom Vo's personal website + +.. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg + :target: https://github.com/pydanny/cookiecutter-django/ + :alt: Built with Cookiecutter Django +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/ambv/black + :alt: Black code style + + +:License: MIT + + +Settings +-------- + +Moved to settings_. + +.. _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 an **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 personal_website + +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 py.test +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:: + + $ pytest + +Live reloading and Sass CSS compilation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Moved to `Live reloading and SASS compilation`_. + +.. _`Live reloading and SASS compilation`: http://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html + + + + + +Deployment +---------- + +The following details how to deploy this application. + + + +Docker +^^^^^^ + +See detailed `cookiecutter-django Docker documentation`_. + +.. _`cookiecutter-django Docker documentation`: http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html + + + diff --git a/backend/compose/local/django/Dockerfile b/backend/compose/local/django/Dockerfile new file mode 100644 index 0000000..bb7e134 --- /dev/null +++ b/backend/compose/local/django/Dockerfile @@ -0,0 +1,31 @@ +FROM python:3.8-slim-buster + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update \ + # dependencies for building Python packages + && apt-get install -y build-essential \ + # psycopg2 dependencies + && apt-get install -y libpq-dev \ + # Translations dependencies + && apt-get install -y gettext \ + # 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 +RUN pip install -r /requirements/local.txt + +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 + +WORKDIR /app + +ENTRYPOINT ["/entrypoint"] diff --git a/backend/compose/local/django/start b/backend/compose/local/django/start new file mode 100644 index 0000000..e815638 --- /dev/null +++ b/backend/compose/local/django/start @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python manage.py migrate +python manage.py runserver_plus 0.0.0.0:8000 + diff --git a/backend/compose/local/docs/Dockerfile b/backend/compose/local/docs/Dockerfile new file mode 100644 index 0000000..315fdd4 --- /dev/null +++ b/backend/compose/local/docs/Dockerfile @@ -0,0 +1,31 @@ +FROM python:3.8-slim-buster + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update \ + # dependencies for building Python packages + && apt-get install -y build-essential \ + # psycopg2 dependencies + && apt-get install -y libpq-dev \ + # Translations dependencies + && apt-get install -y gettext \ + # Uncomment below lines to enable Sphinx output to latex and pdf + # && apt-get install -y texlive-latex-recommended \ + # && apt-get install -y texlive-fonts-recommended \ + # && apt-get install -y texlive-latex-extra \ + # && apt-get install -y latexmk \ + # 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 +# All imports needed for autodoc. +RUN pip install -r /requirements/local.txt -r /requirements/production.txt + +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/backend/compose/local/docs/start b/backend/compose/local/docs/start new file mode 100644 index 0000000..fd2e0de --- /dev/null +++ b/backend/compose/local/docs/start @@ -0,0 +1,7 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + +make livehtml diff --git a/backend/compose/production/django/Dockerfile b/backend/compose/production/django/Dockerfile new file mode 100644 index 0000000..23493f4 --- /dev/null +++ b/backend/compose/production/django/Dockerfile @@ -0,0 +1,39 @@ + +FROM python:3.8-slim-buster + +ENV PYTHONUNBUFFERED 1 + +RUN apt-get update \ + # dependencies for building Python packages + && apt-get install -y build-essential \ + # psycopg2 dependencies + && apt-get install -y libpq-dev \ + # Translations dependencies + && apt-get install -y gettext \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +RUN addgroup --system django \ + && adduser --system --ingroup django django + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements /requirements +RUN pip install --no-cache-dir -r /requirements/production.txt \ + && rm -rf /requirements + +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 --chown=django:django . /app + +USER django + +WORKDIR /app + +ENTRYPOINT ["/entrypoint"] diff --git a/backend/compose/production/django/entrypoint b/backend/compose/production/django/entrypoint new file mode 100644 index 0000000..2c5bec8 --- /dev/null +++ b/backend/compose/production/django/entrypoint @@ -0,0 +1,42 @@ +#!/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}" + +postgres_ready() { +python << END +import sys + +import psycopg2 + +try: + psycopg2.connect( + dbname="${POSTGRES_DB}", + user="${POSTGRES_USER}", + password="${POSTGRES_PASSWORD}", + host="${POSTGRES_HOST}", + port="${POSTGRES_PORT}", + ) +except psycopg2.OperationalError: + sys.exit(-1) +sys.exit(0) + +END +} +until postgres_ready; do + >&2 echo 'Waiting for PostgreSQL to become available...' + sleep 1 +done +>&2 echo 'PostgreSQL is available' + +exec "$@" diff --git a/backend/compose/production/django/start b/backend/compose/production/django/start new file mode 100644 index 0000000..e6ded06 --- /dev/null +++ b/backend/compose/production/django/start @@ -0,0 +1,11 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python /app/manage.py collectstatic --noinput + + +/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app diff --git a/backend/compose/production/postgres/Dockerfile b/backend/compose/production/postgres/Dockerfile new file mode 100644 index 0000000..c4160f1 --- /dev/null +++ b/backend/compose/production/postgres/Dockerfile @@ -0,0 +1,6 @@ +FROM postgres:12.3 + +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/backend/compose/production/postgres/maintenance/_sourced/constants.sh b/backend/compose/production/postgres/maintenance/_sourced/constants.sh new file mode 100644 index 0000000..6ca4f0c --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/_sourced/countdown.sh b/backend/compose/production/postgres/maintenance/_sourced/countdown.sh new file mode 100644 index 0000000..e6cbfb6 --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/_sourced/messages.sh b/backend/compose/production/postgres/maintenance/_sourced/messages.sh new file mode 100644 index 0000000..f6be756 --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/_sourced/yes_no.sh b/backend/compose/production/postgres/maintenance/_sourced/yes_no.sh new file mode 100644 index 0000000..fd9cae1 --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/backup b/backend/compose/production/postgres/maintenance/backup new file mode 100644 index 0000000..ee0c9d6 --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/backups b/backend/compose/production/postgres/maintenance/backups new file mode 100644 index 0000000..0484ccf --- /dev/null +++ b/backend/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/backend/compose/production/postgres/maintenance/restore b/backend/compose/production/postgres/maintenance/restore new file mode 100644 index 0000000..9661ca7 --- /dev/null +++ b/backend/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/backend/compose/production/traefik/Dockerfile b/backend/compose/production/traefik/Dockerfile new file mode 100644 index 0000000..aa87905 --- /dev/null +++ b/backend/compose/production/traefik/Dockerfile @@ -0,0 +1,5 @@ +FROM traefik:v2.2.11 +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/backend/compose/production/traefik/traefik.yml b/backend/compose/production/traefik/traefik.yml new file mode 100644 index 0000000..296575e --- /dev/null +++ b/backend/compose/production/traefik/traefik.yml @@ -0,0 +1,69 @@ +log: + level: INFO + +entryPoints: + web: + # http + address: ":80" + + web-secure: + # https + address: ":443" + +certificatesResolvers: + letsencrypt: + # https://docs.traefik.io/master/https/acme/#lets-encrypt + acme: + email: "tomvothecoder@gmail.com" + storage: /etc/traefik/acme/acme.json + # https://docs.traefik.io/master/https/acme/#httpchallenge + httpChallenge: + entryPoint: web + +http: + routers: + web-router: + rule: "Host(`tomvo.me`) || Host(`www.tomvo.me`)" + + entryPoints: + - web + middlewares: + - redirect + - csrf + service: django + + web-secure-router: + rule: "Host(`tomvo.me`) || Host(`www.tomvo.me`)" + + entryPoints: + - web-secure + middlewares: + - csrf + service: django + tls: + # https://docs.traefik.io/master/routing/routers/#certresolver + certResolver: letsencrypt + + middlewares: + redirect: + # https://docs.traefik.io/master/middlewares/redirectscheme/ + redirectScheme: + scheme: https + permanent: true + 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 + +providers: + # https://docs.traefik.io/master/providers/file/ + file: + filename: /etc/traefik/traefik.yml + watch: true diff --git a/backend/config/__init__.py b/backend/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/config/api_router.py b/backend/config/api_router.py new file mode 100644 index 0000000..c56f901 --- /dev/null +++ b/backend/config/api_router.py @@ -0,0 +1,15 @@ +from django.conf import settings +from rest_framework.routers import DefaultRouter, SimpleRouter + +from personal_website.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/backend/config/settings/__init__.py b/backend/config/settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/config/settings/base.py b/backend/config/settings/base.py new file mode 100644 index 0000000..7655006 --- /dev/null +++ b/backend/config/settings/base.py @@ -0,0 +1,285 @@ +""" +Base settings to build other settings files upon. +""" +from pathlib import Path + +import environ + +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent +# personal_website/ +APPS_DIR = ROOT_DIR / "personal_website" +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(ROOT_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-l10n +USE_L10N = 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(ROOT_DIR / "locale")] + +# DATABASES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#databases +DATABASES = {"default": env.db("DATABASE_URL")} +DATABASES["default"]["ATOMIC_REQUESTS"] = True + +# 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", + "allauth", + "allauth.account", + "allauth.socialaccount", + "rest_framework", + "rest_framework.authtoken", + "corsheaders", +] + +LOCAL_APPS = [ + "personal_website.users.apps.UsersConfig", + # 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": "personal_website.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.common.BrokenLinkEmailsMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", +] + +# STATIC +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#static-root +STATIC_ROOT = str(ROOT_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/#template-dirs + "DIRS": [str(APPS_DIR / "templates")], + "OPTIONS": { + # https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders + # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types + "loaders": [ + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", + ], + # 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", + "personal_website.utils.context_processors.settings_context", + ], + }, + } +] + +# 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 = "bootstrap4" + +# 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/#secure-browser-xss-filter +SECURE_BROWSER_XSS_FILTER = 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 = [("""Tom Vo""", "tomvothecoder@gmail.com")] +# 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 = "username" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_REQUIRED = True +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_VERIFICATION = "mandatory" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_ADAPTER = "personal_website.users.adapters.AccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +SOCIALACCOUNT_ADAPTER = "personal_website.users.adapters.SocialAccountAdapter" + +# 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",), +} + +# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup +CORS_URLS_REGEX = r"^/api/.*$" +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/backend/config/settings/local.py b/backend/config/settings/local.py new file mode 100644 index 0000000..d822b5a --- /dev/null +++ b/backend/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="9FJxdlECUG6OFlun6Fq7G6kyLSGFhTgnyLfPASQeh5Wjn4pFyG1JLPPydUzUCFJM", +) +# 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-backend +EMAIL_BACKEND = env( + "DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend" +) + +# 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/backend/config/settings/production.py b/backend/config/settings/production.py new file mode 100644 index 0000000..9c4e2c0 --- /dev/null +++ b/backend/config/settings/production.py @@ -0,0 +1,151 @@ +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=["tomvo.me"]) + +# DATABASES +# ------------------------------------------------------------------------------ +DATABASES["default"] = env.db("DATABASE_URL") # noqa F405 +DATABASES["default"]["ATOMIC_REQUESTS"] = True # noqa F405 +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 +# ------------------------------------------------------------------------------ + +# TEMPLATES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#templates +TEMPLATES[-1]["OPTIONS"]["loaders"] = [ # type: ignore[index] # noqa F405 + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", + ], + ) +] + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email +DEFAULT_FROM_EMAIL = env( + "DJANGO_DEFAULT_FROM_EMAIL", default="Personal Website " +) +# 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="[Personal Website]" +) + +# 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 +EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" +ANYMAIL = {} + + +# 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. +# A sample logging configuration. The only tangible logging +# performed by this configuration is to send an email to +# the site admins on every HTTP 500 error when DEBUG=False. +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s " + "%(process)d %(thread)d %(message)s" + } + }, + "handlers": { + "mail_admins": { + "level": "ERROR", + "filters": ["require_debug_false"], + "class": "django.utils.log.AdminEmailHandler", + }, + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + }, + }, + "root": {"level": "INFO", "handlers": ["console"]}, + "loggers": { + "django.request": { + "handlers": ["mail_admins"], + "level": "ERROR", + "propagate": True, + }, + "django.security.DisallowedHost": { + "level": "ERROR", + "handlers": ["console", "mail_admins"], + "propagate": True, + }, + }, +} + +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/backend/config/settings/test.py b/backend/config/settings/test.py new file mode 100644 index 0000000..52e0df4 --- /dev/null +++ b/backend/config/settings/test.py @@ -0,0 +1,51 @@ +""" +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="k4G9brwYkN2LPW90II1b9hZ8dGglWKudVSYL1MIXRnHQxNNCpu5Sf7arPEUq0Ry1", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner +TEST_RUNNER = "django.test.runner.DiscoverRunner" + +# CACHES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#caches +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "", + } +} + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] + +# TEMPLATES +# ------------------------------------------------------------------------------ +TEMPLATES[-1]["OPTIONS"]["loaders"] = [ # type: ignore[index] # noqa F405 + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", + ], + ) +] + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend +EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" + +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/backend/config/urls.py b/backend/config/urls.py new file mode 100644 index 0000000..e01acb6 --- /dev/null +++ b/backend/config/urls.py @@ -0,0 +1,54 @@ +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 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("personal_website.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), +] + +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/backend/config/wsgi.py b/backend/config/wsgi.py new file mode 100644 index 0000000..8ae6453 --- /dev/null +++ b/backend/config/wsgi.py @@ -0,0 +1,38 @@ +""" +WSGI config for Personal Website 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 +# personal_website directory. +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent +sys.path.append(str(ROOT_DIR / "personal_website")) +# 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/backend/docker-compose.prod.yml b/backend/docker-compose.prod.yml new file mode 100644 index 0000000..08aee17 --- /dev/null +++ b/backend/docker-compose.prod.yml @@ -0,0 +1,47 @@ +version: "3" + +volumes: + production_postgres_data: {} + production_postgres_data_backups: {} + production_traefik: {} + +services: + django: + build: + context: . + dockerfile: ./compose/production/django/Dockerfile + image: personal_website_production_django + depends_on: + - postgres + - redis + env_file: + - ./.envs/.production/.django + - ./.envs/.production/.postgres + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: personal_website_production_postgres + volumes: + - production_postgres_data:/var/lib/postgresql/data:Z + - production_postgres_data_backups:/backups:z + env_file: + - ./.envs/.production/.postgres + + traefik: + build: + context: . + dockerfile: ./compose/production/traefik/Dockerfile + image: personal_website_production_traefik + depends_on: + - django + volumes: + - production_traefik:/etc/traefik/acme:z + ports: + - "0.0.0.0:80:80" + - "0.0.0.0:443:443" + + redis: + image: redis:5.0 diff --git a/backend/docker-compose.yml b/backend/docker-compose.yml new file mode 100644 index 0000000..828574e --- /dev/null +++ b/backend/docker-compose.yml @@ -0,0 +1,35 @@ +version: "3" + +volumes: + local_postgres_data: {} + local_postgres_data_backups: {} + +services: + django: + build: + context: . + dockerfile: ./compose/local/django/Dockerfile + image: personal_website_local_django + container_name: django + depends_on: + - postgres + 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: personal_website_production_postgres + container_name: postgres + volumes: + - local_postgres_data:/var/lib/postgresql/data:Z + - local_postgres_data_backups:/backups:z + env_file: + - ./.envs/.local/.postgres diff --git a/backend/locale/README.rst b/backend/locale/README.rst new file mode 100644 index 0000000..c2f1dcd --- /dev/null +++ b/backend/locale/README.rst @@ -0,0 +1,6 @@ +Translations +============ + +Translations will be placed in this folder when running:: + + python manage.py makemessages diff --git a/backend/manage.py b/backend/manage.py new file mode 100755 index 0000000..31ca674 --- /dev/null +++ b/backend/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 + # personal_website directory. + current_path = Path(__file__).parent.resolve() + sys.path.append(str(current_path / "personal_website")) + + execute_from_command_line(sys.argv) diff --git a/backend/merge_production_dotenvs_in_dotenv.py b/backend/merge_production_dotenvs_in_dotenv.py new file mode 100644 index 0000000..d1170ef --- /dev/null +++ b/backend/merge_production_dotenvs_in_dotenv.py @@ -0,0 +1,67 @@ +import os +from pathlib import Path +from typing import Sequence + +import pytest + +ROOT_DIR_PATH = Path(__file__).parent.resolve() +PRODUCTION_DOTENVS_DIR_PATH = ROOT_DIR_PATH / ".envs" / ".production" +PRODUCTION_DOTENV_FILE_PATHS = [ + PRODUCTION_DOTENVS_DIR_PATH / ".django", + PRODUCTION_DOTENVS_DIR_PATH / ".postgres", +] +DOTENV_FILE_PATH = ROOT_DIR_PATH / ".env" + + +def merge( + output_file_path: str, merged_file_paths: Sequence[str], append_linesep: bool = True +) -> None: + with open(output_file_path, "w") as output_file: + for merged_file_path in merged_file_paths: + with open(merged_file_path, "r") as merged_file: + merged_file_content = merged_file.read() + output_file.write(merged_file_content) + if append_linesep: + output_file.write(os.linesep) + + +def main(): + merge(DOTENV_FILE_PATH, PRODUCTION_DOTENV_FILE_PATHS) + + +@pytest.mark.parametrize("merged_file_count", range(3)) +@pytest.mark.parametrize("append_linesep", [True, False]) +def test_merge(tmpdir_factory, merged_file_count: int, append_linesep: bool): + tmp_dir_path = Path(str(tmpdir_factory.getbasetemp())) + + output_file_path = tmp_dir_path / ".env" + + expected_output_file_content = "" + merged_file_paths = [] + for i in range(merged_file_count): + merged_file_ord = i + 1 + + merged_filename = ".service{}".format(merged_file_ord) + merged_file_path = tmp_dir_path / merged_filename + + merged_file_content = merged_filename * merged_file_ord + + with open(merged_file_path, "w+") as file: + file.write(merged_file_content) + + expected_output_file_content += merged_file_content + if append_linesep: + expected_output_file_content += os.linesep + + merged_file_paths.append(merged_file_path) + + merge(output_file_path, merged_file_paths, append_linesep) + + with open(output_file_path, "r") as output_file: + actual_output_file_content = output_file.read() + + assert actual_output_file_content == expected_output_file_content + + +if __name__ == "__main__": + main() diff --git a/backend/personal_website/__init__.py b/backend/personal_website/__init__.py new file mode 100644 index 0000000..e1d8615 --- /dev/null +++ b/backend/personal_website/__init__.py @@ -0,0 +1,7 @@ +__version__ = "0.1.0" +__version_info__ = tuple( + [ + int(num) if num.isdigit() else num + for num in __version__.replace("-", ".", 1).split(".") + ] +) diff --git a/backend/personal_website/conftest.py b/backend/personal_website/conftest.py new file mode 100644 index 0000000..665533d --- /dev/null +++ b/backend/personal_website/conftest.py @@ -0,0 +1,14 @@ +import pytest + +from personal_website.users.models import User +from personal_website.users.tests.factories import UserFactory + + +@pytest.fixture(autouse=True) +def media_storage(settings, tmpdir): + settings.MEDIA_ROOT = tmpdir.strpath + + +@pytest.fixture +def user() -> User: + return UserFactory() diff --git a/backend/personal_website/contrib/__init__.py b/backend/personal_website/contrib/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/contrib/sites/__init__.py b/backend/personal_website/contrib/sites/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/contrib/sites/migrations/0001_initial.py b/backend/personal_website/contrib/sites/migrations/0001_initial.py new file mode 100644 index 0000000..304cd6d --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/contrib/sites/migrations/0002_alter_domain_unique.py b/backend/personal_website/contrib/sites/migrations/0002_alter_domain_unique.py new file mode 100644 index 0000000..2c8d6da --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/contrib/sites/migrations/0003_set_site_domain_and_name.py b/backend/personal_website/contrib/sites/migrations/0003_set_site_domain_and_name.py new file mode 100644 index 0000000..25ead85 --- /dev/null +++ b/backend/personal_website/contrib/sites/migrations/0003_set_site_domain_and_name.py @@ -0,0 +1,34 @@ +""" +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_site_forward(apps, schema_editor): + """Set site domain and name.""" + Site = apps.get_model("sites", "Site") + Site.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + "domain": "tomvo.me", + "name": "Personal Website", + }, + ) + + +def update_site_backward(apps, schema_editor): + """Revert site domain and name to default.""" + Site = apps.get_model("sites", "Site") + Site.objects.update_or_create( + id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"} + ) + + +class Migration(migrations.Migration): + + dependencies = [("sites", "0002_alter_domain_unique")] + + operations = [migrations.RunPython(update_site_forward, update_site_backward)] diff --git a/backend/personal_website/contrib/sites/migrations/__init__.py b/backend/personal_website/contrib/sites/migrations/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/static/css/project.css b/backend/personal_website/static/css/project.css new file mode 100644 index 0000000..f1d543d --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/static/fonts/.gitkeep b/backend/personal_website/static/fonts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/static/images/favicons/favicon.ico b/backend/personal_website/static/images/favicons/favicon.ico new file mode 100644 index 0000000..e1c1dd1 Binary files /dev/null and b/backend/personal_website/static/images/favicons/favicon.ico differ diff --git a/backend/personal_website/static/js/project.js b/backend/personal_website/static/js/project.js new file mode 100644 index 0000000..d26d23b --- /dev/null +++ b/backend/personal_website/static/js/project.js @@ -0,0 +1 @@ +/* Project specific Javascript goes here. */ diff --git a/backend/personal_website/static/sass/custom_bootstrap_vars.scss b/backend/personal_website/static/sass/custom_bootstrap_vars.scss new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/static/sass/project.scss b/backend/personal_website/static/sass/project.scss new file mode 100644 index 0000000..3c8f261 --- /dev/null +++ b/backend/personal_website/static/sass/project.scss @@ -0,0 +1,37 @@ + + + + +// project specific CSS goes here + +//////////////////////////////// + //Variables// +//////////////////////////////// + +// Alert colors + +$white: #fff; +$mint-green: #d6e9c6; +$black: #000; +$pink: #f2dede; +$dark-pink: #eed3d7; +$red: #b94a48; + +//////////////////////////////// + //Alerts// +//////////////////////////////// + +// bootstrap alert CSS, translated to the django-standard levels of +// debug, info, success, warning, error + +.alert-debug { + background-color: $white; + border-color: $mint-green; + color: $black; +} + +.alert-error { + background-color: $pink; + border-color: $dark-pink; + color: $red; +} diff --git a/backend/personal_website/templates/403.html b/backend/personal_website/templates/403.html new file mode 100644 index 0000000..77db8ae --- /dev/null +++ b/backend/personal_website/templates/403.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Forbidden (403){% endblock %} + +{% block content %} +

Forbidden (403)

+ +

CSRF verification failed. Request aborted.

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

Page not found

+ +

This is not the page you were looking for.

+{% endblock content %} diff --git a/backend/personal_website/templates/500.html b/backend/personal_website/templates/500.html new file mode 100644 index 0000000..21df606 --- /dev/null +++ b/backend/personal_website/templates/500.html @@ -0,0 +1,13 @@ +{% 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/backend/personal_website/templates/account/account_inactive.html b/backend/personal_website/templates/account/account_inactive.html new file mode 100644 index 0000000..17c2157 --- /dev/null +++ b/backend/personal_website/templates/account/account_inactive.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Account Inactive" %}{% endblock %} + +{% block inner %} +

{% trans "Account Inactive" %}

+ +

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

+{% endblock %} + diff --git a/backend/personal_website/templates/account/base.html b/backend/personal_website/templates/account/base.html new file mode 100644 index 0000000..8e1f260 --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/templates/account/email.html b/backend/personal_website/templates/account/email.html new file mode 100644 index 0000000..0dc8d14 --- /dev/null +++ b/backend/personal_website/templates/account/email.html @@ -0,0 +1,80 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Account" %}{% endblock %} + +{% block inner %} +

{% trans "E-mail Addresses" %}

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

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

+ + + +{% else %} +

{% trans 'Warning:'%} {% trans "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 %} + + +

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

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +{% endblock %} + + +{% block javascript %} +{{ block.super }} + +{% endblock %} + diff --git a/backend/personal_website/templates/account/email_confirm.html b/backend/personal_website/templates/account/email_confirm.html new file mode 100644 index 0000000..46c7812 --- /dev/null +++ b/backend/personal_website/templates/account/email_confirm.html @@ -0,0 +1,32 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %} + + +{% block inner %} +

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

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

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

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

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

+ +{% endif %} + +{% endblock %} + diff --git a/backend/personal_website/templates/account/login.html b/backend/personal_website/templates/account/login.html new file mode 100644 index 0000000..2cadea6 --- /dev/null +++ b/backend/personal_website/templates/account/login.html @@ -0,0 +1,48 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account socialaccount %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Sign In" %}{% endblock %} + +{% block inner %} + +

{% trans "Sign In" %}

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

{% blocktrans with site.name as site_name %}Please sign in with one +of your existing third party accounts. Or, sign up +for a {{ site_name }} account and sign in below:{% endblocktrans %}

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

{% blocktrans %}If you have not created an account yet, then please +sign up first.{% endblocktrans %}

+{% endif %} + + + +{% endblock %} + diff --git a/backend/personal_website/templates/account/logout.html b/backend/personal_website/templates/account/logout.html new file mode 100644 index 0000000..8e2e675 --- /dev/null +++ b/backend/personal_website/templates/account/logout.html @@ -0,0 +1,22 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Out" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Out" %}

+ +

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

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

{% trans "Change Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/backend/personal_website/templates/account/password_reset.html b/backend/personal_website/templates/account/password_reset.html new file mode 100644 index 0000000..845bbda --- /dev/null +++ b/backend/personal_website/templates/account/password_reset.html @@ -0,0 +1,26 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Password Reset" %}{% endblock %} + +{% block inner %} + +

{% trans "Password Reset" %}

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

{% trans "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 }} + +
+ +

{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}

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

{% trans "Password Reset" %}

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

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

+{% endblock %} + diff --git a/backend/personal_website/templates/account/password_reset_from_key.html b/backend/personal_website/templates/account/password_reset_from_key.html new file mode 100644 index 0000000..4abdb56 --- /dev/null +++ b/backend/personal_website/templates/account/password_reset_from_key.html @@ -0,0 +1,25 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

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

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

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

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

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

+ {% endif %} + {% endif %} +{% endblock %} + diff --git a/backend/personal_website/templates/account/password_reset_from_key_done.html b/backend/personal_website/templates/account/password_reset_from_key_done.html new file mode 100644 index 0000000..89be086 --- /dev/null +++ b/backend/personal_website/templates/account/password_reset_from_key_done.html @@ -0,0 +1,10 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% trans "Change Password" %}

+

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

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

{% trans "Set Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/backend/personal_website/templates/account/signup.html b/backend/personal_website/templates/account/signup.html new file mode 100644 index 0000000..6a2954e --- /dev/null +++ b/backend/personal_website/templates/account/signup.html @@ -0,0 +1,23 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Signup" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up" %}

+ +

{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}

+ + + +{% endblock %} + diff --git a/backend/personal_website/templates/account/signup_closed.html b/backend/personal_website/templates/account/signup_closed.html new file mode 100644 index 0000000..2322f17 --- /dev/null +++ b/backend/personal_website/templates/account/signup_closed.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Up Closed" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up Closed" %}

+ +

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

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

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

+ +

{% blocktrans %}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.{% endblocktrans %}

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

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

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

{% blocktrans %}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. {% endblocktrans %}

+ +

{% blocktrans %}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.{% endblocktrans %}

+ +

{% blocktrans %}Note: you can still change your e-mail address.{% endblocktrans %}

+ + +{% endblock %} + diff --git a/backend/personal_website/templates/base.html b/backend/personal_website/templates/base.html new file mode 100644 index 0000000..97d2c0f --- /dev/null +++ b/backend/personal_website/templates/base.html @@ -0,0 +1,114 @@ +{% load static i18n %} + + + + + {% block title %}Personal Website{% endblock title %} + + + + + + + + + + {% block css %} + + + + + + + + + + + + + {% endblock %} + + + + + +
+ + +
+ +
+ + {% 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 javascript %} + + + + + + + + + + + + + + + {% endblock javascript %} + + + diff --git a/backend/personal_website/templates/pages/about.html b/backend/personal_website/templates/pages/about.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/backend/personal_website/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/backend/personal_website/templates/pages/home.html b/backend/personal_website/templates/pages/home.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/backend/personal_website/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/backend/personal_website/templates/users/user_detail.html b/backend/personal_website/templates/users/user_detail.html new file mode 100644 index 0000000..e86eda1 --- /dev/null +++ b/backend/personal_website/templates/users/user_detail.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}User: {{ object.username }}{% endblock %} + +{% block content %} +
+ +
+
+ +

{{ object.username }}

+ {% if object.name %} +

{{ object.name }}

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

{{ user.username }}

+
+ {% csrf_token %} + {{ form|crispy }} +
+
+ +
+
+
+{% endblock %} diff --git a/backend/personal_website/users/__init__.py b/backend/personal_website/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/users/adapters.py b/backend/personal_website/users/adapters.py new file mode 100644 index 0000000..0d206fa --- /dev/null +++ b/backend/personal_website/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/backend/personal_website/users/admin.py b/backend/personal_website/users/admin.py new file mode 100644 index 0000000..2efb5e8 --- /dev/null +++ b/backend/personal_website/users/admin.py @@ -0,0 +1,19 @@ +from django.contrib import admin +from django.contrib.auth import admin as auth_admin +from django.contrib.auth import get_user_model + +from personal_website.users.forms import UserChangeForm, UserCreationForm + +User = get_user_model() + + +@admin.register(User) +class UserAdmin(auth_admin.UserAdmin): + + form = UserChangeForm + add_form = UserCreationForm + fieldsets = (("User", {"fields": ("name",)}),) + tuple( + auth_admin.UserAdmin.fieldsets + ) + list_display = ["username", "name", "is_superuser"] + search_fields = ["name"] diff --git a/backend/personal_website/users/api/serializers.py b/backend/personal_website/users/api/serializers.py new file mode 100644 index 0000000..8bd39d3 --- /dev/null +++ b/backend/personal_website/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 = ["username", "email", "name", "url"] + + extra_kwargs = { + "url": {"view_name": "api:user-detail", "lookup_field": "username"} + } diff --git a/backend/personal_website/users/api/views.py b/backend/personal_website/users/api/views.py new file mode 100644 index 0000000..288ea7a --- /dev/null +++ b/backend/personal_website/users/api/views.py @@ -0,0 +1,24 @@ +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 = "username" + + def get_queryset(self, *args, **kwargs): + return self.queryset.filter(id=self.request.user.id) + + @action(detail=False, methods=["GET"]) + def me(self, request): + serializer = UserSerializer(request.user, context={"request": request}) + return Response(status=status.HTTP_200_OK, data=serializer.data) diff --git a/backend/personal_website/users/apps.py b/backend/personal_website/users/apps.py new file mode 100644 index 0000000..7b8b7b3 --- /dev/null +++ b/backend/personal_website/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class UsersConfig(AppConfig): + name = "personal_website.users" + verbose_name = _("Users") + + def ready(self): + try: + import personal_website.users.signals # noqa F401 + except ImportError: + pass diff --git a/backend/personal_website/users/forms.py b/backend/personal_website/users/forms.py new file mode 100644 index 0000000..7d3a296 --- /dev/null +++ b/backend/personal_website/users/forms.py @@ -0,0 +1,31 @@ +from django.contrib.auth import forms as admin_forms +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.utils.translation import gettext_lazy as _ + +User = get_user_model() + + +class UserChangeForm(admin_forms.UserChangeForm): + class Meta(admin_forms.UserChangeForm.Meta): + model = User + + +class UserCreationForm(admin_forms.UserCreationForm): + + error_message = admin_forms.UserCreationForm.error_messages.update( + {"duplicate_username": _("This username has already been taken.")} + ) + + class Meta(admin_forms.UserCreationForm.Meta): + model = User + + def clean_username(self): + username = self.cleaned_data["username"] + + try: + User.objects.get(username=username) + except User.DoesNotExist: + return username + + raise ValidationError(self.error_messages["duplicate_username"]) diff --git a/backend/personal_website/users/migrations/0001_initial.py b/backend/personal_website/users/migrations/0001_initial.py new file mode 100644 index 0000000..c9d8905 --- /dev/null +++ b/backend/personal_website/users/migrations/0001_initial.py @@ -0,0 +1,132 @@ +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [("auth", "0008_alter_user_username_max_length")] + + operations = [ + migrations.CreateModel( + name="User", + fields=[ + ( + "id", + models.AutoField( + 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", + ), + ), + ( + "username", + models.CharField( + error_messages={ + "unique": "A user with that username already exists." + }, + help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", + max_length=150, + unique=True, + validators=[ + django.contrib.auth.validators.UnicodeUsernameValidator() + ], + verbose_name="username", + ), + ), + ( + "first_name", + models.CharField( + blank=True, max_length=30, verbose_name="first name" + ), + ), + ( + "last_name", + models.CharField( + blank=True, max_length=150, verbose_name="last name" + ), + ), + ( + "email", + models.EmailField( + blank=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_plural": "users", + "verbose_name": "user", + "abstract": False, + }, + managers=[("objects", django.contrib.auth.models.UserManager())], + ) + ] diff --git a/backend/personal_website/users/migrations/__init__.py b/backend/personal_website/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/users/models.py b/backend/personal_website/users/models.py new file mode 100644 index 0000000..6890f6f --- /dev/null +++ b/backend/personal_website/users/models.py @@ -0,0 +1,20 @@ +from django.contrib.auth.models import AbstractUser +from django.db.models import CharField +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ + + +class User(AbstractUser): + """Default user for Personal Website.""" + + #: First and last name do not cover name patterns around the globe + name = CharField(_("Name of User"), blank=True, max_length=255) + + def get_absolute_url(self): + """Get url for user's detail view. + + Returns: + str: URL for user detail. + + """ + return reverse("users:detail", kwargs={"username": self.username}) diff --git a/backend/personal_website/users/tests/__init__.py b/backend/personal_website/users/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/users/tests/factories.py b/backend/personal_website/users/tests/factories.py new file mode 100644 index 0000000..05b3ae0 --- /dev/null +++ b/backend/personal_website/users/tests/factories.py @@ -0,0 +1,32 @@ +from typing import Any, Sequence + +from django.contrib.auth import get_user_model +from factory import Faker, post_generation +from factory.django import DjangoModelFactory + + +class UserFactory(DjangoModelFactory): + + username = Faker("user_name") + 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, + ).generate(params={"locale": None}) + ) + self.set_password(password) + + class Meta: + model = get_user_model() + django_get_or_create = ["username"] diff --git a/backend/personal_website/users/tests/test_drf_urls.py b/backend/personal_website/users/tests/test_drf_urls.py new file mode 100644 index 0000000..c00ce8b --- /dev/null +++ b/backend/personal_website/users/tests/test_drf_urls.py @@ -0,0 +1,24 @@ +import pytest +from django.urls import resolve, reverse + +from personal_website.users.models import User + +pytestmark = pytest.mark.django_db + + +def test_user_detail(user: User): + assert ( + reverse("api:user-detail", kwargs={"username": user.username}) + == f"/api/users/{user.username}/" + ) + assert resolve(f"/api/users/{user.username}/").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/backend/personal_website/users/tests/test_drf_views.py b/backend/personal_website/users/tests/test_drf_views.py new file mode 100644 index 0000000..5cb50f5 --- /dev/null +++ b/backend/personal_website/users/tests/test_drf_views.py @@ -0,0 +1,34 @@ +import pytest +from django.test import RequestFactory + +from personal_website.users.api.views import UserViewSet +from personal_website.users.models import User + +pytestmark = pytest.mark.django_db + + +class TestUserViewSet: + def test_get_queryset(self, user: User, rf: RequestFactory): + view = UserViewSet() + request = rf.get("/fake-url/") + request.user = user + + view.request = request + + assert user in view.get_queryset() + + def test_me(self, user: User, rf: RequestFactory): + view = UserViewSet() + request = rf.get("/fake-url/") + request.user = user + + view.request = request + + response = view.me(request) + + assert response.data == { + "username": user.username, + "email": user.email, + "name": user.name, + "url": f"http://testserver/api/users/{user.username}/", + } diff --git a/backend/personal_website/users/tests/test_forms.py b/backend/personal_website/users/tests/test_forms.py new file mode 100644 index 0000000..197e309 --- /dev/null +++ b/backend/personal_website/users/tests/test_forms.py @@ -0,0 +1,40 @@ +import pytest + +from personal_website.users.forms import UserCreationForm +from personal_website.users.tests.factories import UserFactory + +pytestmark = pytest.mark.django_db + + +class TestUserCreationForm: + def test_clean_username(self): + # A user with proto_user params does not exist yet. + proto_user = UserFactory.build() + + form = UserCreationForm( + { + "username": proto_user.username, + "password1": proto_user._password, + "password2": proto_user._password, + } + ) + + assert form.is_valid() + assert form.clean_username() == proto_user.username + + # Creating a user. + form.save() + + # The user with proto_user params already exists, + # hence cannot be created. + form = UserCreationForm( + { + "username": proto_user.username, + "password1": proto_user._password, + "password2": proto_user._password, + } + ) + + assert not form.is_valid() + assert len(form.errors) == 1 + assert "username" in form.errors diff --git a/backend/personal_website/users/tests/test_models.py b/backend/personal_website/users/tests/test_models.py new file mode 100644 index 0000000..ab875cb --- /dev/null +++ b/backend/personal_website/users/tests/test_models.py @@ -0,0 +1,9 @@ +import pytest + +from personal_website.users.models import User + +pytestmark = pytest.mark.django_db + + +def test_user_get_absolute_url(user: User): + assert user.get_absolute_url() == f"/users/{user.username}/" diff --git a/backend/personal_website/users/tests/test_urls.py b/backend/personal_website/users/tests/test_urls.py new file mode 100644 index 0000000..8fe9b59 --- /dev/null +++ b/backend/personal_website/users/tests/test_urls.py @@ -0,0 +1,24 @@ +import pytest +from django.urls import resolve, reverse + +from personal_website.users.models import User + +pytestmark = pytest.mark.django_db + + +def test_detail(user: User): + assert ( + reverse("users:detail", kwargs={"username": user.username}) + == f"/users/{user.username}/" + ) + assert resolve(f"/users/{user.username}/").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/backend/personal_website/users/tests/test_views.py b/backend/personal_website/users/tests/test_views.py new file mode 100644 index 0000000..ac018c2 --- /dev/null +++ b/backend/personal_website/users/tests/test_views.py @@ -0,0 +1,79 @@ +import pytest +from django.contrib.auth.models import AnonymousUser +from django.http.response import Http404 +from django.test import RequestFactory + +from personal_website.users.models import User +from personal_website.users.tests.factories import UserFactory +from personal_website.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 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.username}/" + + 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 + + +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.username}/" + + +class TestUserDetailView: + def test_authenticated(self, user: User, rf: RequestFactory): + request = rf.get("/fake-url/") + request.user = UserFactory() + + response = user_detail_view(request, username=user.username) + + 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, username=user.username) + + assert response.status_code == 302 + assert response.url == "/accounts/login/?next=/fake-url/" + + def test_case_sensitivity(self, rf: RequestFactory): + request = rf.get("/fake-url/") + request.user = UserFactory(username="UserName") + + with pytest.raises(Http404): + user_detail_view(request, username="username") diff --git a/backend/personal_website/users/urls.py b/backend/personal_website/users/urls.py new file mode 100644 index 0000000..7da21a3 --- /dev/null +++ b/backend/personal_website/users/urls.py @@ -0,0 +1,14 @@ +from django.urls import path + +from personal_website.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/backend/personal_website/users/views.py b/backend/personal_website/users/views.py new file mode 100644 index 0000000..520b1e5 --- /dev/null +++ b/backend/personal_website/users/views.py @@ -0,0 +1,50 @@ +from django.contrib import messages +from django.contrib.auth import get_user_model +from django.contrib.auth.mixins import LoginRequiredMixin +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 = "username" + slug_url_kwarg = "username" + + +user_detail_view = UserDetailView.as_view() + + +class UserUpdateView(LoginRequiredMixin, UpdateView): + + model = User + fields = ["name"] + + def get_success_url(self): + return reverse("users:detail", kwargs={"username": self.request.user.username}) + + def get_object(self): + return User.objects.get(username=self.request.user.username) + + def form_valid(self, form): + messages.add_message( + self.request, messages.INFO, _("Infos successfully updated") + ) + return super().form_valid(form) + + +user_update_view = UserUpdateView.as_view() + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + + permanent = False + + def get_redirect_url(self): + return reverse("users:detail", kwargs={"username": self.request.user.username}) + + +user_redirect_view = UserRedirectView.as_view() diff --git a/backend/personal_website/utils/__init__.py b/backend/personal_website/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/personal_website/utils/context_processors.py b/backend/personal_website/utils/context_processors.py new file mode 100644 index 0000000..3c53514 --- /dev/null +++ b/backend/personal_website/utils/context_processors.py @@ -0,0 +1,8 @@ +from django.conf import settings + + +def settings_context(_request): + """Settings available by default to the templates context.""" + # Note: we intentionally do NOT expose the entire settings + # to prevent accidental leaking of sensitive information + return {"DEBUG": settings.DEBUG} diff --git a/backend/pytest.ini b/backend/pytest.ini new file mode 100644 index 0000000..c2b3a23 --- /dev/null +++ b/backend/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +addopts = --ds=config.settings.test --reuse-db +python_files = tests.py test_*.py diff --git a/backend/requirements/base.txt b/backend/requirements/base.txt new file mode 100644 index 0000000..687bf41 --- /dev/null +++ b/backend/requirements/base.txt @@ -0,0 +1,19 @@ +pytz==2020.4 # https://github.com/stub42/pytz +python-slugify==4.0.1 # https://github.com/un33k/python-slugify +Pillow==8.0.1 # https://github.com/python-pillow/Pillow +argon2-cffi==20.1.0 # https://github.com/hynek/argon2_cffi +whitenoise==5.2.0 # https://github.com/evansd/whitenoise +redis==3.5.3 # https://github.com/andymccurdy/redis-py +hiredis==1.1.0 # https://github.com/redis/hiredis-py + +# Django +# ------------------------------------------------------------------------------ +django==3.0.11 # pyup: < 3.1 # https://www.djangoproject.com/ +django-environ==0.4.5 # https://github.com/joke2k/django-environ +django-model-utils==4.1.1 # https://github.com/jazzband/django-model-utils +django-allauth==0.44.0 # https://github.com/pennersr/django-allauth +django-crispy-forms==1.10.0 # https://github.com/django-crispy-forms/django-crispy-forms +django-redis==4.12.1 # https://github.com/jazzband/django-redis +# Django REST Framework +djangorestframework==3.12.2 # https://github.com/encode/django-rest-framework +django-cors-headers==3.5.0 # https://github.com/adamchainz/django-cors-headers diff --git a/backend/requirements/local.txt b/backend/requirements/local.txt new file mode 100644 index 0000000..60032a1 --- /dev/null +++ b/backend/requirements/local.txt @@ -0,0 +1,35 @@ +-r base.txt + +Werkzeug==1.0.1 # https://github.com/pallets/werkzeug +ipdb==0.13.4 # https://github.com/gotcha/ipdb +psycopg2==2.8.6 # https://github.com/psycopg/psycopg2 + +# Testing +# ------------------------------------------------------------------------------ +mypy==0.790 # https://github.com/python/mypy +django-stubs==1.7.0 # https://github.com/typeddjango/django-stubs +pytest==6.1.2 # https://github.com/pytest-dev/pytest +pytest-sugar==0.9.4 # https://github.com/Frozenball/pytest-sugar + +# Documentation +# ------------------------------------------------------------------------------ +sphinx==3.3.1 # https://github.com/sphinx-doc/sphinx +sphinx-autobuild==2020.9.1 # https://github.com/GaretJax/sphinx-autobuild + +# Code quality +# ------------------------------------------------------------------------------ +flake8==3.8.4 # https://github.com/PyCQA/flake8 +flake8-isort==4.0.0 # https://github.com/gforcada/flake8-isort +coverage==5.3 # https://github.com/nedbat/coveragepy +black==20.8b1 # https://github.com/ambv/black +pylint-django==2.3.0 # https://github.com/PyCQA/pylint-django +pre-commit==2.9.2 # https://github.com/pre-commit/pre-commit + +# Django +# ------------------------------------------------------------------------------ +factory-boy==3.1.0 # https://github.com/FactoryBoy/factory_boy + +django-debug-toolbar==3.2 # https://github.com/jazzband/django-debug-toolbar +django-extensions==3.1.0 # https://github.com/django-extensions/django-extensions +django-coverage-plugin==1.8.0 # https://github.com/nedbat/django_coverage_plugin +pytest-django==4.1.0 # https://github.com/pytest-dev/pytest-django diff --git a/backend/requirements/production.txt b/backend/requirements/production.txt new file mode 100644 index 0000000..35f219b --- /dev/null +++ b/backend/requirements/production.txt @@ -0,0 +1,10 @@ +# PRECAUTION: avoid production dependencies that aren't in development + +-r base.txt + +gunicorn==20.0.4 # https://github.com/benoitc/gunicorn +psycopg2==2.8.6 # https://github.com/psycopg/psycopg2 + +# Django +# ------------------------------------------------------------------------------ +django-anymail==8.1 # https://github.com/anymail/django-anymail diff --git a/backend/setup.cfg b/backend/setup.cfg new file mode 100644 index 0000000..a7e8ce3 --- /dev/null +++ b/backend/setup.cfg @@ -0,0 +1,29 @@ +[flake8] +max-line-length = 120 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules,venv + +[pycodestyle] +max-line-length = 120 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules,venv + +[mypy] +python_version = 3.8 +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.plugins.django-stubs] +django_settings_module = config.settings.test + +[mypy-*.migrations.*] +# Django migrations should not produce any errors: +ignore_errors = True + +[coverage:run] +include = personal_website/* +omit = *migrations*, *tests* +plugins = + django_coverage_plugin diff --git a/frontend/package.json b/frontend/package.json index 591aa0d..508307b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -15,6 +15,7 @@ "core-js": "3.7.0", "moment": "2.29.1", "vue": "2.6.12", + "vue-gtag": "^1.10.0", "vue-router": "3.4.9", "vue-scrollto": "2.20.0" }, diff --git a/frontend/src/main.js b/frontend/src/main.js index 3dd311c..6edb6dc 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,6 +1,7 @@ import AOS from 'aos'; import 'aos/dist/aos.css'; import Vue from 'vue'; +import VueGtag from 'vue-gtag'; import '../node_modules/bulma/css/bulma.css'; import App from './App.vue'; import router from './router'; @@ -12,6 +13,16 @@ Vue.use(VueScrollTo, { duration: 1200 }); +Vue.use( + VueGtag, + { + config: { + id: process.env.VUE_APP_GOOGLE_ANALYTICS_UA + } + }, + router +); + new Vue({ created() { AOS.init({ diff --git a/frontend/yarn.lock b/frontend/yarn.lock index 30a57c3..00794fb 100644 --- a/frontend/yarn.lock +++ b/frontend/yarn.lock @@ -8816,6 +8816,11 @@ vue-eslint-parser@^7.1.1: esquery "^1.0.1" lodash "^4.17.15" +vue-gtag@^1.10.0: + version "1.10.0" + resolved "https://registry.yarnpkg.com/vue-gtag/-/vue-gtag-1.10.0.tgz#787d62eb4f1135dfa2997b465f1b11e5cf8fb0c9" + integrity sha512-pGbe6m/12a2DHftnWQOHBmkS+a3kPAZNU6ouP426mF/MPc/43DcHCEySUtB3MeJCPuXaUQQgGsRosIZWPdl/MQ== + vue-hot-reload-api@^2.3.0: version "2.3.4" resolved "https://registry.yarnpkg.com/vue-hot-reload-api/-/vue-hot-reload-api-2.3.4.tgz#532955cc1eb208a3d990b3a9f9a70574657e08f2"