commit 3f806b13a268d1cd61da837b79c71e1470d66522 Author: Alexandr Karpov Date: Fri Nov 18 10:19:20 2022 +0300 inited django diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5518e60 --- /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 0000000..6a9a5c4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.{html,css,scss,json,yml,xml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab + +[nginx.conf] +indent_style = space +indent_size = 2 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..68de5e4 --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +DATABASE_URL= +CELERY_BROKER_URL= +USE_DOCKER= diff --git a/.envs/.local/.django b/.envs/.local/.django new file mode 100644 index 0000000..247287b --- /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 0000000..b2ba40b --- /dev/null +++ b/.envs/.local/.postgres @@ -0,0 +1,7 @@ +# PostgreSQL +# ------------------------------------------------------------------------------ +POSTGRES_HOST=postgres +POSTGRES_PORT=5432 +POSTGRES_DB=akarpov +POSTGRES_USER=debug +POSTGRES_PASSWORD=debug diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..98a0de6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,79 @@ +# Config for Dependabot updates. See Documentation here: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + # Update GitHub actions in workflows + - package-ecosystem: "github-actions" + directory: "/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + # We need to specify each Dockerfile in a separate entry because Dependabot doesn't + # support wildcards or recursively checking subdirectories. Check this issue for updates: + # https://github.com/dependabot/dependabot-core/issues/2178 + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/local/django` directory + directory: "compose/local/django/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/local/docs` directory + directory: "compose/local/docs/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/local/node` directory + directory: "compose/local/node/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/production/aws` directory + directory: "compose/production/aws/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/production/django` directory + directory: "compose/production/django/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/production/postgres` directory + directory: "compose/production/postgres/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Docker + - package-ecosystem: "docker" + # Look for a `Dockerfile` in the `compose/production/traefik` directory + directory: "compose/production/traefik/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" + + # Enable version updates for Python/Pip - Production + - package-ecosystem: "pip" + # Look for a `requirements.txt` in the `root` directory + # also 'setup.cfg', 'runtime.txt' and 'requirements/*.txt' + directory: "/" + # Check for updates to GitHub Actions every weekday + schedule: + interval: "daily" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..90592d0 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,60 @@ +name: CI + +# Enable Buildkit and let compose use it to speed up image building +env: + DOCKER_BUILDKIT: 1 + COMPOSE_DOCKER_CLI_BUILD: 1 + +on: + pull_request: + branches: [ "master", "main" ] + paths-ignore: [ "docs/**" ] + + push: + branches: [ "master", "main" ] + paths-ignore: [ "docs/**" ] + +concurrency: + group: ${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + linter: + runs-on: ubuntu-latest + steps: + + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: "3.10" + cache: pip + cache-dependency-path: | + requirements/base.txt + requirements/local.txt + + - name: Run pre-commit + uses: pre-commit/action@v2.0.3 + + # With no caching at all the entire ci process takes 4m 30s to complete! + pytest: + runs-on: ubuntu-latest + + steps: + + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Build the Stack + run: docker-compose -f local.yml build + + - name: Run DB Migrations + run: docker-compose -f local.yml run --rm django python manage.py migrate + + - name: Run Django Tests + run: docker-compose -f local.yml run django pytest + + - name: Tear down the Stack + run: docker-compose -f local.yml down diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e20bb86 --- /dev/null +++ b/.gitignore @@ -0,0 +1,335 @@ +.env +.idea +### 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/ + + +# Provided default Pycharm Run/Debug Configurations should be tracked by git +# In case of local modifications made by Pycharm, use update-index command +# for each changed file, like this: +# git update-index --assume-unchanged .idea/akarpov.iml +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + + + +### 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 +akarpov/media/ + +.pytest_cache/ +.ipython/ +.env +.envs/* +!.envs/.local/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..433d97d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,39 @@ +exclude: "^docs/|/migrations/" +default_stages: [commit] + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.3.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + + - repo: https://github.com/asottile/pyupgrade + rev: v3.2.2 + hooks: + - id: pyupgrade + args: [--py310-plus] + + - repo: https://github.com/psf/black + rev: 22.10.0 + hooks: + - id: black + + - repo: https://github.com/PyCQA/isort + rev: 5.10.1 + hooks: + - id: isort + + - repo: https://github.com/PyCQA/flake8 + rev: 5.0.4 + 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 0000000..8e82229 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,14 @@ +[MASTER] +load-plugins=pylint_django, pylint_celery +django-settings-module=config.settings.local +[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/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..e943a5f --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,12 @@ +version: 2 + +sphinx: + configuration: docs/conf.py + +build: + image: testing + +python: + version: 3.10 + install: + - requirements: requirements/local.txt diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt new file mode 100644 index 0000000..e8420d6 --- /dev/null +++ b/CONTRIBUTORS.txt @@ -0,0 +1 @@ +sanspie diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b6b4ce6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ + +The MIT License (MIT) +Copyright (c) 2022, sanspie + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/akarpov/__init__.py b/akarpov/__init__.py new file mode 100644 index 0000000..3da9e5f --- /dev/null +++ b/akarpov/__init__.py @@ -0,0 +1,5 @@ +__version__ = "0.1.0" +__version_info__ = tuple( + int(num) if num.isdigit() else num + for num in __version__.replace("-", ".", 1).split(".") +) diff --git a/akarpov/blog/__init__.py b/akarpov/blog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/blog/api/__init__.py b/akarpov/blog/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/blog/api/serializers.py b/akarpov/blog/api/serializers.py new file mode 100644 index 0000000..0e4d334 --- /dev/null +++ b/akarpov/blog/api/serializers.py @@ -0,0 +1,120 @@ +from django.shortcuts import get_object_or_404 +from rest_framework import serializers + +from akarpov.blog.models import Comment, CommentRating, Post, PostRating +from akarpov.blog.services.post import update_comment_rate, update_post_rating +from akarpov.users.api.serializers import UserPublicInfoSerializer + + +class ListPostSerializer(serializers.ModelSerializer): + creator = UserPublicInfoSerializer() + url = serializers.HyperlinkedIdentityField( + view_name="retrieve_update_delete_post_api", lookup_field="slug" + ) + + class Meta: + model = Post + fields = ( + "title", + "url", + "creator", + "post_views", + "rating", + "comment_count", + "date_pub", + ) + + +class FullPostSerializer(serializers.ModelSerializer): + creator = UserPublicInfoSerializer(read_only=True) + + class Meta: + model = Post + fields = ( + "id", + "slug", + "title", + "body", + "creator", + "post_views", + "rating", + "rating_count", + "comment_count", + "date_pub", + "edited", + "image", + ) + extra_kwargs = { + "id": {"read_only": True}, + "slug": {"read_only": True}, + "creator": {"read_only": True}, + "post_views": {"read_only": True}, + "rating": {"read_only": True}, + "rating_count": {"read_only": True}, + "comment_count": {"read_only": True}, + "date_pub": {"read_only": True}, + "edited": {"read_only": True}, + } + + def create(self, validated_data): + return Post.objects.create( + **validated_data, creator=self.context["request"].user + ) + + +class CommentSerializer(serializers.ModelSerializer): + author = UserPublicInfoSerializer(read_only=True) + + class Meta: + model = Comment + fields = ("id", "author", "body", "created", "rating") + extra_kwargs = { + "id": {"read_only": True}, + "author": {"read_only": True}, + "created": {"read_only": True}, + "rating": {"read_only": True}, + } + + def create(self, validated_data): + return Comment.objects.create( + **validated_data, + author=self.context["request"].user, + post=Post.objects.get( + slug=self.context.get("request") + .parser_context.get("kwargs") + .get("slug") + ), + ) + + +class UpvoteCommentSerializer(serializers.ModelSerializer): + class Meta: + model = CommentRating + fields = ("vote_up",) + + def create(self, validated_data): + comment = get_object_or_404( + Comment, + id=self.context.get("request").parser_context.get("kwargs").get("pk"), + ) + return update_comment_rate( + comment, self.context["request"].user, validated_data["vote_up"] + ) + + +class PostRateSerializer(serializers.ModelSerializer): + class Meta: + model = PostRating + fields = ("rating",) + + def create(self, validated_data): + return update_post_rating( + post=get_object_or_404( + Post, + slug=self.context.get("request") + .parser_context.get("kwargs") + .get("slug"), + ), + user=self.context["request"].user, + rating=validated_data["rating"], + ) diff --git a/akarpov/blog/api/views.py b/akarpov/blog/api/views.py new file mode 100644 index 0000000..cbc0aee --- /dev/null +++ b/akarpov/blog/api/views.py @@ -0,0 +1,188 @@ +from django.db.models import F +from django.shortcuts import get_object_or_404 +from drf_spectacular.utils import extend_schema +from rest_framework import generics, status +from rest_framework.exceptions import AuthenticationFailed +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.response import Response +from rest_framework_simplejwt.authentication import JWTAuthentication + +from akarpov.blog.api.serializers import ( + CommentSerializer, + FullPostSerializer, + ListPostSerializer, + PostRateSerializer, + UpvoteCommentSerializer, +) +from akarpov.blog.models import Comment, CommentRating, Post, PostRating +from akarpov.common.api import SmallResultsSetPagination + + +class ListPostsApiView(generics.ListAPIView): + serializer_class = ListPostSerializer + pagination_class = SmallResultsSetPagination + + permission_classes = [AllowAny] + queryset = Post.objects.get_queryset().order_by("id") + + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + +class CreatePostApiView(generics.CreateAPIView): + serializer_class = FullPostSerializer + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) + + +class GetUpdateDeletePostApiView(generics.RetrieveUpdateDestroyAPIView): + serializer_class = FullPostSerializer + lookup_field = "slug" + + queryset = Post.objects.all() + + def get_permissions(self): + if self.request.method == "GET": + return [AllowAny] + return [IsAuthenticated] + + authentication_classes = [JWTAuthentication] + + def get_object(self): + if self.request.method != "GET": + if super().get_object().creator != self.request.user: + raise AuthenticationFailed("you are not allowed to access this post") + return super().get_object() + + def get(self, request, *args, **kwargs): + post = self.get_object() + post.post_views = F("post_views") + 1 + post.save(update_fields=["post_views"]) + + return self.retrieve(request, *args, **kwargs) + + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) + + def patch(self, request, *args, **kwargs): + return self.partial_update(request, *args, **kwargs) + + def delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) + + +class ListCreateCommentApiView(generics.ListCreateAPIView): + serializer_class = CommentSerializer + pagination_class = SmallResultsSetPagination + + authentication_classes = [JWTAuthentication] + + def get_queryset(self): + return Comment.objects.filter(post__slug=self.kwargs["slug"]) + + def get_permissions(self): + if self.request.method == "GET": + return [AllowAny] + return [IsAuthenticated()] + + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) + + +class RetrieveUpdateDeleteCommentApiView(generics.RetrieveUpdateDestroyAPIView): + serializer_class = CommentSerializer + lookup_field = "pk" + + queryset = Comment.objects.all() + authentication_classes = [JWTAuthentication] + + def get_permissions(self): + if self.request.method == "GET": + return [AllowAny] + return [IsAuthenticated] + + def get_object(self): + if self.request.method != "GET": + if super().get_object().author != self.request.user: + raise AuthenticationFailed("you are not allowed to access this comment") + return super().get_object() + + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) + + def patch(self, request, *args, **kwargs): + return self.partial_update(request, *args, **kwargs) + + def delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) + + +class CreateDeleteCommentRateApiView(generics.CreateAPIView): + serializer_class = UpvoteCommentSerializer + queryset = CommentRating.objects.all() + + authentication_classes = [JWTAuthentication] + permission_classes = [IsAuthenticated] + + def perform_create(self, serializer): + return serializer.save() + + @extend_schema(responses={200: CommentSerializer()}) + def post(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + self.perform_create(serializer) + + comment = CommentSerializer( + Comment.objects.get(id=self.kwargs["pk"]), context={"request": request} + ) + return Response( + data=comment.data, + status=status.HTTP_200_OK, + ) + + @extend_schema(responses={200: CommentSerializer()}) + def delete(self, request, *args, **kwargs): + CommentRating.objects.filter( + user=request.user, comment__id=self.kwargs["pk"] + ).delete() + + comment = CommentSerializer( + Comment.objects.get(id=self.kwargs["pk"]), context={"request": request} + ) + return Response( + data=comment.data, + status=status.HTTP_200_OK, + ) + + +class CreateDeletePostRating(generics.CreateAPIView, generics.DestroyAPIView): + serializer_class = PostRateSerializer + queryset = PostRating.objects.all() + + def get_post(self): + return get_object_or_404(Post, slug=self.kwargs["slug"]) + + def get_object(self): + try: + return PostRating.objects.get(post=self.get_post(), user=self.request.user) + except PostRating.DoesNotExist: + return Response(status=status.HTTP_404_NOT_FOUND) + + @extend_schema(request=PostRateSerializer, responses={200: ListPostSerializer()}) + def post(self, request, *args, **kwargs): + self.create(request, *args, **kwargs) + post = ListPostSerializer(self.get_post(), context={"request": request}) + return Response(post.data, status=status.HTTP_200_OK) + + def delete(self, request, *args, **kwargs): + self.destroy(request, *args, **kwargs) + post = ListPostSerializer(self.get_post(), context={"request": request}) + return Response(post.data, status=status.HTTP_200_OK) diff --git a/akarpov/blog/apps.py b/akarpov/blog/apps.py new file mode 100644 index 0000000..b18234e --- /dev/null +++ b/akarpov/blog/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class BlogConfig(AppConfig): + verbose_name = _("Blog") + name = "akarpov.blog" + + def ready(self): + try: + import akarpov.blog.signals # noqa F401 + except ImportError: + pass diff --git a/akarpov/blog/migrations/0001_initial.py b/akarpov/blog/migrations/0001_initial.py new file mode 100644 index 0000000..6b68545 --- /dev/null +++ b/akarpov/blog/migrations/0001_initial.py @@ -0,0 +1,79 @@ +# Generated by Django 4.0.8 on 2022-11-16 20:00 + +import akarpov.utils.files +from django.conf import settings +import django.core.validators +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Post', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(db_index=True, max_length=120)), + ('slug', models.SlugField(max_length=150, unique=True)), + ('body', models.TextField(db_index=True)), + ('post_views', models.IntegerField(default=0)), + ('rating', models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(5), django.core.validators.MinValueValidator(0)])), + ('rating_exactly', models.IntegerField(default=0)), + ('rating_count', models.IntegerField(default=0)), + ('comment_count', models.IntegerField(default=0)), + ('date_pub', models.DateTimeField(auto_now_add=True)), + ('edited', models.DateTimeField(auto_now=True)), + ('image', models.ImageField(blank=True, upload_to=akarpov.utils.files.user_file_upload_mixin)), + ('image_cropped', models.ImageField(blank=True, upload_to='cropped/')), + ('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ['id'], + }, + ), + migrations.CreateModel( + name='Comment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('body', models.CharField(max_length=500)), + ('created', models.DateTimeField(auto_now_add=True)), + ('rating', models.IntegerField(default=0)), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to=settings.AUTH_USER_MODEL)), + ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='blog.post')), + ], + options={ + 'ordering': ['-rating'], + }, + ), + migrations.CreateModel( + name='PostRating', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('rating', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)])), + ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ratings', to='blog.post')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_ratings', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'unique_together': {('user', 'post')}, + }, + ), + migrations.CreateModel( + name='CommentRating', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('vote_up', models.BooleanField()), + ('comment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ratings', to='blog.comment')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comment_ratings', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'unique_together': {('comment', 'user')}, + }, + ), + ] diff --git a/akarpov/blog/migrations/__init__.py b/akarpov/blog/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/blog/models.py b/akarpov/blog/models.py new file mode 100644 index 0000000..52bbd62 --- /dev/null +++ b/akarpov/blog/models.py @@ -0,0 +1,84 @@ +from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models + +from akarpov.users.models import User +from akarpov.utils.files import user_file_upload_mixin + + +class Post(models.Model): + """Model to store user's posts""" + + title = models.CharField(max_length=120, db_index=True) + slug = models.SlugField(max_length=150, blank=False, unique=True) + body = models.TextField(blank=False, db_index=True) + creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") + + post_views = models.IntegerField(default=0) + rating = models.FloatField( + default=0, validators=[MaxValueValidator(5), MinValueValidator(0)] + ) + rating_exactly = models.IntegerField(default=0) + rating_count = models.IntegerField(default=0) + comment_count = models.IntegerField(default=0) + + date_pub = models.DateTimeField(auto_now_add=True) + edited = models.DateTimeField(auto_now=True) + + image = models.ImageField(upload_to=user_file_upload_mixin, blank=True) + image_cropped = models.ImageField(upload_to="cropped/", blank=True) + + def __str__(self): + return self.title + + class Meta: + ordering = ["id"] + + +class PostRating(models.Model): + user = models.ForeignKey( + User, on_delete=models.CASCADE, related_name="post_ratings" + ) + post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="ratings") + + rating = models.IntegerField( + validators=[MinValueValidator(1), MaxValueValidator(5)] + ) + + def __str__(self): + return f"{self.user.username}'s rating {self.rating} on {self.post.title}" + + class Meta: + unique_together = ["user", "post"] + + +class Comment(models.Model): + post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") + author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") + + body = models.CharField(max_length=500) + created = models.DateTimeField(auto_now_add=True) + + rating = models.IntegerField(default=0) + + def __str__(self): + return f"{self.author.username}'s comment on {self.post.title}" + + class Meta: + ordering = ["-rating"] + + +class CommentRating(models.Model): + comment = models.ForeignKey( + Comment, on_delete=models.CASCADE, related_name="ratings" + ) + user = models.ForeignKey( + User, on_delete=models.CASCADE, related_name="comment_ratings" + ) + + vote_up = models.BooleanField(blank=False) + + def __str__(self): + return f"{self.user}'s vote up" if self.vote_up else f"{self.user}'s vote down" + + class Meta: + unique_together = ["comment", "user"] diff --git a/akarpov/blog/services/__init__.py b/akarpov/blog/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/blog/services/post.py b/akarpov/blog/services/post.py new file mode 100644 index 0000000..9087536 --- /dev/null +++ b/akarpov/blog/services/post.py @@ -0,0 +1,65 @@ +from akarpov.blog.models import Comment, CommentRating, Post, PostRating +from akarpov.users.models import User + + +def update_comment_rate(comment: Comment, user: User, vote_up: bool): + """Creates and updates comments' rating""" + comment_rate = CommentRating.objects.filter(user=user, comment=comment) + + if comment_rate.exists(): + comment_rate = comment_rate[0] + + if comment_rate.vote_up == vote_up: + return comment_rate + elif vote_up: + comment_rate.comment.rating += 2 + else: + comment_rate.comment.rating -= 2 + comment_rate.vote_up = vote_up + + comment_rate.comment.save(update_fields=["rating"]) + comment_rate.save(update_fields=["vote_up"]) + return comment_rate + else: + comment_rate = CommentRating.objects.create( + user=user, comment=comment, vote_up=vote_up + ) + if vote_up: + comment_rate.comment.rating += 1 + else: + comment_rate.comment.rating -= 1 + + comment_rate.comment.save(update_fields=["rating"]) + + return comment_rate + + +def update_post_rating(post: Post, user: User, rating: int): + """Creates and updates posts' rating""" + if old_rate := PostRating.objects.filter( + post=post, + user=user, + ): + old_rate = old_rate[0] + if old_rate.rating != rating: + + rating_ex = post.rating_exactly - old_rate.rating + rating + post.rating_exactly = rating_ex + post.rating = round(rating_ex / post.rating_count, 2) + old_rate.rating = rating + + post.save(update_fields=["rating_count", "rating_exactly", "rating"]) + old_rate.save(update_fields=["rating"]) + return old_rate + else: + rating_ex = post.rating_exactly + rating + post.rating_exactly = rating_ex + post.rating = round(rating_ex / (post.rating_count + 1), 2) + post.rating_count += 1 + + post.save(update_fields=["rating_count", "rating_exactly", "rating"]) + return PostRating.objects.create( + rating=rating, + post=post, + user=user, + ) diff --git a/akarpov/blog/signals.py b/akarpov/blog/signals.py new file mode 100644 index 0000000..dbe8f4c --- /dev/null +++ b/akarpov/blog/signals.py @@ -0,0 +1,71 @@ +from django.core.files import File +from django.db.models.signals import post_delete, post_save +from django.dispatch import receiver + +from akarpov.blog.models import Comment, CommentRating, Post, PostRating +from akarpov.utils.files import crop_image +from akarpov.utils.generators import generate_charset + + +@receiver(post_save, sender=Post) +def create_post(sender, instance, created, **kwargs): + if kwargs["update_fields"] != {"post_views"}: + if created: + slug = generate_charset(4) + while Post.objects.filter(slug=slug).exists(): + slug = generate_charset(4) + + instance.slug = slug + instance.save(update_fields=["slug"]) + + if instance.image: + instance.image_cropped.save( + instance.image.path.split(".")[0].split("/")[-1] + ".png", + File(crop_image(instance.image.path, cut_to=(750, 250))), + save=False, + ) + + post_save.disconnect(create_post, sender=sender) + instance.save(update_fields=["image_cropped"]) + post_save.connect(create_post, sender=Post) + + +# comments + + +@receiver(post_save, sender=Comment) +def create_comment(sender, instance, created, **kwargs): + if created: + instance.post.comment_count += 1 + instance.post.save(update_fields=["comment_count"]) + + +@receiver(post_delete, sender=Comment) +def delete_comment(sender, instance, **kwargs): + instance.post.comment_count -= 1 + instance.post.save(update_fields=["comment_count"]) + + +@receiver(post_delete, sender=CommentRating) +def delete_comment_rating(sender, instance, **kwargs): + if instance.vote_up: + instance.comment.rating -= 1 + else: + instance.comment.rating += 1 + + instance.comment.save(update_fields=["rating"]) + + +@receiver(post_delete, sender=PostRating) +def delete_post_rating(sender, instance, **kwargs): + if instance.post.rating_count != 1: + rating = instance.post.rating_exactly - instance.rating + instance.post.rating_exactly -= instance.rating + instance.post.rating = round(rating / (instance.post.rating_count - 1), 2) + instance.post.rating_count -= 1 + else: + instance.post.rating_exactly = 0 + instance.post.rating = 0 + instance.post.rating_count = 0 + + instance.post.save(update_fields=["rating_count", "rating_exactly", "rating"]) diff --git a/akarpov/common/__init__.py b/akarpov/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/common/api.py b/akarpov/common/api.py new file mode 100644 index 0000000..b5fd290 --- /dev/null +++ b/akarpov/common/api.py @@ -0,0 +1,19 @@ +from rest_framework.pagination import PageNumberPagination + + +class SmallResultsSetPagination(PageNumberPagination): + page_size = 10 + page_size_query_param = "page_size" + max_page_size = 100 + + +class StandardResultsSetPagination(PageNumberPagination): + page_size = 50 + page_size_query_param = "page_size" + max_page_size = 200 + + +class BigResultsSetPagination(PageNumberPagination): + page_size = 100 + page_size_query_param = "page_size" + max_page_size = 1000 diff --git a/akarpov/conftest.py b/akarpov/conftest.py new file mode 100644 index 0000000..0850c00 --- /dev/null +++ b/akarpov/conftest.py @@ -0,0 +1,14 @@ +import pytest + +from akarpov.users.models import User +from akarpov.users.tests.factories import UserFactory + + +@pytest.fixture(autouse=True) +def media_storage(settings, tmpdir): + settings.MEDIA_ROOT = tmpdir.strpath + + +@pytest.fixture +def user(db) -> User: + return UserFactory() diff --git a/akarpov/contrib/__init__.py b/akarpov/contrib/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/akarpov/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/akarpov/contrib/sites/__init__.py b/akarpov/contrib/sites/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/akarpov/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/akarpov/contrib/sites/migrations/0001_initial.py b/akarpov/contrib/sites/migrations/0001_initial.py new file mode 100644 index 0000000..304cd6d --- /dev/null +++ b/akarpov/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/akarpov/contrib/sites/migrations/0002_alter_domain_unique.py b/akarpov/contrib/sites/migrations/0002_alter_domain_unique.py new file mode 100644 index 0000000..2c8d6da --- /dev/null +++ b/akarpov/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/akarpov/contrib/sites/migrations/0003_set_site_domain_and_name.py b/akarpov/contrib/sites/migrations/0003_set_site_domain_and_name.py new file mode 100644 index 0000000..53b8cf7 --- /dev/null +++ b/akarpov/contrib/sites/migrations/0003_set_site_domain_and_name.py @@ -0,0 +1,63 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" +from django.conf import settings +from django.db import migrations + + +def _update_or_create_site_with_sequence(site_model, connection, domain, name): + """Update or create the site with default ID and keep the DB sequence in sync.""" + site, created = site_model.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + "domain": domain, + "name": name, + }, + ) + if created: + # We provided the ID explicitly when creating the Site entry, therefore the DB + # sequence to auto-generate them wasn't used and is now out of sync. If we + # don't do anything, we'll get a unique constraint violation the next time a + # site is created. + # To avoid this, we need to manually update DB sequence and make sure it's + # greater than the maximum value. + max_id = site_model.objects.order_by('-id').first().id + with connection.cursor() as cursor: + cursor.execute("SELECT last_value from django_site_id_seq") + (current_id,) = cursor.fetchone() + if current_id <= max_id: + cursor.execute( + "alter sequence django_site_id_seq restart with %s", + [max_id + 1], + ) + + +def update_site_forward(apps, schema_editor): + """Set site domain and name.""" + Site = apps.get_model("sites", "Site") + _update_or_create_site_with_sequence( + Site, + schema_editor.connection, + "akarpov.ru", + "akarpov", + ) + + +def update_site_backward(apps, schema_editor): + """Revert site domain and name to default.""" + Site = apps.get_model("sites", "Site") + _update_or_create_site_with_sequence( + Site, + schema_editor.connection, + "example.com", + "example.com", + ) + + +class Migration(migrations.Migration): + + dependencies = [("sites", "0002_alter_domain_unique")] + + operations = [migrations.RunPython(update_site_forward, update_site_backward)] diff --git a/akarpov/contrib/sites/migrations/0004_alter_options_ordering_domain.py b/akarpov/contrib/sites/migrations/0004_alter_options_ordering_domain.py new file mode 100644 index 0000000..f7118ca --- /dev/null +++ b/akarpov/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/akarpov/contrib/sites/migrations/__init__.py b/akarpov/contrib/sites/migrations/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/akarpov/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/akarpov/static/css/project.css b/akarpov/static/css/project.css new file mode 100644 index 0000000..f1d543d --- /dev/null +++ b/akarpov/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/akarpov/static/fonts/.gitkeep b/akarpov/static/fonts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/static/images/favicons/favicon.ico b/akarpov/static/images/favicons/favicon.ico new file mode 100644 index 0000000..e1c1dd1 Binary files /dev/null and b/akarpov/static/images/favicons/favicon.ico differ diff --git a/akarpov/static/js/project.js b/akarpov/static/js/project.js new file mode 100644 index 0000000..d26d23b --- /dev/null +++ b/akarpov/static/js/project.js @@ -0,0 +1 @@ +/* Project specific Javascript goes here. */ diff --git a/akarpov/templates/403.html b/akarpov/templates/403.html new file mode 100644 index 0000000..4356d93 --- /dev/null +++ b/akarpov/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/akarpov/templates/404.html b/akarpov/templates/404.html new file mode 100644 index 0000000..31c0f2b --- /dev/null +++ b/akarpov/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/akarpov/templates/500.html b/akarpov/templates/500.html new file mode 100644 index 0000000..46e43a9 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/account_inactive.html b/akarpov/templates/account/account_inactive.html new file mode 100644 index 0000000..07175e4 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/base.html b/akarpov/templates/account/base.html new file mode 100644 index 0000000..8e1f260 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/email.html b/akarpov/templates/account/email.html new file mode 100644 index 0000000..f7fa9b2 --- /dev/null +++ b/akarpov/templates/account/email.html @@ -0,0 +1,78 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Account" %}{% endblock %} + +{% block inner %} +

{% translate "E-mail Addresses" %}

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

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

+ +
+{% csrf_token %} +
+ + {% for emailaddress in user.emailaddress_set.all %} +
+ +
+ {% endfor %} + +
+ + + +
+ +
+
+ +{% 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/akarpov/templates/account/email_confirm.html b/akarpov/templates/account/email_confirm.html new file mode 100644 index 0000000..525c0f3 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/login.html b/akarpov/templates/account/login.html new file mode 100644 index 0000000..838ed11 --- /dev/null +++ b/akarpov/templates/account/login.html @@ -0,0 +1,59 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account socialaccount %} +{% load crispy_forms_tags %} + +{% block head_title %}{% translate "Sign In" %}{% endblock %} + +{% block inner %} + +

{% translate "Sign In" %}

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

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

+ +
+ + + + + +
+ + {% include "socialaccount/snippets/login_extra.html" %} + +{% else %} + {% if ACCOUNT_ALLOW_REGISTRATION %} +

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

+ {% endif %} +{% endif %} + +
+ {% csrf_token %} + {{ form|crispy }} + {% if redirect_field_value %} + + {% endif %} + {% translate "Forgot Password?" %} + +
+ +{% endblock %} diff --git a/akarpov/templates/account/logout.html b/akarpov/templates/account/logout.html new file mode 100644 index 0000000..d41824e --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_change.html b/akarpov/templates/account/password_change.html new file mode 100644 index 0000000..5182a7a --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_reset.html b/akarpov/templates/account/password_reset.html new file mode 100644 index 0000000..8a2b7a5 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_reset_done.html b/akarpov/templates/account/password_reset_done.html new file mode 100644 index 0000000..f682ee8 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_reset_from_key.html b/akarpov/templates/account/password_reset_from_key.html new file mode 100644 index 0000000..dd836b4 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_reset_from_key_done.html b/akarpov/templates/account/password_reset_from_key_done.html new file mode 100644 index 0000000..7a58b44 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/password_set.html b/akarpov/templates/account/password_set.html new file mode 100644 index 0000000..a748eb9 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/signup.html b/akarpov/templates/account/signup.html new file mode 100644 index 0000000..189ab9e --- /dev/null +++ b/akarpov/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 %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + {% if redirect_field_value %} + + {% endif %} + +
+ +{% endblock %} diff --git a/akarpov/templates/account/signup_closed.html b/akarpov/templates/account/signup_closed.html new file mode 100644 index 0000000..fcea1f0 --- /dev/null +++ b/akarpov/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/akarpov/templates/account/verification_sent.html b/akarpov/templates/account/verification_sent.html new file mode 100644 index 0000000..acf81be --- /dev/null +++ b/akarpov/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/akarpov/templates/account/verified_email_required.html b/akarpov/templates/account/verified_email_required.html new file mode 100644 index 0000000..beefcea --- /dev/null +++ b/akarpov/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/akarpov/templates/base.html b/akarpov/templates/base.html new file mode 100644 index 0000000..207f2d2 --- /dev/null +++ b/akarpov/templates/base.html @@ -0,0 +1,112 @@ +{% load static i18n %} +{% get_current_language as LANGUAGE_CODE %} + + + + + {% block title %}akarpov{% endblock title %} + + + + + + + {% block css %} + + + + + + + {% endblock %} + + {# Placed at the top of the document so pages load faster with defer #} + {% block javascript %} + + + + + + + + {% endblock javascript %} + + + + + +
+ + +
+ +
+ + {% if messages %} + {% for message in messages %} +
+ {{ message }} + +
+ {% endfor %} + {% endif %} + + {% block content %} +

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

+ {% endblock content %} + +
+ + {% block modal %}{% endblock modal %} + + {% block inline_javascript %} + {% comment %} + Script tags with only code, no src (defer by default). To run + with a "defer" so that you run inline code: + + {% endcomment %} + {% endblock inline_javascript %} + + diff --git a/akarpov/templates/email_template.html b/akarpov/templates/email_template.html new file mode 100644 index 0000000..8eb048e --- /dev/null +++ b/akarpov/templates/email_template.html @@ -0,0 +1,4 @@ +{% autoescape off %} +Hey there, +Here is your token: {{ uid }}:{{ token }} +{% endautoescape %} diff --git a/akarpov/templates/pages/about.html b/akarpov/templates/pages/about.html new file mode 100644 index 0000000..94d9808 --- /dev/null +++ b/akarpov/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/akarpov/templates/pages/home.html b/akarpov/templates/pages/home.html new file mode 100644 index 0000000..94d9808 --- /dev/null +++ b/akarpov/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/akarpov/templates/users/user_detail.html b/akarpov/templates/users/user_detail.html new file mode 100644 index 0000000..79b8233 --- /dev/null +++ b/akarpov/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/akarpov/templates/users/user_form.html b/akarpov/templates/users/user_form.html new file mode 100644 index 0000000..467357a --- /dev/null +++ b/akarpov/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/akarpov/users/__init__.py b/akarpov/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/users/adapters.py b/akarpov/users/adapters.py new file mode 100644 index 0000000..0d206fa --- /dev/null +++ b/akarpov/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/akarpov/users/admin.py b/akarpov/users/admin.py new file mode 100644 index 0000000..40310a9 --- /dev/null +++ b/akarpov/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 .forms import UserAdminChangeForm, UserAdminCreationForm + +User = get_user_model() + + +@admin.register(User) +class UserAdmin(auth_admin.UserAdmin): + form = UserAdminChangeForm + add_form = UserAdminCreationForm + fieldsets = ( + (None, {"fields": ("username", "password")}), + (_("Personal info"), {"fields": ("email",)}), + (_("Images"), {"fields": ("image", "image_cropped")}), + ( + _("Permissions"), + { + "fields": ( + "is_active", + "is_staff", + "is_superuser", + "groups", + "user_permissions", + ), + }, + ), + (_("Important dates"), {"fields": ("last_login", "date_joined")}), + ) + list_display = ["username", "is_superuser"] + search_fields = ["username", "email"] diff --git a/akarpov/users/api/serializers.py b/akarpov/users/api/serializers.py new file mode 100644 index 0000000..d71d25c --- /dev/null +++ b/akarpov/users/api/serializers.py @@ -0,0 +1,59 @@ +from rest_framework import serializers + +from akarpov.users.models import User +from akarpov.users.services.email_validation import activate + + +class UserRegisterSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ("id", "username", "email", "password") + extra_kwargs = { + "password": {"write_only": True}, + "email": {"required": True}, + "id": {"read_only": True}, + } + + +class UserEmailVerification(serializers.Serializer): + token = serializers.CharField(max_length=255) + + def validate_token(self, token): + activate(token.split(":")[0], token.split(":")[1]) + return token + + +class UserPublicInfoSerializer(serializers.ModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name="user_retrieve_username_api", lookup_field="username" + ) + + class Meta: + model = User + fields = ("id", "username", "url", "image_cropped") + + +class UserFullPublicInfoSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ("id", "username", "email", "is_superuser", "about", "image") + + +class UserFullSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ( + "id", + "username", + "email", + "is_staff", + "is_superuser", + "about", + "image", + ) + extra_kwargs = { + "id": {"read_only": True}, + "email": {"read_only": True}, + "is_staff": {"read_only": True}, + "is_superuser": {"read_only": True}, + } diff --git a/akarpov/users/api/views.py b/akarpov/users/api/views.py new file mode 100644 index 0000000..f65792b --- /dev/null +++ b/akarpov/users/api/views.py @@ -0,0 +1,129 @@ +from drf_spectacular.utils import extend_schema +from rest_framework import generics, permissions, status, views +from rest_framework.response import Response +from rest_framework_simplejwt.settings import api_settings +from rest_framework_simplejwt.views import TokenViewBase + +from akarpov.common.api import SmallResultsSetPagination +from akarpov.users.api.serializers import ( + UserEmailVerification, + UserFullPublicInfoSerializer, + UserFullSerializer, + UserPublicInfoSerializer, + UserRegisterSerializer, +) +from akarpov.users.models import User + + +class UserRegisterViewSet(generics.CreateAPIView): + """Creates new user and sends verification email""" + + serializer_class = UserRegisterSerializer + permission_classes = [permissions.AllowAny] + + @extend_schema( + operation_id="auth_user_register", + ) + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) + + +class TokenObtainPairView(TokenViewBase): + """ + Takes a set of user credentials and returns an access and refresh JSON web + token pair to prove the authentication of those credentials. + """ + + _serializer_class = api_settings.TOKEN_OBTAIN_SERIALIZER + + @extend_schema(operation_id="auth_token_obtain") + def post(self, request, *args, **kwargs): + return super().post(request, *args, **kwargs) + + +class TokenRefreshView(TokenViewBase): + """ + Takes a refresh type JSON web token and returns an access type JSON web + token if the refresh token is valid. + """ + + _serializer_class = api_settings.TOKEN_REFRESH_SERIALIZER + + @extend_schema(operation_id="auth_token_refresh") + def post(self, request, *args, **kwargs): + return super().post(request, *args, **kwargs) + + +class UserEmailValidationViewSet(views.APIView): + """Receives token from email and activates user""" + + permission_classes = [permissions.AllowAny] + serializer_class = UserEmailVerification + + @extend_schema( + operation_id="auth_user_email_prove", + request=UserEmailVerification(), + responses={200: "", 400: {"message": "Incorrect token"}}, + ) + def post(self, request): + serializer = UserEmailVerification(data=request.data) + serializer.is_valid(raise_exception=True) + return Response(status=status.HTTP_200_OK) + + +class UserListViewSet(generics.ListAPIView): + serializer_class = UserPublicInfoSerializer + pagination_class = SmallResultsSetPagination + + permission_classes = [permissions.AllowAny] + queryset = User.objects.get_queryset().filter(is_active=True).order_by("id") + + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + +class UserRetrieveViewSet(generics.RetrieveAPIView): + """Returns user's instance on username""" + + serializer_class = UserFullPublicInfoSerializer + lookup_field = "username" + + queryset = User.objects.all() + permission_classes = [permissions.AllowAny] + + @extend_schema( + operation_id="user_username_lookup", + ) + def get(self, request, *args, **kwargs): + return super().get(request, *args, **kwargs) + + +class UserRetrieveIdViewSet(UserRetrieveViewSet): + """Returns user's instance on user's id""" + + lookup_field = "pk" + + @extend_schema( + operation_id="user_id_lookup", + ) + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + +class UserRetireUpdateSelfViewSet(generics.RetrieveUpdateDestroyAPIView): + serializer_class = UserFullSerializer + + def get_object(self): + return self.request.user + + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) + + def patch(self, request, *args, **kwargs): + return self.partial_update(request, *args, **kwargs) + + def delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) diff --git a/akarpov/users/apps.py b/akarpov/users/apps.py new file mode 100644 index 0000000..b3846fa --- /dev/null +++ b/akarpov/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class UsersConfig(AppConfig): + name = "akarpov.users" + verbose_name = _("Users") + + def ready(self): + try: + import akarpov.users.signals # noqa F401 + except ImportError: + pass diff --git a/akarpov/users/context_processors.py b/akarpov/users/context_processors.py new file mode 100644 index 0000000..e2633ae --- /dev/null +++ b/akarpov/users/context_processors.py @@ -0,0 +1,8 @@ +from django.conf import settings + + +def allauth_settings(request): + """Expose some settings from django-allauth in templates.""" + return { + "ACCOUNT_ALLOW_REGISTRATION": settings.ACCOUNT_ALLOW_REGISTRATION, + } diff --git a/akarpov/users/forms.py b/akarpov/users/forms.py new file mode 100644 index 0000000..6e1dd9d --- /dev/null +++ b/akarpov/users/forms.py @@ -0,0 +1,42 @@ +from allauth.account.forms import SignupForm +from allauth.socialaccount.forms import SignupForm as SocialSignupForm +from django.contrib.auth import forms as admin_forms +from django.contrib.auth import get_user_model +from django.utils.translation import gettext_lazy as _ + +User = get_user_model() + + +class UserAdminChangeForm(admin_forms.UserChangeForm): + class Meta(admin_forms.UserChangeForm.Meta): + model = User + + +class UserAdminCreationForm(admin_forms.UserCreationForm): + """ + Form for User Creation in the Admin Area. + To change user signup, see UserSignupForm and UserSocialSignupForm. + """ + + class Meta(admin_forms.UserCreationForm.Meta): + model = User + + error_messages = { + "username": {"unique": _("This username has already been taken.")} + } + + +class UserSignupForm(SignupForm): + """ + Form that will be rendered on a user sign up section/screen. + Default fields will be added automatically. + Check UserSocialSignupForm for accounts created from social. + """ + + +class UserSocialSignupForm(SocialSignupForm): + """ + Renders the form when user has signed up using social accounts. + Default fields will be added automatically. + See UserSignupForm otherwise. + """ diff --git a/akarpov/users/middleware.py b/akarpov/users/middleware.py new file mode 100644 index 0000000..659c9c2 --- /dev/null +++ b/akarpov/users/middleware.py @@ -0,0 +1,10 @@ +from django.utils.deprecation import MiddlewareMixin +from rest_framework.exceptions import AuthenticationFailed + + +class EmailVerificationMiddleware(MiddlewareMixin): + def process_request(self, request): + if request.user.is_authenticated: + if not request.user.is_verified: + raise AuthenticationFailed("Email is not verified") + return None diff --git a/akarpov/users/migrations/0001_initial.py b/akarpov/users/migrations/0001_initial.py new file mode 100644 index 0000000..acd1851 --- /dev/null +++ b/akarpov/users/migrations/0001_initial.py @@ -0,0 +1,124 @@ +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", "0012_alter_user_first_name_max_length"), + ] + + operations = [ + migrations.CreateModel( + name="User", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("password", models.CharField(max_length=128, verbose_name="password")), + ( + "last_login", + models.DateTimeField( + blank=True, null=True, verbose_name="last login" + ), + ), + ( + "is_superuser", + models.BooleanField( + default=False, + help_text="Designates that this user has all permissions without explicitly assigning them.", + verbose_name="superuser status", + ), + ), + ( + "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": "user", + "verbose_name_plural": "users", + "abstract": False, + }, + managers=[ + ("objects", django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/akarpov/users/migrations/0002_alter_user_options_remove_user_name_user_about_and_more.py b/akarpov/users/migrations/0002_alter_user_options_remove_user_name_user_about_and_more.py new file mode 100644 index 0000000..ce0642e --- /dev/null +++ b/akarpov/users/migrations/0002_alter_user_options_remove_user_name_user_about_and_more.py @@ -0,0 +1,37 @@ +# Generated by Django 4.0.8 on 2022-11-16 20:00 + +import akarpov.utils.files +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('users', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='user', + options={'ordering': ['-id']}, + ), + migrations.RemoveField( + model_name='user', + name='name', + ), + migrations.AddField( + model_name='user', + name='about', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='user', + name='image', + field=models.ImageField(blank=True, upload_to=akarpov.utils.files.user_file_upload_mixin), + ), + migrations.AddField( + model_name='user', + name='image_cropped', + field=models.ImageField(blank=True, upload_to='cropped/'), + ), + ] diff --git a/akarpov/users/migrations/__init__.py b/akarpov/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/users/models.py b/akarpov/users/models.py new file mode 100644 index 0000000..3603964 --- /dev/null +++ b/akarpov/users/models.py @@ -0,0 +1,22 @@ +from django.contrib.auth.models import AbstractUser +from django.db import models + +from akarpov.utils.files import user_file_upload_mixin + + +class User(AbstractUser): + """Base user model, to store all user info""" + + first_name = None + last_name = None + + image = models.ImageField(upload_to=user_file_upload_mixin, blank=True) + image_cropped = models.ImageField(upload_to="cropped/", blank=True) + + about = models.TextField(blank=True) + + def __str__(self): + return self.username + + class Meta: + ordering = ["-id"] diff --git a/akarpov/users/services/__init__.py b/akarpov/users/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/users/services/email_validation.py b/akarpov/users/services/email_validation.py new file mode 100644 index 0000000..cff1f55 --- /dev/null +++ b/akarpov/users/services/email_validation.py @@ -0,0 +1,22 @@ +from django.contrib.auth import get_user_model +from django.utils.encoding import force_str +from django.utils.http import urlsafe_base64_decode +from rest_framework.exceptions import ValidationError + +from akarpov.utils.generators import TokenGenerator + + +def activate(uidb64, token): + User = get_user_model() + account_activation_token = TokenGenerator() + try: + uid = force_str(urlsafe_base64_decode(uidb64)) + user = User.objects.get(pk=uid) + except (TypeError, ValueError, OverflowError, User.DoesNotExist): + user = None + if user is not None and account_activation_token.check_token(user, token): + user.is_active = True + user.save() + return user + else: + raise ValidationError("Incorrect token") diff --git a/akarpov/users/signals.py b/akarpov/users/signals.py new file mode 100644 index 0000000..b8aa740 --- /dev/null +++ b/akarpov/users/signals.py @@ -0,0 +1,42 @@ +from django.core.files import File +from django.core.mail import send_mail +from django.db.models.signals import post_save +from django.dispatch import receiver +from django.template.loader import render_to_string +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode + +from akarpov.users.models import User +from akarpov.utils.files import crop_image +from akarpov.utils.generators import TokenGenerator + + +@receiver(post_save, sender=User) +def create_user(sender, instance, created, **kwargs): + if created: + instance.is_active = False + instance.set_password(instance.password) + instance.save() + account_activation_token = TokenGenerator() + + mail_subject = "Account activation at akarpov.ru." + message = render_to_string( + "email_template.html", + { + "user": instance, + "uid": urlsafe_base64_encode(force_bytes(instance.pk)), + "token": account_activation_token.make_token(instance), + }, + ) + send_mail(mail_subject, message, "main@akarpov.ru", [instance.email]) + + if instance.image: + instance.image_cropped.save( + instance.image.path.split(".")[0].split("/")[-1] + ".png", + File(crop_image(instance.image.path, cut_to=(250, 250))), + save=False, + ) + + post_save.disconnect(create_user, sender=sender) + instance.save(update_fields=["image_cropped"]) + post_save.connect(create_user, sender=User) diff --git a/akarpov/users/tasks.py b/akarpov/users/tasks.py new file mode 100644 index 0000000..c99341c --- /dev/null +++ b/akarpov/users/tasks.py @@ -0,0 +1,11 @@ +from django.contrib.auth import get_user_model + +from config import celery_app + +User = get_user_model() + + +@celery_app.task() +def get_users_count(): + """A pointless Celery task to demonstrate usage.""" + return User.objects.count() diff --git a/akarpov/users/urls.py b/akarpov/users/urls.py new file mode 100644 index 0000000..79b8674 --- /dev/null +++ b/akarpov/users/urls.py @@ -0,0 +1,10 @@ +from django.urls import path + +from akarpov.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/akarpov/users/views.py b/akarpov/users/views.py new file mode 100644 index 0000000..baa04a0 --- /dev/null +++ b/akarpov/users/views.py @@ -0,0 +1,48 @@ +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): + assert ( + self.request.user.is_authenticated + ) # for mypy to know that the user is authenticated + return self.request.user.get_absolute_url() + + def get_object(self): + return self.request.user + + +user_update_view = UserUpdateView.as_view() + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + + permanent = False + + def get_redirect_url(self): + return reverse("users:detail", kwargs={"username": self.request.user.username}) + + +user_redirect_view = UserRedirectView.as_view() diff --git a/akarpov/utils/__init__.py b/akarpov/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/akarpov/utils/files.py b/akarpov/utils/files.py new file mode 100644 index 0000000..8151f94 --- /dev/null +++ b/akarpov/utils/files.py @@ -0,0 +1,32 @@ +import os +from io import BytesIO + +from django.contrib.auth import get_user_model +from PIL import Image + + +def crop_image(image_path: str, cut_to=(500, 500)): + """Makes image's thumbnail bt given parameters. By default, crops to 500x500""" + img = Image.open(image_path) + blob = BytesIO() + + try: + img.thumbnail(cut_to, Image.ANTIALIAS) + except OSError: + print("Can't crop") + + img.save(blob, "PNG") + return blob + + +def user_file_upload_mixin(instance, filename): + """stores user uploaded files at their folder in media dir""" + username = "" + if isinstance(instance, get_user_model()): + username = instance.username + elif hasattr(instance, "user"): + username = instance.user.username + elif hasattr(instance, "creator"): + username = instance.creator.username + + return os.path.join(f"uploads/{username}/", filename) diff --git a/akarpov/utils/generators.py b/akarpov/utils/generators.py new file mode 100644 index 0000000..b9e7727 --- /dev/null +++ b/akarpov/utils/generators.py @@ -0,0 +1,16 @@ +import random +import string + +from django.contrib.auth.tokens import PasswordResetTokenGenerator + + +class TokenGenerator(PasswordResetTokenGenerator): + """token processor for user""" + + def _make_hash_value(self, user, timestamp): + return str(str(user.pk) + str(timestamp) + str(user.is_active)) + + +def generate_charset(length: int) -> str: + """Generate a random string of characters of a given length.""" + return "".join(random.choice(string.ascii_letters) for _ in range(length)) diff --git a/compose/local/django/Dockerfile b/compose/local/django/Dockerfile new file mode 100644 index 0000000..2e31be3 --- /dev/null +++ b/compose/local/django/Dockerfile @@ -0,0 +1,81 @@ +ARG PYTHON_VERSION=3.10-slim-bullseye + +# 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 \ + # 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 ./compose/local/django/celery/worker/start /start-celeryworker +RUN sed -i 's/\r$//g' /start-celeryworker +RUN chmod +x /start-celeryworker + +COPY ./compose/local/django/celery/beat/start /start-celerybeat +RUN sed -i 's/\r$//g' /start-celerybeat +RUN chmod +x /start-celerybeat + +COPY ./compose/local/django/celery/flower/start /start-flower +RUN sed -i 's/\r$//g' /start-flower +RUN chmod +x /start-flower + + +# copy application code to WORKDIR +COPY . ${APP_HOME} + +ENTRYPOINT ["/entrypoint"] diff --git a/compose/local/django/celery/beat/start b/compose/local/django/celery/beat/start new file mode 100644 index 0000000..c04a736 --- /dev/null +++ b/compose/local/django/celery/beat/start @@ -0,0 +1,8 @@ +#!/bin/bash + +set -o errexit +set -o nounset + + +rm -f './celerybeat.pid' +celery -A config.celery_app beat -l INFO diff --git a/compose/local/django/celery/flower/start b/compose/local/django/celery/flower/start new file mode 100644 index 0000000..bd3c9f2 --- /dev/null +++ b/compose/local/django/celery/flower/start @@ -0,0 +1,11 @@ +#!/bin/bash + +set -o errexit +set -o nounset + + +celery \ + -A config.celery_app \ + -b "${CELERY_BROKER_URL}" \ + flower \ + --basic_auth="${CELERY_FLOWER_USER}:${CELERY_FLOWER_PASSWORD}" diff --git a/compose/local/django/celery/worker/start b/compose/local/django/celery/worker/start new file mode 100644 index 0000000..4ddcfa1 --- /dev/null +++ b/compose/local/django/celery/worker/start @@ -0,0 +1,7 @@ +#!/bin/bash + +set -o errexit +set -o nounset + + +watchfiles celery.__main__.main --args '-A config.celery_app worker -l INFO' diff --git a/compose/local/django/start b/compose/local/django/start new file mode 100644 index 0000000..f076ee5 --- /dev/null +++ b/compose/local/django/start @@ -0,0 +1,9 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python manage.py migrate +python manage.py runserver_plus 0.0.0.0:8000 diff --git a/compose/local/docs/Dockerfile b/compose/local/docs/Dockerfile new file mode 100644 index 0000000..c45d18c --- /dev/null +++ b/compose/local/docs/Dockerfile @@ -0,0 +1,64 @@ +ARG PYTHON_VERSION=3.10-slim-bullseye + +# 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 + +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update && apt-get install --no-install-recommends -y \ + # dependencies for building Python packages + build-essential \ + # psycopg2 dependencies + libpq-dev \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# Requirements are installed here to ensure they will be cached. +COPY ./requirements /requirements + +# create python dependency wheels +RUN pip wheel --no-cache-dir --wheel-dir /usr/src/app/wheels \ + -r /requirements/local.txt -r /requirements/production.txt \ + && rm -rf /requirements + + +# Python 'run' stage +FROM python as python-run-stage + +ARG BUILD_ENVIRONMENT +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apt-get update && apt-get install --no-install-recommends -y \ + # To run the Makefile + make \ + # psycopg2 dependencies + libpq-dev \ + # Translations dependencies + gettext \ + # Uncomment below lines to enable Sphinx output to latex and pdf + # texlive-latex-recommended \ + # texlive-fonts-recommended \ + # texlive-latex-extra \ + # latexmk \ + # cleaning up unused files + && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ + && rm -rf /var/lib/apt/lists/* + +# copy python dependency wheels from python-build-stage +COPY --from=python-build-stage /usr/src/app/wheels /wheels + +# use wheels to install python dependencies +RUN pip install --no-cache /wheels/* \ + && rm -rf /wheels + +COPY ./compose/local/docs/start /start-docs +RUN sed -i 's/\r$//g' /start-docs +RUN chmod +x /start-docs + +WORKDIR /docs diff --git a/compose/local/docs/start b/compose/local/docs/start new file mode 100644 index 0000000..fd2e0de --- /dev/null +++ b/compose/local/docs/start @@ -0,0 +1,7 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + +make livehtml diff --git a/compose/production/django/Dockerfile b/compose/production/django/Dockerfile new file mode 100644 index 0000000..59378f2 --- /dev/null +++ b/compose/production/django/Dockerfile @@ -0,0 +1,94 @@ +ARG PYTHON_VERSION=3.10-slim-bullseye + + + +# 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 \ + # 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 --chown=django:django ./compose/production/django/celery/worker/start /start-celeryworker +RUN sed -i 's/\r$//g' /start-celeryworker +RUN chmod +x /start-celeryworker + + +COPY --chown=django:django ./compose/production/django/celery/beat/start /start-celerybeat +RUN sed -i 's/\r$//g' /start-celerybeat +RUN chmod +x /start-celerybeat + + +COPY ./compose/production/django/celery/flower/start /start-flower +RUN sed -i 's/\r$//g' /start-flower +RUN chmod +x /start-flower + + +# 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/celery/beat/start b/compose/production/django/celery/beat/start new file mode 100644 index 0000000..42ddca9 --- /dev/null +++ b/compose/production/django/celery/beat/start @@ -0,0 +1,8 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +exec celery -A config.celery_app beat -l INFO diff --git a/compose/production/django/celery/flower/start b/compose/production/django/celery/flower/start new file mode 100644 index 0000000..4180d67 --- /dev/null +++ b/compose/production/django/celery/flower/start @@ -0,0 +1,11 @@ +#!/bin/bash + +set -o errexit +set -o nounset + + +exec celery \ + -A config.celery_app \ + -b "${CELERY_BROKER_URL}" \ + flower \ + --basic_auth="${CELERY_FLOWER_USER}:${CELERY_FLOWER_PASSWORD}" diff --git a/compose/production/django/celery/worker/start b/compose/production/django/celery/worker/start new file mode 100644 index 0000000..af0c8f7 --- /dev/null +++ b/compose/production/django/celery/worker/start @@ -0,0 +1,8 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +exec celery -A config.celery_app worker -l INFO diff --git a/compose/production/django/entrypoint b/compose/production/django/entrypoint new file mode 100644 index 0000000..62895e9 --- /dev/null +++ b/compose/production/django/entrypoint @@ -0,0 +1,49 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + + +# N.B. If only .env files supported variable expansion... +export CELERY_BROKER_URL="${REDIS_URL}" + + +if [ -z "${POSTGRES_USER}" ]; then + base_postgres_image_default_user='postgres' + export POSTGRES_USER="${base_postgres_image_default_user}" +fi +export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}" + +python << END +import sys +import time + +import psycopg2 + +suggest_unrecoverable_after = 30 +start = time.time() + +while True: + try: + psycopg2.connect( + dbname="${POSTGRES_DB}", + user="${POSTGRES_USER}", + password="${POSTGRES_PASSWORD}", + host="${POSTGRES_HOST}", + port="${POSTGRES_PORT}", + ) + break + except psycopg2.OperationalError as error: + sys.stderr.write("Waiting for PostgreSQL to become available...\n") + + if time.time() - start > suggest_unrecoverable_after: + sys.stderr.write(" This is taking longer than expected. The following exception may be indicative of an unrecoverable error: '{}'\n".format(error)) + + time.sleep(1) +END + +>&2 echo 'PostgreSQL is available' + +exec "$@" diff --git a/compose/production/django/start b/compose/production/django/start new file mode 100644 index 0000000..7b10be1 --- /dev/null +++ b/compose/production/django/start @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset + + +python /app/manage.py collectstatic --noinput + +/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app diff --git a/compose/production/postgres/Dockerfile b/compose/production/postgres/Dockerfile new file mode 100644 index 0000000..101aa81 --- /dev/null +++ b/compose/production/postgres/Dockerfile @@ -0,0 +1,6 @@ +FROM postgres:14 + +COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance +RUN chmod +x /usr/local/bin/maintenance/* +RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ + && rmdir /usr/local/bin/maintenance diff --git a/compose/production/postgres/maintenance/_sourced/constants.sh b/compose/production/postgres/maintenance/_sourced/constants.sh new file mode 100644 index 0000000..6ca4f0c --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/constants.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + + +BACKUP_DIR_PATH='/backups' +BACKUP_FILE_PREFIX='backup' diff --git a/compose/production/postgres/maintenance/_sourced/countdown.sh b/compose/production/postgres/maintenance/_sourced/countdown.sh new file mode 100644 index 0000000..e6cbfb6 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/countdown.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + + +countdown() { + declare desc="A simple countdown. Source: https://superuser.com/a/611582" + local seconds="${1}" + local d=$(($(date +%s) + "${seconds}")) + while [ "$d" -ge `date +%s` ]; do + echo -ne "$(date -u --date @$(($d - `date +%s`)) +%H:%M:%S)\r"; + sleep 0.1 + done +} diff --git a/compose/production/postgres/maintenance/_sourced/messages.sh b/compose/production/postgres/maintenance/_sourced/messages.sh new file mode 100644 index 0000000..f6be756 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/messages.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + + +message_newline() { + echo +} + +message_debug() +{ + echo -e "DEBUG: ${@}" +} + +message_welcome() +{ + echo -e "\e[1m${@}\e[0m" +} + +message_warning() +{ + echo -e "\e[33mWARNING\e[0m: ${@}" +} + +message_error() +{ + echo -e "\e[31mERROR\e[0m: ${@}" +} + +message_info() +{ + echo -e "\e[37mINFO\e[0m: ${@}" +} + +message_suggestion() +{ + echo -e "\e[33mSUGGESTION\e[0m: ${@}" +} + +message_success() +{ + echo -e "\e[32mSUCCESS\e[0m: ${@}" +} diff --git a/compose/production/postgres/maintenance/_sourced/yes_no.sh b/compose/production/postgres/maintenance/_sourced/yes_no.sh new file mode 100644 index 0000000..fd9cae1 --- /dev/null +++ b/compose/production/postgres/maintenance/_sourced/yes_no.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + + +yes_no() { + declare desc="Prompt for confirmation. \$\"\{1\}\": confirmation message." + local arg1="${1}" + + local response= + read -r -p "${arg1} (y/[n])? " response + if [[ "${response}" =~ ^[Yy]$ ]] + then + exit 0 + else + exit 1 + fi +} diff --git a/compose/production/postgres/maintenance/backup b/compose/production/postgres/maintenance/backup new file mode 100644 index 0000000..ee0c9d6 --- /dev/null +++ b/compose/production/postgres/maintenance/backup @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + + +### Create a database backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backup + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "Backing up the '${POSTGRES_DB}' database..." + + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Backing up as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +backup_filename="${BACKUP_FILE_PREFIX}_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz" +pg_dump | gzip > "${BACKUP_DIR_PATH}/${backup_filename}" + + +message_success "'${POSTGRES_DB}' database backup '${backup_filename}' has been created and placed in '${BACKUP_DIR_PATH}'." diff --git a/compose/production/postgres/maintenance/backups b/compose/production/postgres/maintenance/backups new file mode 100644 index 0000000..0484ccf --- /dev/null +++ b/compose/production/postgres/maintenance/backups @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + + +### View backups. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres backups + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +message_welcome "These are the backups you have got:" + +ls -lht "${BACKUP_DIR_PATH}" diff --git a/compose/production/postgres/maintenance/restore b/compose/production/postgres/maintenance/restore new file mode 100644 index 0000000..9661ca7 --- /dev/null +++ b/compose/production/postgres/maintenance/restore @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + + +### Restore database from a backup. +### +### Parameters: +### <1> filename of an existing backup. +### +### Usage: +### $ docker-compose -f .yml (exec |run --rm) postgres restore <1> + + +set -o errexit +set -o pipefail +set -o nounset + + +working_dir="$(dirname ${0})" +source "${working_dir}/_sourced/constants.sh" +source "${working_dir}/_sourced/messages.sh" + + +if [[ -z ${1+x} ]]; then + message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again." + exit 1 +fi +backup_filename="${BACKUP_DIR_PATH}/${1}" +if [[ ! -f "${backup_filename}" ]]; then + message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again." + exit 1 +fi + +message_welcome "Restoring the '${POSTGRES_DB}' database from the '${backup_filename}' backup..." + +if [[ "${POSTGRES_USER}" == "postgres" ]]; then + message_error "Restoring as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again." + exit 1 +fi + +export PGHOST="${POSTGRES_HOST}" +export PGPORT="${POSTGRES_PORT}" +export PGUSER="${POSTGRES_USER}" +export PGPASSWORD="${POSTGRES_PASSWORD}" +export PGDATABASE="${POSTGRES_DB}" + +message_info "Dropping the database..." +dropdb "${PGDATABASE}" + +message_info "Creating a new database..." +createdb --owner="${POSTGRES_USER}" + +message_info "Applying the backup to the new database..." +gunzip -c "${backup_filename}" | psql "${POSTGRES_DB}" + +message_success "The '${POSTGRES_DB}' database has been restored from the '${backup_filename}' backup." diff --git a/compose/production/traefik/Dockerfile b/compose/production/traefik/Dockerfile new file mode 100644 index 0000000..aa87905 --- /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 0000000..1005d93 --- /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: "alexandr.d.karpov@gmail.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(`akarpov.ru`) || Host(`www.akarpov.ru`)" + entryPoints: + - web-secure + middlewares: + - csrf + service: django + tls: + # https://docs.traefik.io/master/routing/routers/#certresolver + certResolver: letsencrypt + + flower-secure-router: + rule: "Host(`akarpov.ru`)" + 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 0000000..10f5014 --- /dev/null +++ b/config/__init__.py @@ -0,0 +1,5 @@ +# This will make sure the app is always imported when +# Django starts so that shared_task will use this app. +from .celery_app import app as celery_app + +__all__ = ("celery_app",) diff --git a/config/api_router.py b/config/api_router.py new file mode 100644 index 0000000..5b63ed2 --- /dev/null +++ b/config/api_router.py @@ -0,0 +1,101 @@ +from django.urls import include, path + +from akarpov.blog.api.views import ( + CreateDeleteCommentRateApiView, + CreateDeletePostRating, + CreatePostApiView, + GetUpdateDeletePostApiView, + ListCreateCommentApiView, + ListPostsApiView, + RetrieveUpdateDeleteCommentApiView, +) +from akarpov.users.api.views import ( + TokenObtainPairView, + TokenRefreshView, + UserEmailValidationViewSet, + UserListViewSet, + UserRegisterViewSet, + UserRetireUpdateSelfViewSet, + UserRetrieveIdViewSet, + UserRetrieveViewSet, +) + +urlpatterns_v1 = [ + path( + "auth/", + include( + [ + path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), + path("refresh/", TokenRefreshView.as_view(), name="token_refresh"), + path( + "register/", UserRegisterViewSet.as_view(), name="user_register_api" + ), + path( + "prove_email/", + UserEmailValidationViewSet.as_view(), + name="user_email_validation_api", + ), + ] + ), + ), + path( + "users/", + include( + [ + path("", UserListViewSet.as_view(), name="user_list_api"), + path( + "self/", + UserRetireUpdateSelfViewSet.as_view(), + name="user_get_update_delete_self_api", + ), + path( + "id/", + UserRetrieveIdViewSet.as_view(), + name="user_retrieve_id_api", + ), + path( + "", + UserRetrieveViewSet.as_view(), + name="user_retrieve_username_api", + ), + ] + ), + ), + # blog + path( + "blog/", + include( + [ + path("", ListPostsApiView.as_view(), name="list_all_posts_api"), + path("create/", CreatePostApiView.as_view(), name="create_post_api"), + path( + "", + GetUpdateDeletePostApiView.as_view(), + name="retrieve_update_delete_post_api", + ), + path( + "/rating/", + CreateDeletePostRating.as_view(), + name="create_delete_post_rating_api", + ), + path( + "/comments/", + ListCreateCommentApiView.as_view(), + name="list_create_comment_api", + ), + path( + "comments/", + RetrieveUpdateDeleteCommentApiView.as_view(), + name="list_create_comment_api", + ), + path( + "comments//vote_up/", + CreateDeleteCommentRateApiView.as_view(), + name="list_create_comment_api", + ), + ] + ), + ), +] + +urlpatterns = [path("v1/", include(urlpatterns_v1))] diff --git a/config/celery_app.py b/config/celery_app.py new file mode 100644 index 0000000..3521c84 --- /dev/null +++ b/config/celery_app.py @@ -0,0 +1,17 @@ +import os + +from celery import Celery + +# set the default Django settings module for the 'celery' program. +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") + +app = Celery("akarpov") + +# Using a string here means the worker doesn't have to serialize +# the configuration object to child processes. +# - namespace='CELERY' means all celery-related configuration keys +# should have a `CELERY_` prefix. +app.config_from_object("django.conf:settings", namespace="CELERY") + +# Load task modules from all registered Django app configs. +app.autodiscover_tasks() diff --git a/config/settings/__init__.py b/config/settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings/base.py b/config/settings/base.py new file mode 100644 index 0000000..5e69f5c --- /dev/null +++ b/config/settings/base.py @@ -0,0 +1,340 @@ +""" +Base settings to build other settings files upon. +""" +from pathlib import Path + +import environ + +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent +# akarpov/ +APPS_DIR = ROOT_DIR / "akarpov" +env = environ.Env() + +READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=True) +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 = "Europe/Moscow" +# 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 +# https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DEFAULT_AUTO_FIELD +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# URLS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf +ROOT_URLCONF = "config.urls" +# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application +WSGI_APPLICATION = "config.wsgi.application" + +# APPS +# ------------------------------------------------------------------------------ +DJANGO_APPS = [ + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.sites", + "django.contrib.messages", + "django.contrib.staticfiles", + # "django.contrib.humanize", # Handy template tags + "django.contrib.admin", + "django.forms", +] +THIRD_PARTY_APPS = [ + "crispy_forms", + "crispy_bootstrap5", + "allauth", + "allauth.account", + "allauth.socialaccount", + "django_celery_beat", + "rest_framework", + "corsheaders", + "drf_spectacular", +] + +HEALTH_CHECKS = [ + "health_check", # required + "health_check.db", # stock Django health checkers + "health_check.cache", + "health_check.storage", + # 'health_check.contrib.celery', + # 'health_check.contrib.celery_ping', + "health_check.contrib.migrations", + "health_check.contrib.psutil", # disk and memory utilization + "health_check.contrib.redis", +] + +LOCAL_APPS = [ + "akarpov.blog.apps.BlogConfig", + "akarpov.users.apps.UsersConfig", + # Your stuff: custom apps go here +] +# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps +INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + HEALTH_CHECKS + LOCAL_APPS + +# MIGRATIONS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules +MIGRATION_MODULES = {"sites": "akarpov.contrib.sites.migrations"} + +# AUTHENTICATION +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends +AUTHENTICATION_BACKENDS = [ + "django.contrib.auth.backends.ModelBackend", + "allauth.account.auth_backends.AuthenticationBackend", +] +# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model +AUTH_USER_MODEL = "users.User" +# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url +LOGIN_REDIRECT_URL = "users:redirect" +# https://docs.djangoproject.com/en/dev/ref/settings/#login-url +LOGIN_URL = "account_login" + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = [ + # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django + "django.contrib.auth.hashers.Argon2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", + "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", +] +# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + }, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + +# MIDDLEWARE +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#middleware +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "corsheaders.middleware.CorsMiddleware", + "whitenoise.middleware.WhiteNoiseMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.locale.LocaleMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.common.BrokenLinkEmailsMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", +] + +# STATIC +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#static-root +STATIC_ROOT = str(ROOT_DIR / "staticfiles") +# https://docs.djangoproject.com/en/dev/ref/settings/#static-url +STATIC_URL = "/static/" +# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS +STATICFILES_DIRS = [str(APPS_DIR / "static")] +# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders +STATICFILES_FINDERS = [ + "django.contrib.staticfiles.finders.FileSystemFinder", + "django.contrib.staticfiles.finders.AppDirectoriesFinder", +] + +# MEDIA +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#media-root +MEDIA_ROOT = str(APPS_DIR / "media") +# https://docs.djangoproject.com/en/dev/ref/settings/#media-url +MEDIA_URL = "/media/" + +# TEMPLATES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#templates +TEMPLATES = [ + { + # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND + "BACKEND": "django.template.backends.django.DjangoTemplates", + # https://docs.djangoproject.com/en/dev/ref/settings/#dirs + "DIRS": [str(APPS_DIR / "templates")], + # https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs + "APP_DIRS": True, + "OPTIONS": { + # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.template.context_processors.i18n", + "django.template.context_processors.media", + "django.template.context_processors.static", + "django.template.context_processors.tz", + "django.contrib.messages.context_processors.messages", + "akarpov.users.context_processors.allauth_settings", + ], + }, + } +] + +# https://docs.djangoproject.com/en/dev/ref/settings/#form-renderer +FORM_RENDERER = "django.forms.renderers.TemplatesSetting" + +# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs +CRISPY_TEMPLATE_PACK = "bootstrap5" +CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" + +# FIXTURES +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs +FIXTURE_DIRS = (str(APPS_DIR / "fixtures"),) + +# SECURITY +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly +SESSION_COOKIE_HTTPONLY = True +# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly +CSRF_COOKIE_HTTPONLY = True +# https://docs.djangoproject.com/en/dev/ref/settings/#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 = [("""sanspie""", "alexandr.d.karpov@gmail.com")] +# https://docs.djangoproject.com/en/dev/ref/settings/#managers +MANAGERS = ADMINS + +# LOGGING +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#logging +# See https://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s " + "%(process)d %(thread)d %(message)s" + } + }, + "handlers": { + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + } + }, + "root": {"level": "INFO", "handlers": ["console"]}, +} + +# Celery +# ------------------------------------------------------------------------------ +if USE_TZ: + # https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-timezone + CELERY_TIMEZONE = TIME_ZONE +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-broker_url +CELERY_BROKER_URL = env("CELERY_BROKER_URL") +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-result_backend +CELERY_RESULT_BACKEND = CELERY_BROKER_URL +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-extended +CELERY_RESULT_EXTENDED = True +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-accept_content +CELERY_ACCEPT_CONTENT = ["json"] +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-task_serializer +CELERY_TASK_SERIALIZER = "json" +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-result_serializer +CELERY_RESULT_SERIALIZER = "json" +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-time-limit +CELERY_TASK_TIME_LIMIT = 5 * 60 +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-soft-time-limit +CELERY_TASK_SOFT_TIME_LIMIT = 60 +# https://docs.celeryq.dev/en/stable/userguide/configuration.html#beat-scheduler +CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" +# django-allauth +# ------------------------------------------------------------------------------ +ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_AUTHENTICATION_METHOD = "username" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_REQUIRED = True +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_EMAIL_VERIFICATION = "mandatory" +# https://django-allauth.readthedocs.io/en/latest/configuration.html +ACCOUNT_ADAPTER = "akarpov.users.adapters.AccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/forms.html +ACCOUNT_FORMS = {"signup": "akarpov.users.forms.UserSignupForm"} +# https://django-allauth.readthedocs.io/en/latest/configuration.html +SOCIALACCOUNT_ADAPTER = "akarpov.users.adapters.SocialAccountAdapter" +# https://django-allauth.readthedocs.io/en/latest/forms.html +SOCIALACCOUNT_FORMS = {"signup": "akarpov.users.forms.UserSocialSignupForm"} + +# django-rest-framework +# ------------------------------------------------------------------------------- +# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/ +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": ( + "rest_framework_simplejwt.authentication.JWTAuthentication", + ), + "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), + "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", +} +# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup +CORS_URLS_REGEX = r"^/api/.*$" + +# By Default swagger ui is available only to admin user(s). You can change permission classes to change that +# See more configuration options at https://drf-spectacular.readthedocs.io/en/latest/settings.html#settings +SPECTACULAR_SETTINGS = { + "TITLE": "akarpov API", + "DESCRIPTION": "Documentation of API endpoints of akarpov", + "VERSION": "1.0.0", + "SCHEMA_PATH_PREFIX": r"/api/v1/", + "SERVE_INCLUDE_SCHEMA": False, + "SERVE_PERMISSIONS": ["rest_framework.permissions.AllowAny"], + "SERVERS": [ + {"url": "http://127.0.0.1:8000", "description": "Local Development server"}, + {"url": "https://akarpov.ru", "description": "Production server"}, + ], +} +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/settings/local.py b/config/settings/local.py new file mode 100644 index 0000000..b0e5cb2 --- /dev/null +++ b/config/settings/local.py @@ -0,0 +1,68 @@ +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="zV4T5BWkBt8sQ3VJSo70hw6XzuAmgXPdJBGQ6quzs53SkvNj4kS1k32U8AHJGE71", +) +# 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 +# Celery +# ------------------------------------------------------------------------------ + +# https://docs.celeryq.dev/en/stable/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 0000000..ed629d7 --- /dev/null +++ b/config/settings/production.py @@ -0,0 +1,164 @@ +import logging + +import sentry_sdk +from sentry_sdk.integrations.celery import CeleryIntegration +from sentry_sdk.integrations.django import DjangoIntegration +from sentry_sdk.integrations.logging import LoggingIntegration +from sentry_sdk.integrations.redis import RedisIntegration + +from .base import * # noqa +from .base import env + +# GENERAL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +SECRET_KEY = env("DJANGO_SECRET_KEY") +# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["akarpov.ru"]) + +# 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 +SECURE_HSTS_SECONDS = 60 +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains +SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( + "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True +) +# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload +SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) +# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff +SECURE_CONTENT_TYPE_NOSNIFF = env.bool( + "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True +) + +# STATIC +# ------------------------ +STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" +# MEDIA +# ------------------------------------------------------------------------------ + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email +DEFAULT_FROM_EMAIL = env( + "DJANGO_DEFAULT_FROM_EMAIL", + default="akarpov ", +) +# 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="[akarpov]", +) + +# 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/mailgun/ +EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" +ANYMAIL = { + "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), + "MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"), + "MAILGUN_API_URL": env("MAILGUN_API_URL", default="https://api.mailgun.net/v3"), +} + + +# LOGGING +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#logging +# See https://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. + +LOGGING = { + "version": 1, + "disable_existing_loggers": True, + "formatters": { + "verbose": { + "format": "%(levelname)s %(asctime)s %(module)s " + "%(process)d %(thread)d %(message)s" + } + }, + "handlers": { + "console": { + "level": "DEBUG", + "class": "logging.StreamHandler", + "formatter": "verbose", + } + }, + "root": {"level": "INFO", "handlers": ["console"]}, + "loggers": { + "django.db.backends": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + # Errors logged by the SDK itself + "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, + "django.security.DisallowedHost": { + "level": "ERROR", + "handlers": ["console"], + "propagate": False, + }, + }, +} + +# Sentry +# ------------------------------------------------------------------------------ +SENTRY_DSN = env("SENTRY_DSN") +SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) + +sentry_logging = LoggingIntegration( + level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs + event_level=logging.ERROR, # Send errors as events +) +integrations = [ + sentry_logging, + DjangoIntegration(), + 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), +) diff --git a/config/settings/test.py b/config/settings/test.py new file mode 100644 index 0000000..e5f90c0 --- /dev/null +++ b/config/settings/test.py @@ -0,0 +1,33 @@ +""" +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="EWxnD10dpFwHHunL68M3P9UjVhLIyZeEmCHsRF9Ypzo0rBnStS78ZV6paNadY2EB", +) +# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner +TEST_RUNNER = "django.test.runner.DiscoverRunner" + +# PASSWORDS +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers +PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] + +# EMAIL +# ------------------------------------------------------------------------------ +# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend +EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" + +# DEBUGING FOR TEMPLATES +# ------------------------------------------------------------------------------ +TEMPLATES[0]["OPTIONS"]["debug"] = True # type: ignore # noqa F405 + +# Your stuff... +# ------------------------------------------------------------------------------ diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..a7498c4 --- /dev/null +++ b/config/urls.py @@ -0,0 +1,70 @@ +from django.conf import settings +from django.conf.urls.static import static +from django.contrib import admin +from django.urls import include, path +from django.views import defaults as default_views +from django.views.generic import TemplateView +from drf_spectacular.views import ( + SpectacularAPIView, + SpectacularRedocView, + SpectacularSwaggerView, +) + +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("akarpov.users.urls", namespace="users")), + path("accounts/", include("allauth.urls")), + # Your stuff: custom urls includes go here +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +# API URLS +urlpatterns += [ + # API base url + path("api/", include("config.api_router")), + path("health/", include("health_check.urls")), + # DRF auth token + path("api_schema/", SpectacularAPIView.as_view(), name="api-schema"), + path("api_rschema/", SpectacularAPIView.as_view(), name="api-redoc-schema"), + path( + "api/docs/", + SpectacularSwaggerView.as_view(url_name="api-schema"), + name="home", + ), + path( + "api/redoc/", + SpectacularRedocView.as_view(url_name="api-redoc-schema"), + name="home", + ), +] + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + path( + "400/", + default_views.bad_request, + kwargs={"exception": Exception("Bad Request!")}, + ), + path( + "403/", + default_views.permission_denied, + kwargs={"exception": Exception("Permission Denied")}, + ), + path( + "404/", + default_views.page_not_found, + kwargs={"exception": Exception("Page not Found")}, + ), + path("500/", default_views.server_error), + ] + if "debug_toolbar" in settings.INSTALLED_APPS: + import debug_toolbar + + urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..6dfb880 --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,38 @@ +""" +WSGI config for akarpov 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 +# akarpov directory. +ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent +sys.path.append(str(ROOT_DIR / "akarpov")) +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +application = get_wsgi_application() +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..6957700 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,29 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = ./_build +APP = /app + +.PHONY: help livehtml apidocs Makefile + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c . + +# Build, watch and serve docs with live reload +livehtml: + sphinx-autobuild -b html --host 0.0.0.0 --port 9000 --watch $(APP) -c . $(SOURCEDIR) $(BUILDDIR)/html + +# Outputs rst files from django application code +apidocs: + sphinx-apidoc -o $(SOURCEDIR)/api $(APP) + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c . diff --git a/docs/__init__.py b/docs/__init__.py new file mode 100644 index 0000000..8772c82 --- /dev/null +++ b/docs/__init__.py @@ -0,0 +1 @@ +# Included so that Django's startproject comment runs against the docs directory diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..a459553 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,63 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +import os +import sys +import django + +if os.getenv("READTHEDOCS", default=False) == "True": + sys.path.insert(0, os.path.abspath("..")) + os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" + os.environ["USE_DOCKER"] = "no" +else: + sys.path.insert(0, os.path.abspath("/app")) +os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db" +os.environ["CELERY_BROKER_URL"] = os.getenv("REDIS_URL", "redis://redis:6379") +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") +django.setup() + +# -- Project information ----------------------------------------------------- + +project = "akarpov" +copyright = """2022, sanspie""" +author = "sanspie" + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", +] + +# Add any paths that contain templates here, relative to this directory. +# templates_path = ["_templates"] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "alabaster" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ["_static"] diff --git a/docs/howto.rst b/docs/howto.rst new file mode 100644 index 0000000..0bf5fdc --- /dev/null +++ b/docs/howto.rst @@ -0,0 +1,38 @@ +How To - Project Documentation +====================================================================== + +Get Started +---------------------------------------------------------------------- + +Documentation can be written as rst files in `akarpov/docs`. + + +To build and serve docs, use the commands:: + + docker-compose -f local.yml up docs + + + +Changes to files in `docs/_source` will be picked up and reloaded automatically. + +`Sphinx `_ is the tool used to build documentation. + +Docstrings to Documentation +---------------------------------------------------------------------- + +The sphinx extension `apidoc `_ is used to automatically document code using signatures and docstrings. + +Numpy or Google style docstrings will be picked up from project files and available for documentation. See the `Napoleon `_ extension for details. + +For an in-use example, see the `page source <_sources/users.rst.txt>`_ for :ref:`users`. + +To compile all docstrings automatically into documentation source files, use the command: + :: + + make apidocs + + +This can be done in the docker container: + :: + + docker run --rm docs make apidocs diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..b79c076 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,24 @@ +.. akarpov documentation master file, created by + sphinx-quickstart. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to akarpov's documentation! +====================================================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + howto + pycharm/configuration + users + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..aa01c33 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,46 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build -c . +) +set SOURCEDIR=_source +set BUILDDIR=_build +set APP=..\akarpov + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.Install sphinx-autobuild for live serving. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -b %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:livehtml +sphinx-autobuild -b html --open-browser -p 9000 --watch %APP% -c . %SOURCEDIR% %BUILDDIR%/html +GOTO :EOF + +:apidocs +sphinx-apidoc -o %SOURCEDIR%/api %APP% +GOTO :EOF + +:help +%SPHINXBUILD% -b help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/pycharm/configuration.rst b/docs/pycharm/configuration.rst new file mode 100644 index 0000000..6e79af7 --- /dev/null +++ b/docs/pycharm/configuration.rst @@ -0,0 +1,70 @@ +Docker Remote Debugging +======================= + +To connect to python remote interpreter inside docker, you have to make sure first, that Pycharm is aware of your docker. + +Go to *Settings > Build, Execution, Deployment > Docker*. If you are on linux, you can use docker directly using its socket `unix:///var/run/docker.sock`, if you are on Windows or Mac, make sure that you have docker-machine installed, then you can simply *Import credentials from Docker Machine*. + +.. image:: images/1.png + +Configure Remote Python Interpreter +----------------------------------- + +This repository comes with already prepared "Run/Debug Configurations" for docker. + +.. image:: images/2.png + +But as you can see, at the beginning there is something wrong with them. They have red X on django icon, and they cannot be used, without configuring remote python interpreter. To do that, you have to go to *Settings > Build, Execution, Deployment* first. + + +Next, you have to add new remote python interpreter, based on already tested deployment settings. Go to *Settings > Project > Project Interpreter*. Click on the cog icon, and click *Add Remote*. + +.. image:: images/3.png + +Switch to *Docker Compose* and select `local.yml` file from directory of your project, next set *Service name* to `django` + +.. image:: images/4.png + +Having that, click *OK*. Close *Settings* panel, and wait few seconds... + +.. image:: images/7.png + +After few seconds, all *Run/Debug Configurations* should be ready to use. + +.. image:: images/8.png + +**Things you can do with provided configuration**: + +* run and debug python code + +.. image:: images/f1.png + +* run and debug tests + +.. image:: images/f2.png +.. image:: images/f3.png + +* run and debug migrations or different django management commands + +.. image:: images/f4.png + +* and many others.. + +Known issues +------------ + +* Pycharm hangs on "Connecting to Debugger" + +.. image:: images/issue1.png + +This might be fault of your firewall. Take a look on this ticket - https://youtrack.jetbrains.com/issue/PY-18913 + +* Modified files in `.idea` directory + +Most of the files from `.idea/` were added to `.gitignore` with a few exceptions, which were made, to provide "ready to go" configuration. After adding remote interpreter some of these files are altered by PyCharm: + +.. image:: images/issue2.png + +In theory you can remove them from repository, but then, other people will lose a ability to initialize a project from provided configurations as you did. To get rid of this annoying state, you can run command:: + + $ git update-index --assume-unchanged akarpov.iml diff --git a/docs/pycharm/images/1.png b/docs/pycharm/images/1.png new file mode 100644 index 0000000..06908a1 Binary files /dev/null and b/docs/pycharm/images/1.png differ diff --git a/docs/pycharm/images/2.png b/docs/pycharm/images/2.png new file mode 100644 index 0000000..1fb8cf1 Binary files /dev/null and b/docs/pycharm/images/2.png differ diff --git a/docs/pycharm/images/3.png b/docs/pycharm/images/3.png new file mode 100644 index 0000000..32c9335 Binary files /dev/null and b/docs/pycharm/images/3.png differ diff --git a/docs/pycharm/images/4.png b/docs/pycharm/images/4.png new file mode 100644 index 0000000..cf07f9d Binary files /dev/null and b/docs/pycharm/images/4.png differ diff --git a/docs/pycharm/images/7.png b/docs/pycharm/images/7.png new file mode 100644 index 0000000..4f8807e Binary files /dev/null and b/docs/pycharm/images/7.png differ diff --git a/docs/pycharm/images/8.png b/docs/pycharm/images/8.png new file mode 100644 index 0000000..05946f2 Binary files /dev/null and b/docs/pycharm/images/8.png differ diff --git a/docs/pycharm/images/f1.png b/docs/pycharm/images/f1.png new file mode 100644 index 0000000..2d8c4b6 Binary files /dev/null and b/docs/pycharm/images/f1.png differ diff --git a/docs/pycharm/images/f2.png b/docs/pycharm/images/f2.png new file mode 100644 index 0000000..b123a47 Binary files /dev/null and b/docs/pycharm/images/f2.png differ diff --git a/docs/pycharm/images/f3.png b/docs/pycharm/images/f3.png new file mode 100644 index 0000000..713ab54 Binary files /dev/null and b/docs/pycharm/images/f3.png differ diff --git a/docs/pycharm/images/f4.png b/docs/pycharm/images/f4.png new file mode 100644 index 0000000..11668ec Binary files /dev/null and b/docs/pycharm/images/f4.png differ diff --git a/docs/pycharm/images/issue1.png b/docs/pycharm/images/issue1.png new file mode 100644 index 0000000..1bb68ee Binary files /dev/null and b/docs/pycharm/images/issue1.png differ diff --git a/docs/pycharm/images/issue2.png b/docs/pycharm/images/issue2.png new file mode 100644 index 0000000..174f6fd Binary files /dev/null and b/docs/pycharm/images/issue2.png differ diff --git a/docs/users.rst b/docs/users.rst new file mode 100644 index 0000000..8ce7fb9 --- /dev/null +++ b/docs/users.rst @@ -0,0 +1,15 @@ + .. _users: + +Users +====================================================================== + +Starting a new project, it’s highly recommended to set up a custom user model, +even if the default User model is sufficient for you. + +This model behaves identically to the default user model, +but you’ll be able to customize it in the future if the need arises. + +.. automodule:: akarpov.users.models + :members: + :noindex: + diff --git a/local.yml b/local.yml new file mode 100644 index 0000000..dd0c6c8 --- /dev/null +++ b/local.yml @@ -0,0 +1,95 @@ +version: '3' + +volumes: + akarpov_local_postgres_data: {} + akarpov_local_postgres_data_backups: {} + +services: + django: &django + build: + context: . + dockerfile: ./compose/local/django/Dockerfile + image: akarpov_local_django + container_name: akarpov_local_django + platform: linux/x86_64 + depends_on: + - postgres + - redis + - mailhog + volumes: + - .:/app:z + env_file: + - ./.envs/.local/.django + - ./.envs/.local/.postgres + ports: + - "8000:8000" + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: akarpov_production_postgres + container_name: akarpov_local_postgres + volumes: + - akarpov_local_postgres_data:/var/lib/postgresql/data:Z + - akarpov_local_postgres_data_backups:/backups:z + env_file: + - ./.envs/.local/.postgres + + docs: + image: akarpov_local_docs + container_name: akarpov_local_docs + platform: linux/x86_64 + build: + context: . + dockerfile: ./compose/local/docs/Dockerfile + env_file: + - ./.envs/.local/.django + volumes: + - ./docs:/docs:z + - ./config:/app/config:z + - ./akarpov:/app/akarpov:z + ports: + - "9000:9000" + command: /start-docs + + mailhog: + image: mailhog/mailhog:v1.0.0 + container_name: akarpov_local_mailhog + ports: + - "8025:8025" + + redis: + image: redis:6 + container_name: akarpov_local_redis + + celeryworker: + <<: *django + image: akarpov_local_celeryworker + container_name: akarpov_local_celeryworker + depends_on: + - redis + - postgres + - mailhog + ports: [] + command: /start-celeryworker + + celerybeat: + <<: *django + image: akarpov_local_celerybeat + container_name: akarpov_local_celerybeat + depends_on: + - redis + - postgres + - mailhog + ports: [] + command: /start-celerybeat + + flower: + <<: *django + image: akarpov_local_flower + container_name: akarpov_local_flower + ports: + - "5555:5555" + command: /start-flower diff --git a/locale/README.rst b/locale/README.rst new file mode 100644 index 0000000..c2f1dcd --- /dev/null +++ b/locale/README.rst @@ -0,0 +1,6 @@ +Translations +============ + +Translations will be placed in this folder when running:: + + python manage.py makemessages diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..dcf38cf --- /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 + # akarpov directory. + current_path = Path(__file__).parent.resolve() + sys.path.append(str(current_path / "akarpov")) + + execute_from_command_line(sys.argv) diff --git a/merge_production_dotenvs_in_dotenv.py b/merge_production_dotenvs_in_dotenv.py new file mode 100644 index 0000000..d702a5f --- /dev/null +++ b/merge_production_dotenvs_in_dotenv.py @@ -0,0 +1,67 @@ +import os +from collections.abc import Sequence +from pathlib import Path + +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) 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 = f".service{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) 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 0000000..63dc0c7 --- /dev/null +++ b/production.yml @@ -0,0 +1,64 @@ +version: '3' + +volumes: + production_postgres_data: {} + production_postgres_data_backups: {} + production_traefik: {} + +services: + django: &django + build: + context: . + dockerfile: ./compose/production/django/Dockerfile + image: akarpov_production_django + platform: linux/x86_64 + depends_on: + - postgres + - redis + env_file: + - ./.envs/.production/.django + - ./.envs/.production/.postgres + command: /start + + postgres: + build: + context: . + dockerfile: ./compose/production/postgres/Dockerfile + image: akarpov_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: akarpov_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 + + celeryworker: + <<: *django + image: akarpov_production_celeryworker + command: /start-celeryworker + + celerybeat: + <<: *django + image: akarpov_production_celerybeat + command: /start-celerybeat + + flower: + <<: *django + image: akarpov_production_flower + command: /start-flower diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..c2b3a23 --- /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 0000000..e85007c --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,30 @@ +pytz==2022.6 # https://github.com/stub42/pytz +python-slugify==6.1.2 # https://github.com/un33k/python-slugify +Pillow==9.3.0 # https://github.com/python-pillow/Pillow +argon2-cffi==21.3.0 # https://github.com/hynek/argon2_cffi +whitenoise==6.2.0 # https://github.com/evansd/whitenoise +redis==4.3.4 # https://github.com/redis/redis-py +hiredis==2.0.0 # https://github.com/redis/hiredis-py +celery==5.2.7 # pyup: < 6.0 # https://github.com/celery/celery +django-celery-beat==2.4.0 # https://github.com/celery/django-celery-beat +flower==1.2.0 # https://github.com/mher/flower + +# Django +# ------------------------------------------------------------------------------ +django==4.0.8 # pyup: < 4.1 # https://www.djangoproject.com/ +django-utils-six==2.0 +django-health-check==3.17.0 +django-environ==0.9.0 # https://github.com/joke2k/django-environ +django-model-utils==4.2.0 # https://github.com/jazzband/django-model-utils +django-allauth==0.51.0 # https://github.com/pennersr/django-allauth +django-crispy-forms==1.14.0 # https://github.com/django-crispy-forms/django-crispy-forms +crispy-bootstrap5==0.7 # https://github.com/django-crispy-forms/crispy-bootstrap5 +django-redis==5.2.0 # https://github.com/jazzband/django-redis +# Django REST Framework +djangorestframework==3.14.0 # https://github.com/encode/django-rest-framework +django-cors-headers==3.13.0 # https://github.com/adamchainz/django-cors-headers +# DRF-spectacular for api documentation +drf-spectacular==0.24.2 # https://github.com/tfranzel/drf-spectacular +djangorestframework-simplejwt==5.2.0 + +psutil==5.9.4 diff --git a/requirements/local.txt b/requirements/local.txt new file mode 100644 index 0000000..03a6d16 --- /dev/null +++ b/requirements/local.txt @@ -0,0 +1,38 @@ +-r base.txt + +Werkzeug[watchdog]==2.2.2 # https://github.com/pallets/werkzeug +ipdb==0.13.9 # https://github.com/gotcha/ipdb +psycopg2==2.9.5 # https://github.com/psycopg/psycopg2 +watchfiles==0.18.1 # https://github.com/samuelcolvin/watchfiles + +# Testing +# ------------------------------------------------------------------------------ +mypy==0.982 # https://github.com/python/mypy +pytest==7.2.0 # https://github.com/pytest-dev/pytest +pytest-sugar==0.9.6 # https://github.com/Frozenball/pytest-sugar +django-stubs==1.13.0 +djangorestframework-stubs==1.7.0 + +# Documentation +# ------------------------------------------------------------------------------ +sphinx==5.3.0 # https://github.com/sphinx-doc/sphinx +sphinx-autobuild==2021.3.14 # https://github.com/GaretJax/sphinx-autobuild + +# Code quality +# ------------------------------------------------------------------------------ +flake8==5.0.4 # https://github.com/PyCQA/flake8 +flake8-isort==5.0.0 # https://github.com/gforcada/flake8-isort +coverage==6.5.0 # https://github.com/nedbat/coveragepy +black==22.10.0 # https://github.com/psf/black +pylint-django==2.5.3 # https://github.com/PyCQA/pylint-django +pylint-celery==0.3 # https://github.com/PyCQA/pylint-celery +pre-commit==2.20.0 # https://github.com/pre-commit/pre-commit + +# Django +# ------------------------------------------------------------------------------ +factory-boy==3.2.1 # https://github.com/FactoryBoy/factory_boy + +django-debug-toolbar==3.7.0 # https://github.com/jazzband/django-debug-toolbar +django-extensions==3.2.1 # https://github.com/django-extensions/django-extensions +django-coverage-plugin==2.0.4 # https://github.com/nedbat/django_coverage_plugin +pytest-django==4.5.2 # https://github.com/pytest-dev/pytest-django diff --git a/requirements/production.txt b/requirements/production.txt new file mode 100644 index 0000000..68b6b6d --- /dev/null +++ b/requirements/production.txt @@ -0,0 +1,13 @@ +# PRECAUTION: avoid production dependencies that aren't in development + +-r base.txt + +gunicorn==20.1.0 # https://github.com/benoitc/gunicorn +psycopg2==2.9.5 # https://github.com/psycopg/psycopg2 + +# Django +# ------------------------------------------------------------------------------ +django-anymail[mailgun]==8.6 # https://github.com/anymail/django-anymail + + +sentry_sdk==1.11.0 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b20382a --- /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 = akarpov,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_drf_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 = akarpov/* +omit = *migrations*, *tests* +plugins = + django_coverage_plugin