diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..5518e60a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.editorconfig +.gitattributes +.github +.gitignore +.gitlab-ci.yml +.idea +.pre-commit-config.yaml +.readthedocs.yml +.travis.yml +venv diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..26140706 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.{html,css,scss,json,yml}] +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/.envs/.local/.django b/.envs/.local/.django new file mode 100644 index 00000000..247287be --- /dev/null +++ b/.envs/.local/.django @@ -0,0 +1,14 @@ +# General +# ------------------------------------------------------------------------------ +USE_DOCKER=yes +IPYTHONDIR=/app/.ipython +# Redis +# ------------------------------------------------------------------------------ +REDIS_URL=redis://redis:6379/0 + +# Celery +# ------------------------------------------------------------------------------ + +# Flower +CELERY_FLOWER_USER=debug +CELERY_FLOWER_PASSWORD=debug diff --git a/.envs/.local/.postgres b/.envs/.local/.postgres new file mode 100644 index 00000000..305d7d31 --- /dev/null +++ b/.envs/.local/.postgres @@ -0,0 +1,7 @@ +# PostgreSQL +# ------------------------------------------------------------------------------ +POSTGRES_HOST=postgres +POSTGRES_PORT=5432 +POSTGRES_DB=memberships +POSTGRES_USER=debug +POSTGRES_PASSWORD=debug diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..176a458f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..8e8ac866 --- /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/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..2ac85751 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: CI + +# Enable Buildkit and let compose use it to speed up image building +env: + DOCKER_BUILDKIT: 1 + COMPOSE_DOCKER_CLI_BUILD: 1 + +on: + pull_request: + branches: [ "master", "main" ] + paths-ignore: [ "docs/**" ] + + push: + branches: [ "master", "main" ] + paths-ignore: [ "docs/**" ] + + +jobs: + linter: + runs-on: ubuntu-latest + steps: + + - name: Checkout Code Repository + uses: actions/checkout@v2 + + - name: Set up Python 3.9 + uses: actions/setup-python@v2 + with: + python-version: 3.9 + + # Run all pre-commit hooks on all the files. + # Getting only staged files can be tricky in case a new PR is opened + # since the action is run on a branch in detached head state + - name: Install and Run Pre-commit + uses: pre-commit/action@v2.0.0 + + # With no caching at all the entire ci process takes 4m 30s to complete! + pytest: + runs-on: ubuntu-latest + + steps: + + - name: Checkout Code Repository + uses: actions/checkout@v2 + + - name: Build the Stack + run: docker-compose -f local.yml build + + - name: Run DB Migrations + run: docker-compose -f local.yml run --rm django python manage.py migrate + + - name: Run Django Tests + run: docker-compose -f local.yml run django pytest + + - name: Tear down the Stack + run: docker-compose -f local.yml down diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..83be1654 --- /dev/null +++ b/.gitignore @@ -0,0 +1,282 @@ +### 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 + +# celery beat schedule file +celerybeat-schedule + +# Environments +.venv +venv/ +ENV/ + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +### Node template +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + + +### Linux template +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + + +### VisualStudioCode template +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + + + + + +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### macOS template +# General +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### SublimeText template +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + + +### Vim template +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] + +# Session +Session.vim + +# Temporary +.netrwhist + +# Auto-generated tag files +tags + +### Project template + +memberships/media/ + +.pytest_cache/ + + +.ipython/ +.env +.envs/* +!.envs/.local/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..6f1bdcbc --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,35 @@ +exclude: 'docs|node_modules|migrations|.git|.tox' +default_stages: [commit] +fail_fast: true + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.0.1 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + + - repo: https://github.com/psf/black + rev: 21.9b0 + hooks: + - id: black + + - repo: https://github.com/timothycrosley/isort + rev: 5.9.3 + hooks: + - id: isort + + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.9.2 + hooks: + - id: flake8 + args: ['--config=setup.cfg'] + additional_dependencies: [flake8-isort] + + +# sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date +ci: + autoupdate_schedule: weekly + skip: [] + submodules: false diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 00000000..55509fe9 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,14 @@ +[MASTER] +load-plugins=pylint_django, pylint_celery +django-settings-module=config.settings.base +[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/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..32c49825 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python.pythonPath": "venv/bin/python", + "python.formatting.provider": "black" +} \ No newline at end of file diff --git a/README.rst b/README.rst new file mode 100644 index 00000000..5d489212 --- /dev/null +++ b/README.rst @@ -0,0 +1,110 @@ +Memberships +=========== + +Behold My Awesome Project! + +.. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg?logo=cookiecutter + :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 + +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 memberships + +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 + +Celery +^^^^^^ + +This app comes with Celery. + +To run a celery worker: + +.. code-block:: bash + + cd memberships + celery -A config.celery_app worker -l info + +Please note: For Celery's import magic to work, it is important *where* the celery commands are run. If you are in the same folder with *manage.py*, you should be right. + +Email Server +^^^^^^^^^^^^ + +In development, it is often nice to be able to see emails that are being sent from your application. For that reason local SMTP server `MailHog`_ with a web interface is available as docker container. + +Container mailhog will start automatically when you will run all docker containers. +Please check `cookiecutter-django Docker documentation`_ for more details how to start all containers. + +With MailHog running, to view messages that are sent by your application, open your browser and go to ``http://127.0.0.1:8025`` + +.. _mailhog: https://github.com/mailhog/MailHog + +Sentry +^^^^^^ + +Sentry is an error logging aggregator service. You can sign up for a free account at https://sentry.io/signup/?code=cookiecutter or download and host it yourself. +The system is setup with reasonable defaults, including 404 logging and integration with the WSGI application. + +You must set the DSN url in production. + +Deployment +---------- + +The following details how to deploy this application. + +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/compose/local/django/Dockerfile b/compose/local/django/Dockerfile new file mode 100644 index 00000000..51168992 --- /dev/null +++ b/compose/local/django/Dockerfile @@ -0,0 +1,70 @@ +ARG PYTHON_VERSION=3.10-slim-buster + +# define an alias for the specfic python version used in this file. +FROM python:${PYTHON_VERSION} as python + +# Python build stage +FROM python as python-build-stage + +ARG BUILD_ENVIRONMENT=local + +# Install apt packages +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements . + +# Create Python Dependency and Sub-Dependency Wheels. +RUN pip wheel --wheel-dir /usr/src/app/wheels \ + -r ${BUILD_ENVIRONMENT}.txt + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT=local +ARG APP_HOME=/app + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 +ENV BUILD_ENV ${BUILD_ENVIRONMENT} + +WORKDIR ${APP_HOME} + +# Install required system dependencies +RUN apt-get update && apt-get install --no-install-recommends -y \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # image processing + libmagic-dev \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels/ + +# use wheels to install python dependencies +RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ + && rm -rf /wheels/ + +COPY ./compose/production/django/entrypoint /entrypoint +RUN sed -i 's/\r$//g' /entrypoint +RUN chmod +x /entrypoint + +COPY ./compose/local/django/start /start +RUN sed -i 's/\r$//g' /start +RUN chmod +x /start + + +# copy application code to WORKDIR +COPY . ${APP_HOME} + +ENTRYPOINT ["/entrypoint"] diff --git a/compose/local/django/start b/compose/local/django/start new file mode 100644 index 00000000..3f0e8e0e --- /dev/null +++ b/compose/local/django/start @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python manage.py migrate +# uvicorn config.asgi:application --host 0.0.0.0 --reload +python manage.py runserver 0.0.0.0:8000 diff --git a/compose/production/aws/Dockerfile b/compose/production/aws/Dockerfile new file mode 100644 index 00000000..8282047b --- /dev/null +++ b/compose/production/aws/Dockerfile @@ -0,0 +1,9 @@ +FROM garland/aws-cli-docker:1.15.47 + +COPY ./compose/production/aws/maintenance /usr/local/bin/maintenance +COPY ./compose/production/postgres/maintenance/_sourced /usr/local/bin/maintenance/_sourced + +RUN chmod +x /usr/local/bin/maintenance/* + +RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ + && rmdir /usr/local/bin/maintenance diff --git a/compose/production/aws/maintenance/download b/compose/production/aws/maintenance/download new file mode 100644 index 00000000..0c515935 --- /dev/null +++ b/compose/production/aws/maintenance/download @@ -0,0 +1,23 @@ +#!/bin/sh + +### Download a file from your Amazon S3 bucket to the postgres /backups folder +### +### Usage: +### $ docker-compose -f production.yml run --rm awscli <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" + +export AWS_ACCESS_KEY_ID="${DJANGO_AWS_ACCESS_KEY_ID}" +export AWS_SECRET_ACCESS_KEY="${DJANGO_AWS_SECRET_ACCESS_KEY}" +export AWS_STORAGE_BUCKET_NAME="${DJANGO_AWS_STORAGE_BUCKET_NAME}" + + +aws s3 cp s3://${AWS_STORAGE_BUCKET_NAME}${BACKUP_DIR_PATH}/${1} ${BACKUP_DIR_PATH}/${1} + +message_success "Finished downloading ${1}." diff --git a/compose/production/aws/maintenance/upload b/compose/production/aws/maintenance/upload new file mode 100644 index 00000000..9446b930 --- /dev/null +++ b/compose/production/aws/maintenance/upload @@ -0,0 +1,29 @@ +#!/bin/sh + +### Upload the /backups folder to Amazon S3 +### +### Usage: +### $ docker-compose -f production.yml run --rm awscli upload + +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" + +export AWS_ACCESS_KEY_ID="${DJANGO_AWS_ACCESS_KEY_ID}" +export AWS_SECRET_ACCESS_KEY="${DJANGO_AWS_SECRET_ACCESS_KEY}" +export AWS_STORAGE_BUCKET_NAME="${DJANGO_AWS_STORAGE_BUCKET_NAME}" + + +message_info "Upload the backups directory to S3 bucket {$AWS_STORAGE_BUCKET_NAME}" + +aws s3 cp ${BACKUP_DIR_PATH} s3://${AWS_STORAGE_BUCKET_NAME}${BACKUP_DIR_PATH} --recursive + +message_info "Cleaning the directory ${BACKUP_DIR_PATH}" + +rm -rf ${BACKUP_DIR_PATH}/* + +message_success "Finished uploading and cleaning." diff --git a/compose/production/django/Dockerfile b/compose/production/django/Dockerfile new file mode 100644 index 00000000..5ce28899 --- /dev/null +++ b/compose/production/django/Dockerfile @@ -0,0 +1,82 @@ +ARG PYTHON_VERSION=3.10-slim-buster + + + +# define an alias for the specfic python version used in this file. +FROM python:${PYTHON_VERSION} as python + +# Python build stage +FROM python as python-build-stage + +ARG BUILD_ENVIRONMENT=production + +# Install apt packages +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements . + +# Create Python Dependency and Sub-Dependency Wheels. +RUN pip wheel --wheel-dir /usr/src/app/wheels \ + -r ${BUILD_ENVIRONMENT}.txt + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT=production +ARG APP_HOME=/app + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 +ENV BUILD_ENV ${BUILD_ENVIRONMENT} + +WORKDIR ${APP_HOME} + +RUN addgroup --system django \ + && adduser --system --ingroup django django + + +# Install required system dependencies +RUN apt-get update && apt-get install --no-install-recommends -y \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # image processing + libmagic-dev \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels/ + +# use wheels to install python dependencies +RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ + && rm -rf /wheels/ + + +COPY --chown=django:django ./compose/production/django/entrypoint /entrypoint +RUN sed -i 's/\r$//g' /entrypoint +RUN chmod +x /entrypoint + + +COPY --chown=django:django ./compose/production/django/start /start +RUN sed -i 's/\r$//g' /start +RUN chmod +x /start + +# copy application code to WORKDIR +COPY --chown=django:django . ${APP_HOME} + +# make django owner of the WORKDIR directory as well. +RUN chown django:django ${APP_HOME} + +USER django + +ENTRYPOINT ["/entrypoint"] diff --git a/compose/production/django/entrypoint b/compose/production/django/entrypoint new file mode 100644 index 00000000..3a01683f --- /dev/null +++ b/compose/production/django/entrypoint @@ -0,0 +1,40 @@ +#!/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/compose/production/django/start b/compose/production/django/start new file mode 100644 index 00000000..cceb5f59 --- /dev/null +++ b/compose/production/django/start @@ -0,0 +1,12 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python /app/manage.py collectstatic --noinput + + +/usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn.workers.UvicornWorker + diff --git a/compose/production/postgres/Dockerfile b/compose/production/postgres/Dockerfile new file mode 100644 index 00000000..bac0be52 --- /dev/null +++ b/compose/production/postgres/Dockerfile @@ -0,0 +1,6 @@ +FROM postgres:13.2 + +COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance +RUN chmod +x /usr/local/bin/maintenance/* +RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ + && rmdir /usr/local/bin/maintenance diff --git a/compose/production/postgres/maintenance/_sourced/constants.sh b/compose/production/postgres/maintenance/_sourced/constants.sh new file mode 100644 index 00000000..6ca4f0ca --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/constants.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + + +BACKUP_DIR_PATH='/backups' +BACKUP_FILE_PREFIX='backup' diff --git a/compose/production/postgres/maintenance/_sourced/countdown.sh b/compose/production/postgres/maintenance/_sourced/countdown.sh new file mode 100644 index 00000000..e6cbfb6f --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/countdown.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + + +countdown() { + declare desc="A simple countdown. Source: https://superuser.com/a/611582" + local seconds="${1}" + local d=$(($(date +%s) + "${seconds}")) + while [ "$d" -ge `date +%s` ]; do + echo -ne "$(date -u --date @$(($d - `date +%s`)) +%H:%M:%S)\r"; + sleep 0.1 + done +} diff --git a/compose/production/postgres/maintenance/_sourced/messages.sh b/compose/production/postgres/maintenance/_sourced/messages.sh new file mode 100644 index 00000000..f6be756e --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/messages.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + + +message_newline() { + echo +} + +message_debug() +{ + echo -e "DEBUG: ${@}" +} + +message_welcome() +{ + echo -e "\e[1m${@}\e[0m" +} + +message_warning() +{ + echo -e "\e[33mWARNING\e[0m: ${@}" +} + +message_error() +{ + echo -e "\e[31mERROR\e[0m: ${@}" +} + +message_info() +{ + echo -e "\e[37mINFO\e[0m: ${@}" +} + +message_suggestion() +{ + echo -e "\e[33mSUGGESTION\e[0m: ${@}" +} + +message_success() +{ + echo -e "\e[32mSUCCESS\e[0m: ${@}" +} diff --git a/compose/production/postgres/maintenance/_sourced/yes_no.sh b/compose/production/postgres/maintenance/_sourced/yes_no.sh new file mode 100644 index 00000000..fd9cae16 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/yes_no.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + + +yes_no() { + declare desc="Prompt for confirmation. \$\"\{1\}\": confirmation message." + local arg1="${1}" + + local response= + read -r -p "${arg1} (y/[n])? " response + if [[ "${response}" =~ ^[Yy]$ ]] + then + exit 0 + else + exit 1 + fi +} diff --git a/compose/production/postgres/maintenance/backup b/compose/production/postgres/maintenance/backup new file mode 100644 index 00000000..ee0c9d63 --- /dev/null +++ b/compose/production/postgres/maintenance/backup @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + + +### Create a database backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backup + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "Backing up the '${POSTGRES_DB}' database..." + + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Backing up as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +backup_filename="${BACKUP_FILE_PREFIX}_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz" +pg_dump | gzip > "${BACKUP_DIR_PATH}/${backup_filename}" + + +message_success "'${POSTGRES_DB}' database backup '${backup_filename}' has been created and placed in '${BACKUP_DIR_PATH}'." diff --git a/compose/production/postgres/maintenance/backups b/compose/production/postgres/maintenance/backups new file mode 100644 index 00000000..0484ccff --- /dev/null +++ b/compose/production/postgres/maintenance/backups @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + + +### View backups. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backups + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "These are the backups you have got:" + +ls -lht "${BACKUP_DIR_PATH}" diff --git a/compose/production/postgres/maintenance/restore b/compose/production/postgres/maintenance/restore new file mode 100644 index 00000000..9661ca7f --- /dev/null +++ b/compose/production/postgres/maintenance/restore @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + + +### Restore database from a backup. +### +### Parameters: +### <1> filename of an existing backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres restore <1> + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +if [[ -z ${1+x} ]]; then + message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again." + exit 1 +fi +backup_filename="${BACKUP_DIR_PATH}/${1}" +if [[ ! -f "${backup_filename}" ]]; then + message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again." + exit 1 +fi + +message_welcome "Restoring the '${POSTGRES_DB}' database from the '${backup_filename}' backup..." + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Restoring as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +message_info "Dropping the database..." +dropdb "${PGDATABASE}" + +message_info "Creating a new database..." +createdb --owner="${POSTGRES_USER}" + +message_info "Applying the backup to the new database..." +gunzip -c "${backup_filename}" | psql "${POSTGRES_DB}" + +message_success "The '${POSTGRES_DB}' database has been restored from the '${backup_filename}' backup." diff --git a/compose/production/traefik/Dockerfile b/compose/production/traefik/Dockerfile new file mode 100644 index 00000000..aa879052 --- /dev/null +++ b/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/compose/production/traefik/traefik.yml b/compose/production/traefik/traefik.yml new file mode 100644 index 00000000..96e53a64 --- /dev/null +++ b/compose/production/traefik/traefik.yml @@ -0,0 +1,75 @@ +log: + level: INFO + +entryPoints: + web: + # http + address: ":80" + http: + # https://docs.traefik.io/routing/entrypoints/#entrypoint + redirections: + entryPoint: + to: web-secure + + web-secure: + # https + address: ":443" + + flower: + address: ":5555" + +certificatesResolvers: + letsencrypt: + # https://docs.traefik.io/master/https/acme/#lets-encrypt + acme: + email: "vikas@example.com" + storage: /etc/traefik/acme/acme.json + # https://docs.traefik.io/master/https/acme/#httpchallenge + httpChallenge: + entryPoint: web + +http: + routers: + web-secure-router: + rule: "Host(`example.com`) || Host(`www.example.com`)" + entryPoints: + - web-secure + middlewares: + - csrf + service: django + tls: + # https://docs.traefik.io/master/routing/routers/#certresolver + certResolver: letsencrypt + + flower-secure-router: + rule: "Host(`example.com`)" + entryPoints: + - flower + service: flower + tls: + # https://docs.traefik.io/master/routing/routers/#certresolver + certResolver: letsencrypt + + middlewares: + csrf: + # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders + # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax + headers: + hostsProxyHeaders: ["X-CSRFToken"] + + services: + django: + loadBalancer: + servers: + - url: http://django:5000 + + flower: + loadBalancer: + servers: + - url: http://flower:5555 + +providers: + # https://docs.traefik.io/master/providers/file/ + file: + filename: /etc/traefik/traefik.yml + watch: true diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/config/api_router.py b/config/api_router.py new file mode 100644 index 00000000..09f8529a --- /dev/null +++ b/config/api_router.py @@ -0,0 +1,63 @@ +from django.conf import settings +from django.urls.conf import include, path +from rest_framework.routers import DefaultRouter, SimpleRouter +from memberships.donations.api.views import DonationViewSet +from memberships.payments.api.views import PaymentViewSet, PayoutViewSet +from memberships.posts.api.views import PostViewSet + +from memberships.users.api.views import OwnUserAPIView, UserViewSet +from memberships.subscriptions.api.views import ( + SubscriberViewSet, + SubscriptionViewSet, + TierViewSet, +) + +from dj_rest_auth.views import ( + LoginView, + LogoutView, + PasswordChangeView, + PasswordResetConfirmView, + PasswordResetView, +) +from dj_rest_auth.registration.views import ( + RegisterView, + VerifyEmailView, + ResendEmailVerificationView, +) + +from drf_spectacular.views import SpectacularSwaggerView, SpectacularAPIView + + +router = SimpleRouter() +router.register("users", UserViewSet, basename="users") +router.register("tiers", TierViewSet, basename="tiers") +router.register("posts", PostViewSet, basename="posts") +router.register("subscriptions", SubscriptionViewSet, basename="subscriptions") +router.register("subscribers", SubscriberViewSet, basename="subscribers") +router.register("donations", DonationViewSet, basename="donations") +router.register("payments", PaymentViewSet, basename="payments") +router.register("payouts", PayoutViewSet, basename="payouts") + +auth_patterns = [ + path("register/", RegisterView.as_view(), name="register"), + path("verify_email/", VerifyEmailView.as_view(), name="verify_email"), + path("resend_email/", ResendEmailVerificationView.as_view(), name="resend_email"), + path("login/", LoginView.as_view(), name="login"), + path("logout/", LogoutView.as_view(), name="logout"), + path("password/change/", PasswordChangeView.as_view(), name="password_change"), + path("password/reset/", PasswordResetView.as_view(), name="password_reset"), + path( + "password/reset/confirm/", + PasswordResetConfirmView.as_view(), + name="password_reset_confirm", + ), +] + +app_name = "api" +urlpatterns = router.urls + [ + path("me/", OwnUserAPIView.as_view(), name="me"), + path("auth/", include(auth_patterns)), + # docs + path("", SpectacularSwaggerView.as_view(url_name="api:schema"), name="docs"), + path("schema/", SpectacularAPIView.as_view(), name="schema"), +] diff --git a/config/asgi.py b/config/asgi.py new file mode 100644 index 00000000..fcb3f024 --- /dev/null +++ b/config/asgi.py @@ -0,0 +1,40 @@ +""" +ASGI config for Memberships project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/dev/howto/deployment/asgi/ + +""" +import os +import sys +from pathlib import Path + +from django.core.asgi import get_asgi_application + +# This allows easy placement of apps within the interior +# memberships directory. +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent +sys.path.append(str(ROOT_DIR / "memberships")) + +# If DJANGO_SETTINGS_MODULE is unset, default to the local settings +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") + +# This application object is used by any ASGI server configured to use this file. +django_application = get_asgi_application() +# Apply ASGI middleware here. +# from helloworld.asgi import HelloWorldApplication +# application = HelloWorldApplication(application) + +# Import websocket application here, so apps from django_application are loaded first +from config.websocket import websocket_application # noqa isort:skip + + +async def application(scope, receive, send): + if scope["type"] == "http": + await django_application(scope, receive, send) + elif scope["type"] == "websocket": + await websocket_application(scope, receive, send) + else: + raise NotImplementedError(f"Unknown scope type {scope['type']}") diff --git a/config/settings/__init__.py b/config/settings/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/config/settings/base.py b/config/settings/base.py new file mode 100644 index 00000000..bc2b0ae8 --- /dev/null +++ b/config/settings/base.py @@ -0,0 +1,347 @@ +""" +Base settings to build other settings files upon. +""" +from pathlib import Path + +import environ + +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent +# memberships/ +APPS_DIR = ROOT_DIR / "memberships" +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 = "Asia/Kolkata" +# 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 +DEFAULT_AUTO_FIELD = 'hashid_field.HashidAutoField' + +# 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", + "dj_rest_auth", + "corsheaders", + "drf_spectacular", + "djmoney", + "versatileimagefield", +] + +LOCAL_APPS = [ + "memberships.users.apps.UsersConfig", + "memberships.subscriptions.apps.SubscriptionsConfig", + "memberships.posts.apps.PostsConfig", + + "memberships.payments", + "memberships.donations", + "memberships.webhooks", + # 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": "memberships.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" + +# Mock token authentication +REST_AUTH_TOKEN_MODEL = "memberships.users.models.User" +REST_AUTH_TOKEN_CREATOR = "memberships.utils.authentication.create_auth_token" +REST_AUTH_SERIALIZERS = { + "TOKEN_SERIALIZER": "memberships.users.api.serializers.UserSerializer" +} + + +# 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", + "memberships.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 = [("""Vikas""", "vikas@example.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 = "optional" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_ADAPTER = "memberships.users.adapters.AccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +SOCIALACCOUNT_ADAPTER = "memberships.users.adapters.SocialAccountAdapter" + +# django-rest-framework +# ------------------------------------------------------------------------------- +# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/ +REST_FRAMEWORK = { + "DEFAULT_RENDERER_CLASSES": [ + "rest_framework.renderers.JSONRenderer", + ], + "DEFAULT_PARSER_CLASSES": [ + "rest_framework.parsers.JSONParser", + ], + "DEFAULT_AUTHENTICATION_CLASSES": ( + "rest_framework.authentication.SessionAuthentication", + ), + "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", + "PAGE_SIZE": 100, + "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", + "EXCEPTION_HANDLER": "memberships.utils.exception_handlers.handle_drf_exception", +} + +SPECTACULAR_SETTINGS = { + "TITLE": "Memberships API", + "DESCRIPTION": "", + "VERSION": "1.0.0", + "SERVE_INCLUDE_SCHEMA": False, + "SCHEMA_PATH_PREFIX": "/api", + "COMPONENT_SPLIT_REQUEST": True, + # OTHER SETTINGS +} + + +# money - https://github.com/django-money/django-money +CURRENCIES = ('INR', ) +from moneyed import INR +DEFAULT_CURRENCY = INR + +# payments +RAZORPAY_KEY = "FANMO_SECRET_CHANGE_ME" +RAZORPAY_SECRET = "FANMO_SECRET_CHANGE_ME" + + +# business logic +DEFAULT_PLATFORM_FEE_PERCENT = 5.00 + + +# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup +CORS_URLS_REGEX = r"^/api/.*$" + +# django-versatileimagefield - https://github.com/respondcreate/django-versatileimagefield +VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = { + 'user_avatar': [ + ('full', 'url'), + ], + 'user_cover': [ + ('full', 'url'), + ], + 'tier_cover': [ + ('full', 'url'), + ], +} diff --git a/config/settings/local.py b/config/settings/local.py new file mode 100644 index 00000000..cd1b6e1a --- /dev/null +++ b/config/settings/local.py @@ -0,0 +1,81 @@ +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="dtRvZY5MprTYDIAf5S5IGtnjfVhPbaUJxRe362k34CQ8qR7umLD8ySrgfYm2pASR", +) +HASHID_FIELD_SALT = env( + "HASHID_FIELD_SALT", + default="946$pk^z&2ow-k2=sal&)f@p-0t0!_nz_js7*$xn$osnd3vids" +) +# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"] + +# CACHES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#caches +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "", + } +} + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-host +EMAIL_HOST = env("EMAIL_HOST", default="mailhog") +# https://docs.djangoproject.com/en/dev/ref/settings/#email-port +EMAIL_PORT = 1025 + +# WhiteNoise +# ------------------------------------------------------------------------------ +# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development +INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS # noqa F405 + + +# django-debug-toolbar +# ------------------------------------------------------------------------------ +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites +INSTALLED_APPS += ["debug_toolbar"] # noqa F405 +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware +MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405 +# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config +DEBUG_TOOLBAR_CONFIG = { + "DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"], + "SHOW_TEMPLATE_CONTEXT": True, +} +# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips +INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"] +if env("USE_DOCKER") == "yes": + import socket + + hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) + INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips] + +# django-extensions +# ------------------------------------------------------------------------------ +# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration +INSTALLED_APPS += ["django_extensions"] # noqa F405 + +# django-rest-framework +# ------------------------------------------------------------------------------- +# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/ +REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] = ( + "rest_framework.authentication.SessionAuthentication", + "memberships.utils.authentication.UsernameAuthentication", +) + +# Celery +# ------------------------------------------------------------------------------ + +# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-eager-propagates +CELERY_TASK_EAGER_PROPAGATES = True +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/production.py b/config/settings/production.py new file mode 100644 index 00000000..41e69956 --- /dev/null +++ b/config/settings/production.py @@ -0,0 +1,204 @@ +import logging + +import sentry_sdk +from sentry_sdk.integrations.django import DjangoIntegration +from sentry_sdk.integrations.logging import LoggingIntegration +from sentry_sdk.integrations.celery import CeleryIntegration + +from sentry_sdk.integrations.redis import RedisIntegration + +from .base import * # noqa +from .base import env + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +SECRET_KEY = env("DJANGO_SECRET_KEY") +HASHID_FIELD_SALT = env("HASHID_FIELD_SALT") + +# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["example.com"]) + +# 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 +) + +# STORAGES +# ------------------------------------------------------------------------------ +# https://django-storages.readthedocs.io/en/latest/#installation +INSTALLED_APPS += ["storages"] # noqa F405 +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_QUERYSTRING_AUTH = False +# DO NOT change these unless you know what you're doing. +_AWS_EXPIRY = 60 * 60 * 24 * 7 +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_S3_OBJECT_PARAMETERS = { + "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" +} +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings +AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) +# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#cloudfront +AWS_S3_CUSTOM_DOMAIN = env("DJANGO_AWS_S3_CUSTOM_DOMAIN", default=None) +aws_s3_domain = AWS_S3_CUSTOM_DOMAIN or f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" +# STATIC +# ------------------------ +STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" +# MEDIA +# ------------------------------------------------------------------------------ +DEFAULT_FILE_STORAGE = "memberships.utils.storages.MediaRootS3Boto3Storage" +MEDIA_URL = f"https://{aws_s3_domain}/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="Memberships " +) +# 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="[Memberships]", +) + +# 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/amazon_ses/ +EMAIL_BACKEND = "anymail.backends.amazon_ses.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. + +LOGGING = { + "version": 1, + "disable_existing_loggers": True, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s " + "%(process)d %(thread)d %(message)s" + } + }, + "handlers": { + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + } + }, + "root": {"level": "INFO", "handlers": ["console"]}, + "loggers": { + "django.db.backends": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + # Errors logged by the SDK itself + "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, + "django.security.DisallowedHost": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + }, +} + +# Sentry +# ------------------------------------------------------------------------------ +SENTRY_DSN = env("SENTRY_DSN") +SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) + +sentry_logging = LoggingIntegration( + level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs + event_level=logging.ERROR, # Send errors as events +) +integrations = [ + sentry_logging, + DjangoIntegration(), + CeleryIntegration(), + RedisIntegration(), +] +sentry_sdk.init( + dsn=SENTRY_DSN, + integrations=integrations, + environment=env("SENTRY_ENVIRONMENT", default="production"), + traces_sample_rate=env.float("SENTRY_TRACES_SAMPLE_RATE", default=0.0), +) + +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/test.py b/config/settings/test.py new file mode 100644 index 00000000..1ea0077c --- /dev/null +++ b/config/settings/test.py @@ -0,0 +1,45 @@ +""" +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="uS4NKyRtwJqaYs3MHacspJIhiuYdnoQOghOUoUOv0bZh42kBnVC0xsKUa9AYOL0Z", +) +HASHID_FIELD_SALT = env( + "HASHID_FIELD_SALT", + default="e^h6=azhukkwxqz&%d4vvq7o2_2w_&=o$rt4vx)zdx-d9pf&66" +) +# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner +TEST_RUNNER = "django.test.runner.DiscoverRunner" + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] + +# 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/config/urls.py b/config/urls.py new file mode 100644 index 00000000..075cc4f8 --- /dev/null +++ b/config/urls.py @@ -0,0 +1,57 @@ +from django.conf import settings +from django.conf.urls.static import static +from django.contrib import admin +from django.contrib.staticfiles.urls import staticfiles_urlpatterns +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("memberships.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) + +if settings.DEBUG: + # Static file serving when using Gunicorn + Uvicorn for local web socket development + urlpatterns += staticfiles_urlpatterns() + +# API URLS +urlpatterns += [ + # API base url + path("api/", include("config.api_router")), +] + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + path( + "400/", + default_views.bad_request, + kwargs={"exception": Exception("Bad Request!")}, + ), + path( + "403/", + default_views.permission_denied, + kwargs={"exception": Exception("Permission Denied")}, + ), + path( + "404/", + default_views.page_not_found, + kwargs={"exception": Exception("Page not Found")}, + ), + path("500/", default_views.server_error), + ] + if "debug_toolbar" in settings.INSTALLED_APPS: + import debug_toolbar + + urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns diff --git a/config/websocket.py b/config/websocket.py new file mode 100644 index 00000000..81adfbc6 --- /dev/null +++ b/config/websocket.py @@ -0,0 +1,13 @@ +async def websocket_application(scope, receive, send): + while True: + event = await receive() + + if event["type"] == "websocket.connect": + await send({"type": "websocket.accept"}) + + if event["type"] == "websocket.disconnect": + break + + if event["type"] == "websocket.receive": + if event["text"] == "ping": + await send({"type": "websocket.send", "text": "pong!"}) diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 00000000..e0f9534a --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,38 @@ +""" +WSGI config for Memberships 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 +# memberships directory. +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent +sys.path.append(str(ROOT_DIR / "memberships")) +# 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/local.yml b/local.yml new file mode 100644 index 00000000..18a2a127 --- /dev/null +++ b/local.yml @@ -0,0 +1,46 @@ +version: '3' + +volumes: + local_postgres_data: {} + local_postgres_data_backups: {} + +services: + django: &django + build: + context: . + dockerfile: ./compose/local/django/Dockerfile + image: memberships_local_django + container_name: memberships_django + depends_on: + - postgres + - mailhog + volumes: + - .:/app:z + env_file: + - ./.envs/.local/.django + - ./.envs/.local/.postgres + ports: + - "8801:8000" + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: memberships_production_postgres + container_name: memberships_postgres + volumes: + - local_postgres_data:/var/lib/postgresql/data:Z + - local_postgres_data_backups:/backups:z + env_file: + - ./.envs/.local/.postgres + + mailhog: + image: mailhog/mailhog:v1.0.0 + container_name: memberships_mailhog + ports: + - "8025:8025" + + redis: + image: redis:6 + container_name: memberships_redis diff --git a/manage.py b/manage.py new file mode 100755 index 00000000..bf34d7ac --- /dev/null +++ b/manage.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +import os +import sys +from pathlib import Path + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") + + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django # noqa + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + + raise + + # This allows easy placement of apps within the interior + # memberships directory. + current_path = Path(__file__).parent.resolve() + sys.path.append(str(current_path / "memberships")) + + execute_from_command_line(sys.argv) diff --git a/memberships/__init__.py b/memberships/__init__.py new file mode 100644 index 00000000..e1d86152 --- /dev/null +++ b/memberships/__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/memberships/conftest.py b/memberships/conftest.py new file mode 100644 index 00000000..576e0193 --- /dev/null +++ b/memberships/conftest.py @@ -0,0 +1,14 @@ +import pytest + +from memberships.users.models import User +from memberships.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/memberships/contrib/__init__.py b/memberships/contrib/__init__.py new file mode 100644 index 00000000..1c7ecc89 --- /dev/null +++ b/memberships/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/memberships/contrib/sites/__init__.py b/memberships/contrib/sites/__init__.py new file mode 100644 index 00000000..1c7ecc89 --- /dev/null +++ b/memberships/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/memberships/contrib/sites/migrations/0001_initial.py b/memberships/contrib/sites/migrations/0001_initial.py new file mode 100644 index 00000000..304cd6d7 --- /dev/null +++ b/memberships/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/memberships/contrib/sites/migrations/0002_alter_domain_unique.py b/memberships/contrib/sites/migrations/0002_alter_domain_unique.py new file mode 100644 index 00000000..2c8d6dac --- /dev/null +++ b/memberships/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/memberships/contrib/sites/migrations/0003_set_site_domain_and_name.py b/memberships/contrib/sites/migrations/0003_set_site_domain_and_name.py new file mode 100644 index 00000000..43249a30 --- /dev/null +++ b/memberships/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": "example.com", + "name": "Memberships", + }, + ) + + +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/memberships/contrib/sites/migrations/0004_alter_options_ordering_domain.py b/memberships/contrib/sites/migrations/0004_alter_options_ordering_domain.py new file mode 100644 index 00000000..f7118ca8 --- /dev/null +++ b/memberships/contrib/sites/migrations/0004_alter_options_ordering_domain.py @@ -0,0 +1,21 @@ +# Generated by Django 3.1.7 on 2021-02-04 14:49 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ("sites", "0003_set_site_domain_and_name"), + ] + + operations = [ + migrations.AlterModelOptions( + name="site", + options={ + "ordering": ["domain"], + "verbose_name": "site", + "verbose_name_plural": "sites", + }, + ), + ] diff --git a/memberships/contrib/sites/migrations/__init__.py b/memberships/contrib/sites/migrations/__init__.py new file mode 100644 index 00000000..1c7ecc89 --- /dev/null +++ b/memberships/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/memberships/core/__init__.py b/memberships/core/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/core/migrations/__init__.py b/memberships/core/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/core/models.py b/memberships/core/models.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/donations/__init__.py b/memberships/donations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/donations/api/__init__.py b/memberships/donations/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/donations/api/serializers.py b/memberships/donations/api/serializers.py new file mode 100644 index 00000000..a8b099ea --- /dev/null +++ b/memberships/donations/api/serializers.py @@ -0,0 +1,97 @@ +from django.conf import settings + +from djmoney.contrib.django_rest_framework.fields import MoneyField +from hashid_field.rest import HashidSerializerCharField +from rest_framework import serializers + +from memberships.donations.models import Donation +from memberships.users.api.serializers import UserPreviewSerializer +from memberships.users.models import User + + +class DonationPaymentSerializer(serializers.ModelSerializer): + key = serializers.SerializerMethodField() + order_id = serializers.CharField(source="external_id") + name = serializers.CharField(source="payment_plan.name") + prefill = serializers.SerializerMethodField() + notes = serializers.SerializerMethodField() + + class Meta: + model = Donation + fields = ["key", "order_id", "name", "prefill", "notes"] + + def get_key(self, _): + return settings.RAZORPAY_KEY + + def get_prefill(self, _): + sender = self.context["request"].user + if sender.is_authenticated: + return {"name": sender.display_name, "email": sender.email} + return dict() + + def get_notes(self, donation): + return {"external_id": donation.id} + + +class DonationCreateSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + username = serializers.SlugRelatedField( + slug_field="username", + queryset=User.objects.filter(is_active=True), + source="receiver", + write_only=True, + ) + payment_processor = serializers.CharField(read_only=True, default="razorpay") + payment_payload = DonationPaymentSerializer(source="*", read_only=True) + + class Meta: + model = Donation + fields = [ + "id", + "username", + "amount", + "name", + "message", + "is_anonymous", + "payment_processor", + "payment_payload", + ] + + def validate(self, attrs): + receiver = attrs["receiver"] + if not receiver.can_accept_payments(): + raise serializers.ValidationError( + f"{receiver.name} is currently not accepting payments.", + "cannot_accept_payments", + ) + + min_amount = receiver.user_preferences.minimum_amount + if min_amount > attrs["amount"]: + raise serializers.ValidationError( + f"Amount cannot be lower than {min_amount.amount}", + "min_payment_account", + ) + return attrs + + def create(self, validated_data): + validated_data["buyer"] = self.context["request"].user + donation = super().create(validated_data) + donation.create_external() + return donation + + +class DonationSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + receiver = UserPreviewSerializer() + + class Meta: + model = Donation + fields = [ + "id", + "receiver", + "name", + "message", + "is_anonymous", + "status", + "created_at", + ] diff --git a/memberships/donations/api/views.py b/memberships/donations/api/views.py new file mode 100644 index 00000000..aff6aa15 --- /dev/null +++ b/memberships/donations/api/views.py @@ -0,0 +1,16 @@ +from rest_framework import viewsets, mixins + +from memberships.donations.api.serializers import ( + DonationCreateSerializer, + DonationSerializer, +) + +# protect this view +class DonationViewSet(mixins.CreateModelMixin, viewsets.ReadOnlyModelViewSet): + def get_queryset(self): + return self.request.user.donations.all() + + def get_serializer_class(self): + if self.action == "create": + return DonationCreateSerializer + return DonationSerializer diff --git a/memberships/donations/migrations/__init__.py b/memberships/donations/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/donations/models.py b/memberships/donations/models.py new file mode 100644 index 00000000..94f9e2a4 --- /dev/null +++ b/memberships/donations/models.py @@ -0,0 +1,41 @@ +from django.db import models +from django_extensions.db.fields import RandomCharField +from djmoney.models.fields import MoneyField + +from model_utils import Choices + +from django_fsm import FSMField, transition +from razorpay.errors import SignatureVerificationError +from memberships.utils.models import BaseModel +from utils import razorpay_client + + +class Donation(BaseModel): + class Status(models.TextChoices): + PENDING = "pending" + FAILED = "failed" + COMPLETED = "completed" + + sender = models.ForeignKey("users.User", on_delete=models.SET_NULL, null=True) + receiver = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="received_donations" + ) + + name = models.CharField(max_length=30, blank=True) + message = models.TextField(blank=True) + is_anonymous = models.BooleanField(default=False) + + status = FSMField(default=Status.PENDING, choices=Status.choices) + + amount = MoneyField(max_digits=7, decimal_places=2) + external_id = models.CharField(max_length=12) + + def create_external(self): + external_data = razorpay_client.orders.create( + { + "amount": self.amount.get_amount_in_subunit(), + "currency": self.amount.currency.code, + } + ) + self.external_id = external_data["id"] + self.save() diff --git a/memberships/payments/__init__.py b/memberships/payments/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/payments/api/serializers.py b/memberships/payments/api/serializers.py new file mode 100644 index 00000000..41e8aba2 --- /dev/null +++ b/memberships/payments/api/serializers.py @@ -0,0 +1,96 @@ +from hashid_field.rest import HashidSerializerCharField +from rest_framework import serializers +from memberships.donations.api.serializers import DonationSerializer + +from memberships.payments.models import Payment, Payout +from memberships.subscriptions.api.serializers import SubscriptionSerializer +from memberships.users.api.serializers import UserPreviewSerializer + + +class RazorpayResponseSerializer(serializers.Serializer): + razorpay_order_id = serializers.CharField(required=False) + razorpay_subscription_id = serializers.CharField(required=False) + razorpay_payment_id = serializers.CharField() + razorpay_signature = serializers.CharField() + + def validate(self, attrs): + if "razorpay_order_id" in attrs and "razorpay_subscription_id" in attrs: + raise serializers.ValidationError("Invalid payment response.") + return super().validate(attrs) + + +class PaymentProcessingSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + processor = serializers.ChoiceField( + choices=["razorpay"], default="razorpay", write_only=True + ) + type = serializers.ChoiceField(choices=["donation", "subscription"]) + payload = RazorpayResponseSerializer(write_only=True) + + seller = UserPreviewSerializer(read_only=True) + donation = DonationSerializer(read_only=True) + subscription = SubscriptionSerializer(read_only=True) + + class Meta: + model = Payment + fields = [ + "id", + "amount", + "seller", + "subscription", + "donation", + "created_at", + "processor", + "type", + "payload", + ] + read_only_fields = [ + "id", + "seller", + "amount", + "subscription", + "donation", + "created_at", + ] + + def create(self, validated_data): + if validated_data["type"] == "donation": + return Payment.capture_donation(validated_data["payload"]) + return Payment.capture_subscription(validated_data["payload"]) + + +class PaymentSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + seller = UserPreviewSerializer() + donation = DonationSerializer() + subscription = SubscriptionSerializer() + + class Meta: + model = Payment + fields = [ + "id", + "type", + "amount", + "seller", + "subscription", + "donation", + "created_at", + ] + + +class PaymentPreviewSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + buyer = UserPreviewSerializer() + + class Meta: + model = Payment + fields = ["id", "amount", "type", "buyer", "created_at"] + + +class PayoutSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + payment = PaymentPreviewSerializer() + + class Meta: + model = Payout + fields = ["id", "amount", "status", "payment", "created_at"] diff --git a/memberships/payments/api/views.py b/memberships/payments/api/views.py new file mode 100644 index 00000000..49223c8c --- /dev/null +++ b/memberships/payments/api/views.py @@ -0,0 +1,28 @@ +from rest_framework import mixins, viewsets +from rest_framework.decorators import action +from memberships.payments.api.serializers import ( + PaymentProcessingSerializer, + PaymentSerializer, + PayoutSerializer, +) +from memberships.payments.models import Payment + + +class PaymentViewSet(mixins.CreateModelMixin, viewsets.ReadOnlyModelViewSet): + serializer_class = PaymentSerializer + + def get_queryset(self): + # include recently failed? + return self.request.user.payments.filter(status=Payment.Status.CAPTURED) + + def get_serializer_class(self): + if self.action == "create": + return PaymentProcessingSerializer + return super().get_serializer_class() + + +class PayoutViewSet(viewsets.ReadOnlyModelViewSet): + serializer_class = PayoutSerializer + + def get_queryset(self): + return self.request.user.payouts.all() diff --git a/memberships/payments/migrations/__init__.py b/memberships/payments/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/payments/models.py b/memberships/payments/models.py new file mode 100644 index 00000000..14ca26f7 --- /dev/null +++ b/memberships/payments/models.py @@ -0,0 +1,197 @@ +from decimal import Decimal +from django.conf import settings +from django.core.exceptions import SuspiciousFileOperation +from django.db import models +from django_extensions.db.fields import RandomCharField +from django_fsm import FSMField +from djmoney.models.fields import MoneyField +from memberships.donations.models import Donation +from memberships.subscriptions.models import Subscription + +from memberships.utils import razorpay_client +from memberships.utils.models import BaseModel +from memberships.utils.money import deduct_platform_fee, money_from_sub_unit + + +class Payment(BaseModel): + class Type(models.TextChoices): + DONATION = "donation" + SUBSCRIPTION = "subscription" + + class Status(models.TextChoices): + CREATED = "created" + AUTHORIZED = "authorized" + CAPTURED = "captured" + REFUNDED = "refunded" + FAILED = "failed" + + subscription = models.ForeignKey( + "subscriptions.Subscription", on_delete=models.CASCADE, null=True + ) + donation = models.ForeignKey( + "donations.Donation", on_delete=models.CASCADE, null=True + ) + + seller = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="received_payments" + ) + buyer = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True) + + status = FSMField(default=Status.CREATED, choices=Status.choices) + type = models.CharField(max_length=16, choices=Type.choices) + + amount = MoneyField(max_digits=7, decimal_places=2) + external_id = models.CharField(max_length=255) + + @classmethod + def from_razorpay_response(cls, payload): + pass + + @classmethod + def from_razorpay_webhook(cls, payload): + razorpay_client.utils.verify_payment_signature(payload) + pass + + @classmethod + def for_subscription(cls, subscription, payload): + payment, _ = Payment.objects.get_or_create( + type=Payment.Type.SUBSCRIPTION, + subscription=subscription, + status=Payment.Status.CAPTURED, + amount=money_from_sub_unit(payload["amount"], payload["currency"]), + external_id=payload["id"], + seller=subscription.seller, + buyer=subscription.buyer, + ) + Payout.for_payment(payment) + return payment + + @classmethod + def capture_subscription(cls, payload): + razorpay_client.utils.verify_subscription_payment_signature(payload) + + subscription = Subscription.objects.select_for_update().get( + external_id=payload["razorpay_subscription_id"] + ) + + payment, _created = Payment.objects.get_or_create( + type=Payment.Type.SUBSCRIPTION, + subscription=subscription, + amount=subscription.plan.amount, + external_id=payload["razorpay_payment_id"], + seller=subscription.seller, + buyer=subscription.buyer, + defaults={"status": Payment.Status.CAPTURED}, + ) + + # fetch subscription? + if _created: + subscription.activate() + subscription.save() + + # in background? + Payout.for_payment(payment) + return payment + + @classmethod + def capture_donation(cls, payload): + razorpay_client.utils.verify_payment_signature(payload) + + donation = Donation.objects.get(external_id=payload["razorpay_order_id"]) + + payment, _ = Payment.objects.get_or_create( + type=Payment.Type.DONATION, + donation=donation, + amount=donation.amount, + external_id=payload["razorpay_payment_id"], + seller=donation.seller, + buyer=donation.buyer, + ) + + razorpay_client.payments.capture( + payment.external_id, + payment.amount.get_amount_in_sub_unit(), + {"currency": payment.amount.currency.code}, + ) + + donation.state = Donation.STATE.completed + donation.save() + + # in background? + Payout.for_payment(payment) + return payment + + +class Payout(BaseModel): + class Status(models.TextChoices): + SCHEDULED = "scheduled" + PROCESSED = "processed" + + recipient = models.ForeignKey("users.User", on_delete=models.CASCADE) + payment = models.ForeignKey("payments.Payment", on_delete=models.CASCADE) + status = models.CharField( + max_length=16, choices=Status.choices, default=Status.SCHEDULED + ) + + amount = MoneyField(decimal_places=2, max_digits=7) + bank_account = models.ForeignKey("payments.BankAccount", on_delete=models.CASCADE) + + external_id = models.CharField(max_length=255) + + @classmethod + def for_payment(cls, payment): + payout = cls.objects.create( + recipient=payment.seller, + payment=payment, + amount=deduct_platform_fee(payment.amount, payment.seller), + ) + payout.create_external() + return payout + + def create_external(self): + external_data = razorpay_client.payment.transfer( + self.payment.external_id, + { + "transfers": [ + { + "account": self.recipient.bank_account.external_id, + "amount": self.amount.get_amount_in_sub_unit(), + "currency": self.amount.currency.code, + } + ], + }, + ) + self.external_id = external_data["id"] + self.save() + + +class BankAccount(BaseModel): + class AccountType(models.TextChoices): + PRIVATE_LIMITED = "Private Limited" + PARTNERSHIP = "Partnership" + PROPRIETORSHIP = "Proprietorship" + INDIVIDUAL = "Individual" + LLP = "LLP" + + class Status(models.TextChoices): + PROCESSING = "processing" + LINKED = "linked" + + user = models.ForeignKey("users.User", on_delete=models.CASCADE) + status = models.CharField( + max_length=16, choices=Status.choices, default=Status.PROCESSING + ) + + account_name = models.CharField(max_length=255) + mobile_number = models.CharField(max_length=10) + + account_number = models.CharField(max_length=255) + account_type = models.CharField( + max_length=32, choices=AccountType.choices, default=AccountType.INDIVIDUAL + ) + beneficiary_name = models.CharField(max_length=255) + ifsc = models.CharField(max_length=16) + + is_active = models.BooleanField(default=True) + + external_id = models.CharField(max_length=12) diff --git a/memberships/posts/__init__.py b/memberships/posts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/posts/api/serializers.py b/memberships/posts/api/serializers.py new file mode 100644 index 00000000..9bd1c904 --- /dev/null +++ b/memberships/posts/api/serializers.py @@ -0,0 +1,29 @@ +from hashid_field.rest import HashidSerializerCharField +from rest_framework import serializers + +from memberships.posts.models import Content, Post + + +class ContentSerializer(serializers.ModelSerializer): + class Meta: + model = Content + fields = ["type", "text", "image", "link", "link_og", "link_embed"] + + +class PostSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + content = ContentSerializer() + + class Meta: + model = Post + fields = [ + "id", + "title", + "slug", + "content", + "visibility", + "minimum_tier", + "is_published", + "created_at", + "updated_at", + ] diff --git a/memberships/posts/api/views.py b/memberships/posts/api/views.py new file mode 100644 index 00000000..d305282c --- /dev/null +++ b/memberships/posts/api/views.py @@ -0,0 +1,33 @@ +from rest_framework import viewsets + +from memberships.posts.api.serializers import PostSerializer +from memberships.posts.models import Post + + +class PostViewSet(viewsets.ModelViewSet): + serializer_class = PostSerializer + queryset = Post.objects.all() + + def get_queryset(self): + """ + who can see posts? + + public posts: + - everyone + + supportor-only posts (non mvp): + - authenticated user has donated to the author + - gets 30 days access from last donation + - qs.filter(author__supporters__sender=self.request.user) + - qs.filter(author__supporters__created_at=self.request.user) + + member-only posts (non mvp - covered by min-tier): + - authenticated user who has an active subscription with author + - qs.filter(author__subscriptions__subscriber=self.request.user) + + min-tier posts: + - authenticated user who is an active member of minimum tier amount + - qs.filter(author__subscribers=self.request.user) + - qs.filter(author__subscribers__plan__amount__gte=F('minimum_tier_level__amount')) + """ + return super().get_queryset() diff --git a/memberships/posts/apps.py b/memberships/posts/apps.py new file mode 100644 index 00000000..5f112af8 --- /dev/null +++ b/memberships/posts/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class PostsConfig(AppConfig): + name = "memberships.posts" + verbose_name = _("Posts") + + def ready(self): + try: + import memberships.posts.signals # noqa F401 + except ImportError: + pass diff --git a/memberships/posts/migrations/__init__.py b/memberships/posts/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/posts/models.py b/memberships/posts/models.py new file mode 100644 index 00000000..2931fa3a --- /dev/null +++ b/memberships/posts/models.py @@ -0,0 +1,49 @@ +from django.db import models +from versatileimagefield.fields import VersatileImageField + +from memberships.utils.models import BaseModel +from django_extensions.db.fields import AutoSlugField + + +class Post(BaseModel): + class Visiblity(models.TextChoices): + PUBLIC = "public" + ALL_MEMBERS = "all_members" + MINIMUM_TIER = "minimum_tier" + + title = models.CharField(max_length=255) + slug = AutoSlugField(populate_from="title", allow_duplicates=True) + content = models.OneToOneField("posts.Content", on_delete=models.CASCADE) + + author = models.ForeignKey("users.User", on_delete=models.CASCADE) + + visibility = models.CharField( + max_length=16, choices=Visiblity.choices, default=Visiblity.PUBLIC + ) + minimum_tier = models.ForeignKey( + "subscriptions.Tier", on_delete=models.SET_NULL, null=True + ) + + is_published = models.BooleanField(default=True) + + +class Content(BaseModel): + class Type(models.TextChoices): + TEXT = "text" + IMAGE = "image" + LINK = "link" + + type = models.CharField(max_length=16, choices=Type.choices) + text = models.TextField(blank=True) + image = VersatileImageField(upload_to="uploads/content/") + link = models.URLField() + link_og = models.JSONField() + link_embed = models.JSONField() + + +class Comment(BaseModel): + post = models.ForeignKey("posts.Post", on_delete=models.CASCADE) + body = models.TextField() + author = models.ForeignKey("users.User", on_delete=models.CASCADE) + + is_published = models.BooleanField(default=True) diff --git a/memberships/static/css/project.css b/memberships/static/css/project.css new file mode 100644 index 00000000..f1d543da --- /dev/null +++ b/memberships/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/memberships/static/fonts/.gitkeep b/memberships/static/fonts/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/memberships/static/images/favicons/favicon.ico b/memberships/static/images/favicons/favicon.ico new file mode 100644 index 00000000..e1c1dd1a Binary files /dev/null and b/memberships/static/images/favicons/favicon.ico differ diff --git a/memberships/static/js/project.js b/memberships/static/js/project.js new file mode 100644 index 00000000..d26d23b9 --- /dev/null +++ b/memberships/static/js/project.js @@ -0,0 +1 @@ +/* Project specific Javascript goes here. */ diff --git a/memberships/static/sass/custom_bootstrap_vars.scss b/memberships/static/sass/custom_bootstrap_vars.scss new file mode 100644 index 00000000..e69de29b diff --git a/memberships/static/sass/project.scss b/memberships/static/sass/project.scss new file mode 100644 index 00000000..3c8f2616 --- /dev/null +++ b/memberships/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/memberships/subscriptions/__init__.py b/memberships/subscriptions/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/subscriptions/admin.py b/memberships/subscriptions/admin.py new file mode 100644 index 00000000..3fd5a4ff --- /dev/null +++ b/memberships/subscriptions/admin.py @@ -0,0 +1,21 @@ +from django.contrib import admin + +from memberships.subscriptions.models import Plan, Tier + + +@admin.register(Tier) +class TierAdmin(admin.ModelAdmin): + list_display = ["name", "seller", "is_public", "created_at"] + + +@admin.register(Plan) +class PlanAdmin(admin.ModelAdmin): + list_display = [ + "name", + "amount", + "tier", + "seller", + "buyer", + "is_active", + "created_at", + ] diff --git a/memberships/subscriptions/api/serializers.py b/memberships/subscriptions/api/serializers.py new file mode 100644 index 00000000..5ceddc0e --- /dev/null +++ b/memberships/subscriptions/api/serializers.py @@ -0,0 +1,160 @@ +from django.conf import settings +from hashid_field.rest import HashidSerializerCharField +from memberships.subscriptions.models import Plan, Subscription, Tier +from memberships.users.api.serializers import UserPreviewSerializer +from memberships.users.models import User +from rest_framework import serializers +from djmoney.contrib.django_rest_framework import MoneyField + + +class TierSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + + class Meta: + model = Tier + fields = [ + "id", + "name", + "amount", + "description", + "cover", + "welcome_message", + "benefits", + "is_public", + ] + extra_kwargs = {"cover": {"required": False}} + + def create(self, validated_data): + user = self.context["request"].user + + payment_plan_data = { + "name": f"{validated_data['name']} ({validated_data['amount']}) - {user.display_name}", + "amount": validated_data["amount"], + "owner": user, + "created_by": user, + } + payment_plan = Plan.objects.create(**payment_plan_data) + + tier = super().create( + {**validated_data, "owner": user, "payment_plan": payment_plan} + ) + + payment_plan.tier = tier + payment_plan.create_external() + + return tier + + +class TierPreviewSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + + class Meta: + model = Tier + fields = ["id", "name", "amount"] + + +class SubscriptionSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + seller = UserPreviewSerializer() + amount = MoneyField(max_digits=7, decimal_places=2, source="plan.amount") + tier = TierPreviewSerializer(source="plan.tier") + + class Meta: + model = Subscription + fields = ["id", "seller", "amount", "tier", "status", "expires_at", "is_active"] + + +class SubscriberSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + buyer = UserPreviewSerializer() + amount = MoneyField(max_digits=7, decimal_places=2, source="plan.amount") + tier = TierPreviewSerializer(source="plan.tier") + + class Meta: + model = Subscription + fields = ["id", "buyer", "amount", "tier", "status", "expires_at", "is_active"] + + +class SubscriptionPaymentSerializer(serializers.ModelSerializer): + key = serializers.SerializerMethodField() + subscription_id = serializers.CharField(source="external_id") + name = serializers.CharField(source="plan.name") + prefill = serializers.SerializerMethodField() + notes = serializers.SerializerMethodField() + + class Meta: + model = Subscription + fields = ["key", "subscription_id", "name", "prefill", "notes"] + + def get_key(self, _): + return settings.RAZORPAY_KEY + + def get_prefill(self, _): + buyer = self.context["request"].user + return {"name": buyer.display_name, "email": buyer.email} + + def get_notes(self, subscription): + return {"external_id": subscription.id} + + +class SubscriptionCreateSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField(read_only=True) + username = serializers.SlugRelatedField( + slug_field="username", + queryset=User.objects.filter(is_active=True), + source="seller", + write_only=True, + ) + amount = MoneyField(max_digits=7, decimal_places=2, source="plan.amount") + + seller = UserPreviewSerializer(read_only=True) + tier = TierPreviewSerializer(source="plan.tier", read_only=True) + + payment_processor = serializers.CharField(read_only=True, default="razorpay") + payment_payload = SubscriptionPaymentSerializer(source="*", read_only=True) + + class Meta: + model = Subscription + fields = [ + "id", + "username", + "amount", + "seller", + "tier", + "payment_processor", + "payment_payload", + "expires_at", + ] + read_only_fields = [ + "seller", + "tier", + "payment_processor", + "payment_payload", + "expires_at", + ] + + def validate(self, attrs): + seller = attrs["seller"] + if not seller.can_accept_payments(): + raise serializers.ValidationError( + f"{seller.name} is currently not accepting payments.", + "cannot_accept_payments", + ) + + min_amount = seller.user_preferences.minimum_amount + if min_amount > attrs["amount"]: + raise serializers.ValidationError( + f"Amount cannot be lower than {min_amount.amount}", + "min_payment_account", + ) + return attrs + + def create(self, validated_data): + buyer = self.context["request"].user + payment_plan = Plan.for_subscription( + validated_data["plan"]["amount"], + validated_data["seller"], + buyer, + ) + subscription = payment_plan.subscribe(buyer) + return subscription diff --git a/memberships/subscriptions/api/views.py b/memberships/subscriptions/api/views.py new file mode 100644 index 00000000..8775aff8 --- /dev/null +++ b/memberships/subscriptions/api/views.py @@ -0,0 +1,64 @@ +from drf_spectacular.utils import extend_schema +from rest_framework import viewsets, permissions, mixins +from rest_framework.decorators import action +from memberships.subscriptions.api.serializers import ( + SubscriberSerializer, + SubscriptionCreateSerializer, + SubscriptionSerializer, + TierSerializer, +) + + +class TierViewSet( + mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.ReadOnlyModelViewSet +): + serializer_class = TierSerializer + permission_classes = [permissions.IsAuthenticated] + + def get_queryset(self): + return self.request.user.tiers.all() + + +class SubscriptionViewSet(mixins.CreateModelMixin, viewsets.ReadOnlyModelViewSet): + permission_classes = [permissions.IsAuthenticated] + + def get_queryset(self): + return self.request.user.subscriptions.all() + + def get_serializer_class(self): + if self.action == "create": + return SubscriptionCreateSerializer + return SubscriptionSerializer + + # do we need pause/resume? + @extend_schema(request=None) + @action(methods=["POST"], detail=True) + def pause(self, request, *args, **kwargs): + subscription = self.get_object() + subscription.pause() + subscription.save() + return self.retrieve(request, *args, **kwargs) + + @extend_schema(request=None) + @action(methods=["POST"], detail=True) + def resume(self, request, *args, **kwargs): + subscription = self.get_object() + subscription.resume() + subscription.save() + return self.retrieve(request, *args, **kwargs) + + @extend_schema(request=None) + @action(methods=["POST"], detail=True) + def cancel(self, request, *args, **kwargs): + subscription = self.get_object() + subscription.cancel() + subscription.save() + return self.retrieve(request, *args, **kwargs) + + +class SubscriberViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): + serializer_class = SubscriberSerializer + permission_classes = [permissions.IsAuthenticated] + + def get_queryset(self): + return self.request.user.subscribers.all() diff --git a/memberships/subscriptions/apps.py b/memberships/subscriptions/apps.py new file mode 100644 index 00000000..fb7fb9c7 --- /dev/null +++ b/memberships/subscriptions/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class SubscriptionsConfig(AppConfig): + name = "memberships.subscriptions" + verbose_name = _("Subcriptions") + + def ready(self): + try: + import memberships.subcriptions.signals # noqa F401 + except ImportError: + pass diff --git a/memberships/subscriptions/migrations/__init__.py b/memberships/subscriptions/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/subscriptions/models.py b/memberships/subscriptions/models.py new file mode 100644 index 00000000..56845d4c --- /dev/null +++ b/memberships/subscriptions/models.py @@ -0,0 +1,205 @@ +import copy +from dateutil.relativedelta import relativedelta + +from django.db import models +from django.contrib.postgres.fields import ArrayField + +from django.utils import timezone +from versatileimagefield.fields import VersatileImageField + +from memberships.utils import razorpay_client +from djmoney.models.fields import MoneyField + +from django_fsm import FSMField, transition + +from memberships.utils.models import BaseModel + + +class Tier(BaseModel): + name = models.CharField(max_length=255) + description = models.TextField(blank=True) + cover = VersatileImageField(upload_to="uploads/covers/", blank=True) + welcome_message = models.TextField(blank=True) + benefits = ArrayField(models.CharField(max_length=50), size=8) + + amount = MoneyField(max_digits=7, decimal_places=2) + + is_active = models.BooleanField(default=True) + is_public = models.BooleanField(default=True) + + seller = models.ForeignKey("users.User", on_delete=models.CASCADE) + + def __str__(self): + return self.name + + +class Plan(BaseModel): + name = models.CharField(max_length=255) + tier = models.ForeignKey("subscriptions.Tier", on_delete=models.CASCADE, null=True) + + # hardcode for now. + period = "monthly" + interval = 1 + + amount = MoneyField(max_digits=7, decimal_places=2) + external_id = models.CharField(max_length=255) + + seller = models.ForeignKey("users.User", on_delete=models.CASCADE) + buyer = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="created_plans" + ) + + is_active = models.BooleanField(default=True) + + def __str__(self): + return self.name + + @classmethod + def for_subscription(cls, amount, seller, buyer): + tier = ( + Tier.objects.filter(amount__lte=amount, seller=seller) + .order_by("-amount") + .first() + ) + + tier_name = tier.name if tier else "Custom" + default_name = f"{tier_name} ({amount}) - {seller.name}" + + # todo - cleanup orpahed plans? + plan, created = cls.objects.get_or_create( + amount=amount, + tier=tier, + seller=seller, + created_by=seller if tier else buyer, + defaults={"name": default_name}, + ) + if created: + plan.create_external() + + return plan + + def subscribe(self, subscriber): + subscription = Subscription.objects.create( + plan=self, + status=Subscription.Status.CREATED, + subscriber=subscriber, + expires_at=timezone.now() + relativedelta(month=1), + ) + subscription.create_external() + return subscription + + def create_external(self): + external_plan = razorpay_client.plan.create( + { + "period": self.period, + "interval": self.interval, + "item": { + "name": self.name, + "amount": self.amount.get_amount_in_sub_unit(), + "currency": self.amount.currency.code, + }, + "notes": {"external_id": self.id}, + } + ) + self.external_id = external_plan["id"] + self.save() + + +class Subscription(BaseModel): + class Status(models.TextChoices): + CREATED = "created" + AUTHENTICATED = "authenticated" + ACTIVE = "active" + PENDING = "pending" + HALTED = "halted" + CANCELLED = "cancelled" + PAUSED = "paused" + EXPIRED = "expired" + COMPLETED = "completed" + + plan = models.ForeignKey("subscriptions.Plan", on_delete=models.CASCADE) + status = FSMField(default=Status.CREATED) + external_id = models.CharField(max_length=255) + + is_active = models.BooleanField(default=False) + expires_at = models.DateTimeField() + + seller = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="subscribers" + ) + buyer = models.ForeignKey("users.User", on_delete=models.CASCADE) + + def create_external(self): + external_subscription = razorpay_client.subscription.create( + { + "plan_id": self.plan.external_id, + "total_count": 12, + "notes": {"external_id": self.id}, + } + ) + self.external_id = external_subscription["id"] + self.save() + + @transition( + field=status, + source=[Status.AUTHENTICATED, Status.PENDING, Status.HALTED], + target=Status.ACTIVE, + ) + def activate(self): + self.expires_at = relativedelta(timezone.now(), months=1) + + @transition(field=status, source=Status.ACTIVE, target=Status.PAUSED) + def pause(self): + razorpay_client.subscription.post_url( + f"{razorpay_client.subscription.base_url}/{self.external_id}/pause", + {"pause_at": "now"}, + ) + + @transition(field=status, source=Status.PAUSED, target=Status.ACTIVE) + def resume(self): + razorpay_client.subscription.post_url( + f"{razorpay_client.subscription.base_url}/{self.external_id}/resume", + {"resume_at": "now"}, + ) + + @transition(field=status, source="*", target=Status.CANCELLED) + def cancel(self): + razorpay_client.subscription.cancel(self.external_id) + + @transition(field=status, source=[Status.ACTIVE], target=Status.COMPLETED) + def update(self, plan, schedule_at_end=True): + razorpay_client.subscription.post_url( + f"{razorpay_client.subscription.base_url}/{self.external_id}/update", + { + "plan_id": plan.external_id, + "schedule_change_at": "cycle_end" if schedule_at_end else "now", + }, + ) + new_subscription = copy.deepcopy(self) + new_subscription.pk = None + new_subscription.plan = plan + new_subscription.status = self.Status.AUTHENTICATED + new_subscription.save() + return new_subscription + + @transition( + field=status, + source=[ + Status.ACTIVE, + ], + target=Status.PENDING, + ) + def start_renewal(self): + pass + + @transition( + field=status, source=[Status.PENDING, Status.ACTIVE], target=Status.ACTIVE + ) + def renew(self): + self.expires_at = relativedelta(timezone.now(), months=1) + + @transition( + field=status, source=[Status.PENDING, Status.ACTIVE], target=Status.HALTED + ) + def halt(self): + pass diff --git a/memberships/templates/403.html b/memberships/templates/403.html new file mode 100644 index 00000000..4356d932 --- /dev/null +++ b/memberships/templates/403.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Forbidden (403){% endblock %} + +{% block content %} +

Forbidden (403)

+ +

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

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

Page not found

+ +

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

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

Ooops!!! 500

+ +

Looks like something went wrong!

+ +

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

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

{% translate "Account Inactive" %}

+ +

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

+{% endblock %} diff --git a/memberships/templates/account/base.html b/memberships/templates/account/base.html new file mode 100644 index 00000000..8e1f260e --- /dev/null +++ b/memberships/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/memberships/templates/account/email.html b/memberships/templates/account/email.html new file mode 100644 index 00000000..cfd6e6c5 --- /dev/null +++ b/memberships/templates/account/email.html @@ -0,0 +1,81 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Account" %}{% endblock %} + +{% block inner %} +

{% translate "E-mail Addresses" %}

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

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

+ + + +{% else %} +

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

+ +{% endif %} + + +

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

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

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

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

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

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

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

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

{% translate "Sign In" %}

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

{% blocktranslate 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:{% endblocktranslate %}

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

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

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

{% translate "Sign Out" %}

+ +

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

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

{% translate "Change Password" %}

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

{% translate "Password Reset" %}

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

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

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

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

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

{% translate "Password Reset" %}

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

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

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

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

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

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

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

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

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

{% translate "Change Password" %}

+

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

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

{% translate "Set Password" %}

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

{% translate "Sign Up" %}

+ +

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

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

{% translate "Sign Up Closed" %}

+ +

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

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

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

+ +

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

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

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

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

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

+ +

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

+ +

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

+{% endblock %} diff --git a/memberships/templates/base.html b/memberships/templates/base.html new file mode 100644 index 00000000..d5ed7eb8 --- /dev/null +++ b/memberships/templates/base.html @@ -0,0 +1,106 @@ +{% load static i18n %} + + + + + {% block title %}Memberships{% endblock title %} + + + + + + + + + + {% block css %} + + + + + + + {% endblock %} + + {# Placed at the top of the document so pages load faster with defer #} + {% block javascript %} + + + + + + + + + + + {% endblock javascript %} + + + + + +
+ + +
+ +
+ + {% if messages %} + {% for message in messages %} +
{{ message }}
+ {% endfor %} + {% endif %} + + {% block content %} +

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

+ {% endblock content %} + +
+ + {% block modal %}{% endblock modal %} + + {% block inline_javascript %} + {# Script tags with only code, no src (defer by default) #} + {% endblock inline_javascript %} + + diff --git a/memberships/templates/pages/about.html b/memberships/templates/pages/about.html new file mode 100644 index 00000000..94d9808c --- /dev/null +++ b/memberships/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/memberships/templates/pages/home.html b/memberships/templates/pages/home.html new file mode 100644 index 00000000..94d9808c --- /dev/null +++ b/memberships/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/memberships/templates/users/user_detail.html b/memberships/templates/users/user_detail.html new file mode 100644 index 00000000..79b8233e --- /dev/null +++ b/memberships/templates/users/user_detail.html @@ -0,0 +1,34 @@ +{% 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/memberships/templates/users/user_form.html b/memberships/templates/users/user_form.html new file mode 100644 index 00000000..467357ad --- /dev/null +++ b/memberships/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/memberships/users/__init__.py b/memberships/users/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/users/adapters.py b/memberships/users/adapters.py new file mode 100644 index 00000000..0d206fae --- /dev/null +++ b/memberships/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/memberships/users/admin.py b/memberships/users/admin.py new file mode 100644 index 00000000..63ddfb56 --- /dev/null +++ b/memberships/users/admin.py @@ -0,0 +1,34 @@ +from django.contrib import admin +from django.contrib.auth import admin as auth_admin +from django.contrib.auth import get_user_model +from django.utils.translation import gettext_lazy as _ + +from memberships.users.forms import UserChangeForm, UserCreationForm + +User = get_user_model() + + +@admin.register(User) +class UserAdmin(auth_admin.UserAdmin): + + form = UserChangeForm + add_form = UserCreationForm + fieldsets = ( + (None, {"fields": ("username", "password")}), + (_("Personal info"), {"fields": ("name", "email")}), + ( + _("Permissions"), + { + "fields": ( + "is_active", + "is_staff", + "is_superuser", + "groups", + "user_permissions", + ), + }, + ), + (_("Important dates"), {"fields": ("last_login", "date_joined")}), + ) + list_display = ["username", "name", "is_superuser"] + search_fields = ["name"] diff --git a/memberships/users/api/serializers.py b/memberships/users/api/serializers.py new file mode 100644 index 00000000..d86bd66a --- /dev/null +++ b/memberships/users/api/serializers.py @@ -0,0 +1,82 @@ +from djmoney.contrib.django_rest_framework.fields import MoneyField +from rest_framework import serializers + +from memberships.subscriptions.models import Tier +from memberships.users.models import SocialLink, User, UserPreference + +from versatileimagefield.serializers import VersatileImageFieldSerializer + +from hashid_field.rest import HashidSerializerCharField + + +class UserTierSerializer(serializers.ModelSerializer): + id = HashidSerializerCharField() + amount = MoneyField(max_digits=7, decimal_places=2, source="payment_plan.amount") + + class Meta: + model = Tier + fields = ["id", "name", "description", "amount", "cover", "benefits"] + + +class SocialLinkSerializer(serializers.ModelSerializer): + class Meta: + model = SocialLink + fields = [ + "website_url", + "youtube_url", + "facebook_url", + "instagram_url", + "twitter_url", + ] + + +class UserPreferenceSerializer(serializers.ModelSerializer): + class Meta: + model = UserPreference + fields = ["is_accepting_payments", "minimum_amount"] + + +class UserSerializer(serializers.ModelSerializer): + tiers = UserTierSerializer(many=True, read_only=True, source="public_tiers") + social_links = SocialLinkSerializer() + user_preferences = UserPreferenceSerializer() + avatar = VersatileImageFieldSerializer("user_avatar") + cover = VersatileImageFieldSerializer("user_cover") + + class Meta: + model = User + fields = [ + "username", + "name", + "about", + "avatar", + "cover", + "tiers", + "social_links", + "user_preferences", + "follower_count", + "subscriber_count", + ] + read_only_fields = ["tiers", "follower_count", "subscriber_count"] + + def update(self, instance, validated_data): + user_preferences = validated_data.pop("user_preferences", {}) + social_links = validated_data.pop("social_links", {}) + + for field_name, value in user_preferences.items(): + setattr(instance.user_preferences, field_name, value) + instance.user_preferences.save() + + for field_name, value in social_links.items(): + setattr(instance.social_links, field_name, value) + instance.social_links.save() + + return super().update(instance, validated_data) + + +class UserPreviewSerializer(serializers.ModelSerializer): + avatar = VersatileImageFieldSerializer("user_avatar") + + class Meta: + model = User + fields = ["username", "name", "avatar"] diff --git a/memberships/users/api/views.py b/memberships/users/api/views.py new file mode 100644 index 00000000..99417d41 --- /dev/null +++ b/memberships/users/api/views.py @@ -0,0 +1,54 @@ +from rest_framework.decorators import action +from rest_framework.generics import GenericAPIView +from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin +from rest_framework.viewsets import GenericViewSet + +from memberships.users.models import User + +from .serializers import UserSerializer + +from drf_spectacular.utils import extend_schema + + +class UserViewSet(RetrieveModelMixin, GenericViewSet): + serializer_class = UserSerializer + queryset = User.objects.all() + lookup_field = "username" + + def get_queryset(self): + return super().get_queryset() + + @extend_schema(request=None) + @action(detail=True, methods=["POST"]) + def follow(self, request, *args, **kwargs): + user = self.get_object() + self.request.user.follow(user) + return self.detail(request, *args, **kwargs) + + @extend_schema(request=None) + @action(detail=True, methods=["POST"]) + def unfollow(self, request, *args, **kwargs): + user = self.get_object() + self.request.user.unfollow(user) + return self.detail(request, *args, **kwargs) + + @action(detail=True, methods=["GET"]) + def followers(self, request, *args, **kwargs): + pass + + @action(detail=True, methods=["GET"]) + def followings(self, request, *args, **kwargs): + pass + + +class OwnUserAPIView(RetrieveModelMixin, UpdateModelMixin, GenericAPIView): + serializer_class = UserSerializer + + def get_object(self): + return self.request.user + + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + def patch(self, request, *args, **kwargs): + return self.partial_update(request, *args, **kwargs) diff --git a/memberships/users/apps.py b/memberships/users/apps.py new file mode 100644 index 00000000..7f7fee7a --- /dev/null +++ b/memberships/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class UsersConfig(AppConfig): + name = "memberships.users" + verbose_name = _("Users") + + def ready(self): + try: + import memberships.users.signals # noqa F401 + except ImportError: + pass diff --git a/memberships/users/forms.py b/memberships/users/forms.py new file mode 100644 index 00000000..80cd97ae --- /dev/null +++ b/memberships/users/forms.py @@ -0,0 +1,19 @@ +from django.contrib.auth import forms as admin_forms +from django.contrib.auth import get_user_model +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): + class Meta(admin_forms.UserCreationForm.Meta): + model = User + + error_messages = { + "username": {"unique": _("This username has already been taken.")} + } diff --git a/memberships/users/migrations/0001_initial.py b/memberships/users/migrations/0001_initial.py new file mode 100644 index 00000000..ef2c2d94 --- /dev/null +++ b/memberships/users/migrations/0001_initial.py @@ -0,0 +1,120 @@ +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", + ), + ), + ( + "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/memberships/users/migrations/__init__.py b/memberships/users/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/users/models.py b/memberships/users/models.py new file mode 100644 index 00000000..200595f4 --- /dev/null +++ b/memberships/users/models.py @@ -0,0 +1,99 @@ +from django.conf import settings +from django.contrib.auth.models import AbstractUser +from django.db import models +from django.db.models import CharField +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from djmoney.models.fields import MoneyField + +from memberships.utils.models import BaseModel +from versatileimagefield.fields import VersatileImageField + + +class User(AbstractUser, BaseModel): + """Default user for Memberships.""" + + # First and last name do not cover name patterns around the globe + name = CharField(_("Name of User"), blank=True, max_length=255) + first_name = None + last_name = None + + avatar = VersatileImageField(upload_to="profiles/avatars/", blank=True) + cover = VersatileImageField(upload_to="profiles/covers/", blank=True) + about = models.TextField(blank=True) + + # followers and subscriber count? + subscriber_count = models.PositiveSmallIntegerField(default=0) + follower_count = models.PositiveSmallIntegerField(default=0) + + def get_absolute_url(self): + return reverse("users:detail", kwargs={"username": self.username}) + + def public_tiers(self): + return self.tiers.filter(is_public=True) + + def display_name(self): + return self.name or self.username + + def can_accept_payments(self): + return ( + self.bank_account.status == UserPreference.Status.LINKED + and self.user_preferences.is_accepting_payments + ) + + def will_accept(self, amount): + return ( + self.can_accept_payments() + and self.user_preferences.minimum_amount <= amount + ) + + def follow(self, user): + _, created = Following.objects.get_or_create(from_user=self, to_user=user) + if created: + self.follower_count = self.followers.count() + self.save() + + def unfollow(self, user): + following = Following.objects.filter(from_user=user, to_user=self).first() + if following is not None: + following.delete() + user.follower_count = user.followers.count() + user.save() + + +class SocialLink(models.Model): + user = models.OneToOneField( + "users.User", on_delete=models.CASCADE, related_name="social_links" + ) + + website_url = models.URLField(blank=True) + youtube_url = models.URLField(blank=True) + facebook_url = models.URLField(blank=True) + instagram_url = models.URLField(blank=True) + twitter_url = models.URLField(blank=True) + + +class Following(BaseModel): + from_user = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="followers" + ) + to_user = models.ForeignKey( + "users.User", on_delete=models.CASCADE, related_name="followings" + ) + + class Meta: + constraints = [ + models.UniqueConstraint(fields=["from_user", "to_user"], name="following") + ] + unique_together = ("from_user", "to_user") + + +class UserPreference(BaseModel): + user = models.OneToOneField("users.User", on_delete=models.CASCADE) + + is_accepting_payments = models.BooleanField(default=True) + minimum_amount = MoneyField(max_digits=7, decimal_places=2) + + platform_fee_percent = models.DecimalField( + decimal_places=2, max_digits=3, default=settings.DEFAULT_PLATFORM_FEE_PERCENT + ) diff --git a/memberships/users/tests/__init__.py b/memberships/users/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/users/tests/factories.py b/memberships/users/tests/factories.py new file mode 100644 index 00000000..edd306cb --- /dev/null +++ b/memberships/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, + ).evaluate(None, None, extra={"locale": None}) + ) + self.set_password(password) + + class Meta: + model = get_user_model() + django_get_or_create = ["username"] diff --git a/memberships/users/tests/test_admin.py b/memberships/users/tests/test_admin.py new file mode 100644 index 00000000..afcceff3 --- /dev/null +++ b/memberships/users/tests/test_admin.py @@ -0,0 +1,40 @@ +import pytest +from django.urls import reverse + +from memberships.users.models import User + +pytestmark = pytest.mark.django_db + + +class TestUserAdmin: + def test_changelist(self, admin_client): + url = reverse("admin:users_user_changelist") + response = admin_client.get(url) + assert response.status_code == 200 + + def test_search(self, admin_client): + url = reverse("admin:users_user_changelist") + response = admin_client.get(url, data={"q": "test"}) + assert response.status_code == 200 + + def test_add(self, admin_client): + url = reverse("admin:users_user_add") + response = admin_client.get(url) + assert response.status_code == 200 + + response = admin_client.post( + url, + data={ + "username": "test", + "password1": "My_R@ndom-P@ssw0rd", + "password2": "My_R@ndom-P@ssw0rd", + }, + ) + assert response.status_code == 302 + assert User.objects.filter(username="test").exists() + + def test_view_user(self, admin_client): + user = User.objects.get(username="admin") + url = reverse("admin:users_user_change", kwargs={"object_id": user.pk}) + response = admin_client.get(url) + assert response.status_code == 200 diff --git a/memberships/users/tests/test_drf_urls.py b/memberships/users/tests/test_drf_urls.py new file mode 100644 index 00000000..6f949b72 --- /dev/null +++ b/memberships/users/tests/test_drf_urls.py @@ -0,0 +1,24 @@ +import pytest +from django.urls import resolve, reverse + +from memberships.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/memberships/users/tests/test_drf_views.py b/memberships/users/tests/test_drf_views.py new file mode 100644 index 00000000..a18b2b5a --- /dev/null +++ b/memberships/users/tests/test_drf_views.py @@ -0,0 +1,33 @@ +import pytest +from django.test import RequestFactory + +from memberships.users.api.views import UserViewSet +from memberships.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, + "name": user.name, + "url": f"http://testserver/api/users/{user.username}/", + } diff --git a/memberships/users/tests/test_forms.py b/memberships/users/tests/test_forms.py new file mode 100644 index 00000000..3df34b58 --- /dev/null +++ b/memberships/users/tests/test_forms.py @@ -0,0 +1,39 @@ +""" +Module for all Form Tests. +""" +import pytest +from django.utils.translation import gettext_lazy as _ + +from memberships.users.forms import UserCreationForm +from memberships.users.models import User + +pytestmark = pytest.mark.django_db + + +class TestUserCreationForm: + """ + Test class for all tests related to the UserCreationForm + """ + + def test_username_validation_error_msg(self, user: User): + """ + Tests UserCreation Form's unique validator functions correctly by testing: + 1) A new user with an existing username cannot be added. + 2) Only 1 error is raised by the UserCreation Form + 3) The desired error message is raised + """ + + # The user already exists, + # hence cannot be created. + form = UserCreationForm( + { + "username": user.username, + "password1": user.password, + "password2": user.password, + } + ) + + assert not form.is_valid() + assert len(form.errors) == 1 + assert "username" in form.errors + assert form.errors["username"][0] == _("This username has already been taken.") diff --git a/memberships/users/tests/test_models.py b/memberships/users/tests/test_models.py new file mode 100644 index 00000000..bc2a19dc --- /dev/null +++ b/memberships/users/tests/test_models.py @@ -0,0 +1,9 @@ +import pytest + +from memberships.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/memberships/users/tests/test_tasks.py b/memberships/users/tests/test_tasks.py new file mode 100644 index 00000000..c0a41cbf --- /dev/null +++ b/memberships/users/tests/test_tasks.py @@ -0,0 +1,16 @@ +import pytest +from celery.result import EagerResult + +from memberships.users.tasks import get_users_count +from memberships.users.tests.factories import UserFactory + +pytestmark = pytest.mark.django_db + + +def test_user_count(settings): + """A basic test to execute the get_users_count Celery task.""" + UserFactory.create_batch(3) + settings.CELERY_TASK_ALWAYS_EAGER = True + task_result = get_users_count.delay() + assert isinstance(task_result, EagerResult) + assert task_result.result == 3 diff --git a/memberships/users/tests/test_urls.py b/memberships/users/tests/test_urls.py new file mode 100644 index 00000000..67e25b2e --- /dev/null +++ b/memberships/users/tests/test_urls.py @@ -0,0 +1,24 @@ +import pytest +from django.urls import resolve, reverse + +from memberships.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/memberships/users/tests/test_views.py b/memberships/users/tests/test_views.py new file mode 100644 index 00000000..e8cb197e --- /dev/null +++ b/memberships/users/tests/test_views.py @@ -0,0 +1,101 @@ +import pytest +from django.conf import settings +from django.contrib import messages +from django.contrib.auth.models import AnonymousUser +from django.contrib.messages.middleware import MessageMiddleware +from django.contrib.sessions.middleware import SessionMiddleware +from django.http import HttpRequest +from django.test import RequestFactory +from django.urls import reverse + +from memberships.users.forms import UserChangeForm +from memberships.users.models import User +from memberships.users.tests.factories import UserFactory +from memberships.users.views import ( + UserRedirectView, + UserUpdateView, + user_detail_view, +) + +pytestmark = pytest.mark.django_db + + +class TestUserUpdateView: + """ + TODO: + extracting view initialization code as class-scoped fixture + would be great if only pytest-django supported non-function-scoped + fixture db access -- this is a work-in-progress for now: + https://github.com/pytest-dev/pytest-django/pull/258 + """ + + def dummy_get_response(self, request: HttpRequest): + return None + + def test_get_success_url(self, user: User, rf: RequestFactory): + view = UserUpdateView() + request = rf.get("/fake-url/") + request.user = user + + view.request = request + + assert view.get_success_url() == f"/users/{user.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 + + def test_form_valid(self, user: User, rf: RequestFactory): + view = UserUpdateView() + request = rf.get("/fake-url/") + + # Add the session/message middleware to the request + SessionMiddleware(self.dummy_get_response).process_request(request) + MessageMiddleware(self.dummy_get_response).process_request(request) + request.user = user + + view.request = request + + # Initialize the form + form = UserChangeForm() + form.cleaned_data = [] + view.form_valid(form) + + messages_sent = [m.message for m in messages.get_messages(request)] + assert messages_sent == ["Information successfully updated"] + + +class TestUserRedirectView: + def test_get_redirect_url(self, user: User, rf: RequestFactory): + view = UserRedirectView() + request = rf.get("/fake-url") + request.user = user + + view.request = request + + assert view.get_redirect_url() == f"/users/{user.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) + login_url = reverse(settings.LOGIN_URL) + + assert response.status_code == 302 + assert response.url == f"{login_url}?next=/fake-url/" diff --git a/memberships/users/urls.py b/memberships/users/urls.py new file mode 100644 index 00000000..b790436e --- /dev/null +++ b/memberships/users/urls.py @@ -0,0 +1,14 @@ +from django.urls import path + +from memberships.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/memberships/users/views.py b/memberships/users/views.py new file mode 100644 index 00000000..c7b846c0 --- /dev/null +++ b/memberships/users/views.py @@ -0,0 +1,45 @@ +from django.contrib.auth import get_user_model +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.messages.views import SuccessMessageMixin +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from django.views.generic import DetailView, RedirectView, UpdateView + +User = get_user_model() + + +class UserDetailView(LoginRequiredMixin, DetailView): + + model = User + slug_field = "username" + slug_url_kwarg = "username" + + +user_detail_view = UserDetailView.as_view() + + +class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): + + model = User + fields = ["name"] + success_message = _("Information successfully updated") + + def get_success_url(self): + return self.request.user.get_absolute_url() # type: ignore [union-attr] + + def get_object(self): + return self.request.user + + +user_update_view = UserUpdateView.as_view() + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + + permanent = False + + def get_redirect_url(self): + return reverse("users:detail", kwargs={"username": self.request.user.username}) + + +user_redirect_view = UserRedirectView.as_view() diff --git a/memberships/utils/__init__.py b/memberships/utils/__init__.py new file mode 100644 index 00000000..c8fd0d6c --- /dev/null +++ b/memberships/utils/__init__.py @@ -0,0 +1,7 @@ +import razorpay +from django.conf import settings + +razorpay_client = razorpay.Client( + auth=(settings.RAZORPAY_KEY, settings.RAZORPAY_SECRET) +) +razorpay_client.set_app_details({"title": "Memberships", "version": "0.1"}) diff --git a/memberships/utils/authentication.py b/memberships/utils/authentication.py new file mode 100644 index 00000000..51f8cec6 --- /dev/null +++ b/memberships/utils/authentication.py @@ -0,0 +1,32 @@ +from django.conf import settings + +from rest_framework import authentication +from rest_framework import exceptions + +from memberships.users.models import User + + +def create_auth_token(token_model, user, serializer): + """Do not create auth token, application is supposed to used session auth.""" + return user + + +class UsernameAuthentication(authentication.BaseAuthentication): + """ + Authenticate using x-username header, only available in DEBUG mode. + """ + + def authenticate(self, request): + if not settings.DEBUG: + return None + + username = request.META.get("HTTP_X_USERNAME") + if not username: + return None + + try: + user = User.objects.get(username=username) + except User.DoesNotExist: + raise exceptions.AuthenticationFailed("No such user") + + return (user, None) diff --git a/memberships/utils/context_processors.py b/memberships/utils/context_processors.py new file mode 100644 index 00000000..3c535141 --- /dev/null +++ b/memberships/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/memberships/utils/exception_handlers.py b/memberships/utils/exception_handlers.py new file mode 100644 index 00000000..0ca45638 --- /dev/null +++ b/memberships/utils/exception_handlers.py @@ -0,0 +1,29 @@ +from django.http.response import Http404 +from rest_framework import exceptions +from rest_framework.views import set_rollback +from rest_framework.response import Response +from django_fsm import TransitionNotAllowed + + +def handle_drf_exception(exc, context): + if isinstance(exc, Http404): + exc = exceptions.NotFound() + elif isinstance(exc, (exceptions.PermissionDenied, TransitionNotAllowed)): + exc = exceptions.PermissionDenied() + + if isinstance(exc, exceptions.APIException): + headers = {} + if getattr(exc, "auth_header", None): + headers["WWW-Authenticate"] = exc.auth_header + if getattr(exc, "wait", None): + headers["Retry-After"] = "%d" % exc.wait + + if isinstance(exc.detail, (list, dict)): + data = exc.get_full_details() + else: + data = {"detail": exc.get_full_details()} + + set_rollback() + return Response(data, status=exc.status_code, headers=headers) + + return None diff --git a/memberships/utils/fields.py b/memberships/utils/fields.py new file mode 100644 index 00000000..1ea4f741 --- /dev/null +++ b/memberships/utils/fields.py @@ -0,0 +1,8 @@ +from model_utils.fields import StatusField as ModelUtilsStatusField +from django_fsm import FSMFieldMixin + + +class StateField(FSMFieldMixin, ModelUtilsStatusField): + def __init__(self, *args, **kwargs): + kwargs.setdefault("choices_name", "") + super().__init__(*args, **kwargs) diff --git a/memberships/utils/models.py b/memberships/utils/models.py new file mode 100644 index 00000000..730fa80b --- /dev/null +++ b/memberships/utils/models.py @@ -0,0 +1,51 @@ +from django.db import models +from inflection import underscore, pluralize + + +class BaseModelMeta(models.base.ModelBase): + def __new__(cls, name, bases, attrs): + defined_meta = attrs.get("Meta") + + # custom db table name + if defined_meta and hasattr(defined_meta, "db_table"): + custom_db_table = defined_meta.db_table + else: + custom_db_table = pluralize(underscore(name)) + + # custom realted name + if defined_meta and hasattr(defined_meta, "default_related_name"): + custom_related_name = defined_meta.default_realted_name + else: + custom_related_name = pluralize(underscore(name)) + + # custom ordering + if defined_meta and hasattr(defined_meta, "ordering"): + custom_ordering = defined_meta.ordering + else: + custom_ordering = ("-created_at",) + + super_class = super(BaseModelMeta, cls).__new__(cls, name, bases, attrs) + + # Proxy models should keep their existing db_table + if not hasattr(defined_meta, "proxy") or not defined_meta.proxy: + super_class._meta.db_table = custom_db_table + super_class._meta.original_attrs["db_table"] = custom_db_table + + super_class._meta.default_related_name = custom_related_name + super_class._meta.original_attrs[ + "default_related_name" + ] = custom_related_name + + super_class._meta.ordering = custom_ordering + super_class._meta.original_attrs["ordering"] = custom_ordering + + return super_class + + +class BaseModel(models.Model, metaclass=BaseModelMeta): + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + abstract = True diff --git a/memberships/utils/money.py b/memberships/utils/money.py new file mode 100644 index 00000000..477c4007 --- /dev/null +++ b/memberships/utils/money.py @@ -0,0 +1,11 @@ +from moneyed import get_currency, Money +from decimal import Decimal + + +def money_from_sub_unit(amount, currency_code): + currency = get_currency(currency_code) + return Money(Decimal(amount) / currency.sub_unit, currency.code) + + +def deduct_platform_fee(money, seller): + return money * (1 - Decimal(seller.user_preferences.platform_fee_percent / 100)) diff --git a/memberships/utils/storages.py b/memberships/utils/storages.py new file mode 100644 index 00000000..bc9e5064 --- /dev/null +++ b/memberships/utils/storages.py @@ -0,0 +1,11 @@ +from storages.backends.s3boto3 import S3Boto3Storage + + +class StaticRootS3Boto3Storage(S3Boto3Storage): + location = "static" + default_acl = "public-read" + + +class MediaRootS3Boto3Storage(S3Boto3Storage): + location = "media" + file_overwrite = False diff --git a/memberships/webhooks/__init__.py b/memberships/webhooks/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/webhooks/migrations/__init__.py b/memberships/webhooks/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memberships/webhooks/models.py b/memberships/webhooks/models.py new file mode 100644 index 00000000..16982bd3 --- /dev/null +++ b/memberships/webhooks/models.py @@ -0,0 +1,89 @@ +from operator import sub +from django.db import models + +from memberships.subscriptions.models import Subscription +from memberships.utils.models import BaseModel + + +class WebhookMessage(BaseModel): + class Sender(models.TextChoices): + RAZORPAY = "razorpay" + + sender = models.CharField(max_length=15, choices=Sender.choices) + payload = models.JSONField() + + is_processed = models.BooleanField(default=False) + external_id = models.CharField(max_length=255, unique=True) + + def process(self): + pass + + def process_razorpay(self): + event_name = self.payload["event"] + + # subscription is paid + # update active status + # create a payout + if self.payload["event"] == "subscription.charged": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.renew() + + # subscription is failed + # update active status + elif self.payload["event"] == "subscription.pending": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.start_renewal() + subscription.save() + + # subscription is halted + # update active status + elif self.payload["event"] == "subscription.halted": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.halt() + subscription.save() + + # subscription is cancelled + # update active status + elif self.payload["event"] == "subscription.cancelled": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.cancel() + + # subscription is paused + # update active status + elif self.payload["event"] == "subscription.paused": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.pause() + + # subscription is resumed + # update active status + elif self.payload["event"] == "subscription.resumed": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.resume() + + # donation is paid + # publish donation + # create a payload + elif self.payload["event"] == "order.paid": + # todo handle subscription with active ids? + subscription = Subscription.objects.get( + external_id=self.payload["subscription"]["id"] + ) + subscription.resume() diff --git a/memberships/webhooks/signals.py b/memberships/webhooks/signals.py new file mode 100644 index 00000000..d371e88c --- /dev/null +++ b/memberships/webhooks/signals.py @@ -0,0 +1,3 @@ +import django.dispatch + +webhook_received = django.dispatch.Signal() diff --git a/memberships/webhooks/tasks.py b/memberships/webhooks/tasks.py new file mode 100644 index 00000000..4e108b9b --- /dev/null +++ b/memberships/webhooks/tasks.py @@ -0,0 +1,65 @@ +from decimal import Decimal +from django.db.transaction import atomic +from moneyed import Money, get_currency +from memberships.payments.models import Payment, Payout +from memberships.subscriptions.models import Subscription +from memberships.webhooks.models import WebhookMessage +from memberships.donations.models import Donation + + +@atomic +def process_razorpay_webhook(webhook_message_id): + webhook_message = WebhookMessage.objects.get(pk=webhook_message_id) + + handlers = { + "subscription.charged": subscription_charged, + "order.paid": order_paid, + } + event_name = webhook_message["event"] + if event_name in handlers: + handlers[event_name](webhook_message.payload) + + webhook_message.is_processed = True + webhook_message.save() + + +def subscription_charged(payload): + """ + Update subscription expiration date, record payment, issue a payout. + """ + # nowait and try later? + subscription = Subscription.objects.select_for_update().get( + external_id=payload["payload"]["subscription"]["entity"]["id"] + ) + + payment_payload = payload["payload"]["payment"]["entity"] + payment, _ = Payment.objects.get_or_create( + type=Payment.Type.SUBSCRIPTION, + subscription=subscription, + status=Payment.Status.CAPTURED, + amount=get_money_from_subunit(payload["amount"], payload["currency"]), + external_id=payment_payload["id"], + seller=subscription.seller, + buyer=subscription.buyer, + ) + + # send payout + Payout.for_payment(payment) + + +def order_paid(payload): + """ + Update donation publish state, record payment, issue a payout. + """ + order_id = payload["payload"]["order"]["id"] + if not Donation.objects.filter(external_id=order_id).exists(): + # donation with this order id does not exists. + # this was most likely a subscription + return + + donation = Donation.objects.select_for_update().get(external_id=order_id) + + +def get_money_from_subunit(amount, currency_code): + currency = get_currency(currency_code) + return Money(Decimal(amount) / currency.sub_unit, currency.code) diff --git a/memberships/webhooks/views.py b/memberships/webhooks/views.py new file mode 100644 index 00000000..52e6a80c --- /dev/null +++ b/memberships/webhooks/views.py @@ -0,0 +1,35 @@ +import json +from secrets import compare_digest + +from django.conf import settings +from django.db.transaction import non_atomic_requests +from django.http import HttpResponse, HttpResponseForbidden +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_POST + +from memberships.utils import razorpay_client +from memberships.webhooks.models import WebhookMessage +from razorpay.errors import SignatureVerificationError + + +@csrf_exempt +@require_POST +@non_atomic_requests +def razorpay_webhook(request): + try: + razorpay_client.utility.verify_webhook_signature( + request.body, + request.headers["X-Razorpay-Signature"], + settings.RAZORPAY_WEBHOOK_SECRET, + ) + except (SignatureVerificationError, KeyError): + return HttpResponseForbidden("Invalid payload.", content_type="text/plain") + + payload = json.loads(request.body) + webhook_message = WebhookMessage.objects.create( + sender=WebhookMessage.Sender.RAZORPAY, + external_id=request.headers["x-razorpay-event-id"], + payload=payload, + ) + # process_webhook_payload(webhook_message) + return HttpResponse("Ok.", content_type="text/plain") diff --git a/merge_production_dotenvs_in_dotenv.py b/merge_production_dotenvs_in_dotenv.py new file mode 100644 index 00000000..d1170eff --- /dev/null +++ b/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/production.yml b/production.yml new file mode 100644 index 00000000..8277f2e5 --- /dev/null +++ b/production.yml @@ -0,0 +1,57 @@ +version: '3' + +volumes: + production_postgres_data: {} + production_postgres_data_backups: {} + production_traefik: {} + +services: + django: &django + build: + context: . + dockerfile: ./compose/production/django/Dockerfile + image: memberships_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: memberships_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: memberships_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" + - "0.0.0.0:5555:5555" + + redis: + image: redis:6 + + awscli: + build: + context: . + dockerfile: ./compose/production/aws/Dockerfile + env_file: + - ./.envs/.production/.django + volumes: + - production_postgres_data_backups:/backups:z diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 00000000..c2b3a233 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +addopts = --ds=config.settings.test --reuse-db +python_files = tests.py test_*.py diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 00000000..886b6945 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,39 @@ +pytz==2021.3 # https://github.com/stub42/pytz +python-slugify==5.0.2 # https://github.com/un33k/python-slugify +Pillow==8.3.2 # https://github.com/python-pillow/Pillow +argon2-cffi==21.1.0 # https://github.com/hynek/argon2_cffi +whitenoise==5.3.0 # https://github.com/evansd/whitenoise +redis==3.5.3 # https://github.com/andymccurdy/redis-py +hiredis==2.0.0 # https://github.com/redis/hiredis-py +uvicorn[standard]==0.15.0 # https://github.com/encode/uvicorn +python-dateutil==2.8.2 # https://github.com/dateutil/dateutil + +# Django +# ------------------------------------------------------------------------------ +django==3.2.8 # https://www.djangoproject.com/ +django-environ==0.7.0 # https://github.com/joke2k/django-environ +django-model-utils==4.1.1 # https://github.com/jazzband/django-model-utils +django-allauth==0.45.0 # https://github.com/pennersr/django-allauth +django-crispy-forms==1.13.0 # https://github.com/django-crispy-forms/django-crispy-forms +django-redis==5.0.0 # https://github.com/jazzband/django-redis +django-extensions==3.1.3 # https://github.com/django-extensions/django-extensions +django-versatileimagefield==2.2 # https://github.com/respondcreate/django-versatileimagefield +django-hashid-field==3.3.2 # https://github.com/nshafer/django-hashid-field + + +# Django REST Framework +# ------------------------------------------------------------------------------ +djangorestframework==3.12.4 # https://github.com/encode/django-rest-framework +django-cors-headers==3.9.0 # https://github.com/adamchainz/django-cors-headers +drf-spectacular==0.20.0 # https://github.com/tfranzel/drf-spectacular +dj-rest-auth==2.1.11 # http://github.com/iMerica/dj-rest-auth +drf-extensions==0.7.1 # http://github.com/chibisov/drf-extensions + + +# Business Logic +# --------------------------------------------------------------------------------- +razorpay==1.2.0 # https://github.com/razorpay/razorpay-python +# git+https://github.com/razorpay/razorpay-python.git@20610134a1b0b524f93eb95bd816bc30727a2cd0 + +django-fsm==2.7.1 # https://github.com/viewflow/django-fsm +django-money==2.1 # https://github.com/django-money/django-money diff --git a/requirements/local.txt b/requirements/local.txt new file mode 100644 index 00000000..a2a9e556 --- /dev/null +++ b/requirements/local.txt @@ -0,0 +1,36 @@ +-r base.txt + +Werkzeug==1.0.1 # https://github.com/pallets/werkzeug +ipdb==0.13.9 # https://github.com/gotcha/ipdb +psycopg2==2.9.1 # https://github.com/psycopg/psycopg2 +watchgod==0.7 # https://github.com/samuelcolvin/watchgod + +# Testing +# ------------------------------------------------------------------------------ +mypy==0.910 # https://github.com/python/mypy +django-stubs==1.8.0 # https://github.com/typeddjango/django-stubs +pytest==6.2.5 # https://github.com/pytest-dev/pytest +pytest-sugar==0.9.4 # https://github.com/Frozenball/pytest-sugar + +# Documentation +# ------------------------------------------------------------------------------ +sphinx==4.2.0 # https://github.com/sphinx-doc/sphinx +sphinx-autobuild==2021.3.14 # https://github.com/GaretJax/sphinx-autobuild + +# Code quality +# ------------------------------------------------------------------------------ +flake8==3.9.2 # https://github.com/PyCQA/flake8 +flake8-isort==4.0.0 # https://github.com/gforcada/flake8-isort +coverage==5.5 # https://github.com/nedbat/coveragepy +black==21.9b0 # https://github.com/psf/black +pylint-django==2.4.4 # https://github.com/PyCQA/pylint-django +pylint-celery==0.3 # https://github.com/PyCQA/pylint-celery +pre-commit==2.15.0 # https://github.com/pre-commit/pre-commit + +# Django +# ------------------------------------------------------------------------------ +factory-boy==3.2.0 # https://github.com/FactoryBoy/factory_boy + +django-debug-toolbar==3.2.2 # https://github.com/jazzband/django-debug-toolbar +django-coverage-plugin==2.0.0 # https://github.com/nedbat/django_coverage_plugin +pytest-django==4.4.0 # https://github.com/pytest-dev/pytest-django diff --git a/requirements/production.txt b/requirements/production.txt new file mode 100644 index 00000000..9b6b10e8 --- /dev/null +++ b/requirements/production.txt @@ -0,0 +1,12 @@ +# PRECAUTION: avoid production dependencies that aren't in development + +-r base.txt + +gunicorn==20.1.0 # https://github.com/benoitc/gunicorn +psycopg2==2.9.1 # https://github.com/psycopg/psycopg2 +sentry-sdk==1.4.3 # https://github.com/getsentry/sentry-python + +# Django +# ------------------------------------------------------------------------------ +django-storages[boto3]==1.11.1 # https://github.com/jschneier/django-storages +django-anymail[amazon_ses]==8.4 # https://github.com/anymail/django-anymail diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 00000000..55e9deef --- /dev/null +++ b/setup.cfg @@ -0,0 +1,40 @@ +[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 + +[isort] +line_length = 88 +known_first_party = memberships,config +multi_line_output = 3 +default_section = THIRDPARTY +skip = venv/ +skip_glob = **/migrations/*.py +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true + +[mypy] +python_version = 3.10 +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 = memberships/* +omit = *migrations*, *tests* +plugins = + django_coverage_plugin diff --git a/user opens profile page.yml b/user opens profile page.yml new file mode 100644 index 00000000..41f96a10 --- /dev/null +++ b/user opens profile page.yml @@ -0,0 +1,42 @@ +- user opens profile page +- signs up +- clicks subscribe +- backend created rzp and local subscribtion +- user is taken to checkout +- payment is successful +- rzp payment response is sent to backend +- backend verifies it +- backend updates the subscription status? + + +--- + +- consider 3 plans +- standard + - Rs. 100/month + - benefits? + + can see posts marked 'standard'? + can comment posts marked 'standard'? +- pro + - Rs. 300/month +- premium + - Rs. 500/month + + +user_1 comes +- chooses to custom pledge for Rs. 350 +- a new payment plan is created +- inherits - payment plan + + +--- + +--- + +generic benefits + +- visible to all "subscribers" +- visible to public +- all subscribers can comment +