├── .dockerignore ├── .env.example ├── .github ├── CODEOWNERS ├── semantic.yaml └── workflows │ └── ci-backend.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE.md ├── README.md ├── backend ├── Dockerfile ├── README.md ├── alembic.ini ├── entrypoint.sh ├── pyproject.toml ├── requirements.txt ├── src │ ├── __init__.py │ ├── api │ │ ├── __init__.py │ │ ├── dependencies │ │ │ ├── __init__.py │ │ │ ├── repository.py │ │ │ └── session.py │ │ ├── endpoints.py │ │ └── routes │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ └── authentication.py │ ├── config │ │ ├── __init__.py │ │ ├── events.py │ │ ├── manager.py │ │ └── settings │ │ │ ├── __init__.py │ │ │ ├── base.py │ │ │ ├── development.py │ │ │ ├── environment.py │ │ │ ├── production.py │ │ │ └── staging.py │ ├── main.py │ ├── models │ │ ├── __init__.py │ │ ├── db │ │ │ ├── __init__.py │ │ │ └── account.py │ │ └── schemas │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ ├── base.py │ │ │ └── jwt.py │ ├── repository │ │ ├── __init__.py │ │ ├── base.py │ │ ├── crud │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ └── base.py │ │ ├── database.py │ │ ├── events.py │ │ ├── migrations │ │ │ ├── env.py │ │ │ ├── script.py.mako │ │ │ └── versions │ │ │ │ └── 2022_12_09_1825-60d1844cb5d3_initial_migration_fo_account_table.py │ │ └── table.py │ ├── securities │ │ ├── __init__.py │ │ ├── authorizations │ │ │ ├── __init__.py │ │ │ └── jwt.py │ │ ├── hashing │ │ │ ├── __init__.py │ │ │ ├── hash.py │ │ │ └── password.py │ │ └── verifications │ │ │ ├── __init__.py │ │ │ └── credentials.py │ └── utilities │ │ ├── __init__.py │ │ ├── exceptions │ │ ├── __init__.py │ │ ├── database.py │ │ ├── http │ │ │ ├── __init__.py │ │ │ ├── exc_400.py │ │ │ ├── exc_401.py │ │ │ ├── exc_403.py │ │ │ └── exc_404.py │ │ └── password.py │ │ ├── formatters │ │ ├── datetime_formatter.py │ │ └── field_formatter.py │ │ └── messages │ │ ├── __init__.py │ │ └── exceptions │ │ ├── __init__.py │ │ ├── database.py │ │ └── http │ │ ├── __init__.py │ │ └── exc_details.py └── tests │ ├── __init__.py │ ├── conftest.py │ ├── end_to_end_tests │ └── __init__.py │ ├── integration_tests │ └── __init__.py │ ├── security_tests │ └── __init__.py │ └── unit_tests │ ├── __init__.py │ └── test_src.py ├── codecov.yaml └── docker-compose.yaml /.dockerignore: -------------------------------------------------------------------------------- 1 | .mypy_cache 2 | .pytest_cache 3 | __pycache__ 4 | .coverage 5 | .gitignore 6 | .github 7 | *.md 8 | env 9 | .dockerignore 10 | Dockerfile 11 | Dockerfile.prod 12 | docker-compose.yaml 13 | .eslintrc.js 14 | requirements-build.txt 15 | requirements-lint.txt 16 | requirements-test.txt 17 | requirements-dev.txt 18 | requirements-prod.txt 19 | CONTAINER.md 20 | README.md 21 | node_modules/ 22 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | ENVIRONMENT=DEV 2 | DEBUG=True 3 | BACKEND_SERVER_HOST=127.0.0.1 4 | BACKEND_SERVER_PORT=8000 5 | BACKEND_SERVER_WORKERS=4 6 | 7 | # Database - Postgres 8 | POSTGRES_DB=my_db 9 | POSTGRES_PASSWORD=postgres13240! 10 | POSTGRES_PORT=5432 11 | POSTGRES_SCHEMA=postgresql 12 | POSTGRES_USERNAME=postgres 13 | IS_ALLOWED_CREDENTIALS=True 14 | API_TOKEN=YOUR-API-TOKEN 15 | AUTH_TOKEN=YOUR-AUTHENTICATION-TOKEN 16 | 17 | # This is the host for Docker Postgres Image in docker-compose.yaml 18 | POSTGRES_HOST=db 19 | POSTGRES_URI={POSTGRES_SCHEMA}://{POSTGRES_USERNAME}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DB} 20 | 21 | # Database - SQLAlchemy 22 | DB_TIMEOUT=5 23 | DB_POOL_SIZE=100 24 | DB_MAX_POOL_CON=80 25 | DB_POOL_OVERFLOW=20 26 | IS_DB_ECHO_LOG=True 27 | IS_DB_EXPIRE_ON_COMMIT=False 28 | IS_DB_FORCE_ROLLBACK=True 29 | 30 | # JWT Token 31 | JWT_SECRET_KEY=YOUR-JWT-SECRET-KEY 32 | JWT_SUBJECT=YOUR-JWT-SUBJECT 33 | JWT_TOKEN_PREFIX=YOUR-TOKEN-PREFIX 34 | JWT_ALGORITHM=HS256 35 | JWT_MIN=60 36 | JWT_HOUR=23 37 | JWT_DAY=6 38 | 39 | # Hash Functions 40 | HASHING_ALGORITHM_LAYER_1=bcrypt 41 | HASHING_ALGORITHM_LAYER_2=argon2 42 | HASHING_SALT=YOUR-RANDOM-SALTY-SALT 43 | 44 | # Codecov (Login to COdecov and get your TOKEN) 45 | CODECOV_TOKEN= 46 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Python related code 2 | *.py @Aeternalis-Ingenium 3 | 4 | # Java Script related code 5 | *.tsx @Aeternalis-Ingenium 6 | *.ts @Aeternalis-Ingenium 7 | *.cjs @Aeternalis-Ingenium 8 | 9 | # HTML & CSS related code 10 | *.html @Aeternalis-Ingenium 11 | *.css @Aeternalis-Ingenium 12 | *.scss @Aeternalis-Ingenium 13 | 14 | # JSON related code 15 | *.json @Aeternalis-Ingenium 16 | 17 | # DevOps related code 18 | *.yml @Aeternalis-Ingenium 19 | *.yaml @Aeternalis-Ingenium 20 | 21 | # Terraform 22 | *.tf @Aeternalis-Ingenium 23 | 24 | # Docker related code 25 | Dockerfile @Aeternalis-Ingenium 26 | *.prod @Aeternalis-Ingenium 27 | -------------------------------------------------------------------------------- /.github/semantic.yaml: -------------------------------------------------------------------------------- 1 | titleAndCommits: true 2 | types: 3 | - feat 4 | - fix 5 | - docs 6 | - style 7 | - refactor 8 | - perf 9 | - test 10 | - build 11 | - ci 12 | - chore 13 | - revert 14 | -------------------------------------------------------------------------------- /.github/workflows/ci-backend.yaml: -------------------------------------------------------------------------------- 1 | name: 'CI - Backend' 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - 'feature/**' 7 | - 'fix/**' 8 | pull_request: 9 | branches: 10 | - 'feature/**' 11 | - 'fix/**' 12 | 13 | jobs: 14 | build: 15 | name: 'Build 🏗' 16 | strategy: 17 | matrix: 18 | os: 19 | - ubuntu-latest 20 | python-version: 21 | - "3.11" 22 | defaults: 23 | run: 24 | working-directory: backend/ 25 | runs-on: ${{ matrix.os }} 26 | steps: 27 | - name: Check repository 28 | uses: actions/checkout@v3 29 | - name: Set up Python ${{ matrix.python-version }} 30 | uses: actions/setup-python@v4 31 | with: 32 | python-version: ${{ matrix.python-version }} 33 | cache: 'pip' 34 | - name: Display Python version 35 | run: python -c "import sys; print(sys.version)" 36 | - name: Install dependencies 37 | run: | 38 | python -m pip install --upgrade pip 39 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 40 | 41 | code-quality: 42 | name: 'Code-Quality 💎' 43 | needs: build 44 | strategy: 45 | matrix: 46 | os: 47 | - ubuntu-latest 48 | python-version: 49 | - "3.11" 50 | defaults: 51 | run: 52 | working-directory: backend/ 53 | runs-on: ${{ matrix.os }} 54 | 55 | steps: 56 | - name: Check repository 57 | uses: actions/checkout@v3 58 | - name: Set up Python ${{ matrix.python-version }} 59 | uses: actions/setup-python@v4 60 | with: 61 | python-version: ${{ matrix.python-version }} 62 | cache: 'pip' 63 | - name: Display Python version 64 | run: python -c "import sys; print(sys.version)" 65 | - name: Install dev dependencies 66 | run: | 67 | python -m pip install --upgrade pip 68 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 69 | - name: Install Dependencies for Linting 70 | run: | 71 | pip install flake8 72 | - name: Lint with Black 73 | uses: psf/black@stable 74 | with: 75 | options: "--exclude=tests/" 76 | src: "backend/src/" 77 | - name: Lint with Isort 78 | run: | 79 | isort . --profile black 80 | - name: Lint with Flake8 81 | run: | 82 | # stop the build if there are Python syntax errors or undefined names 83 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 84 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 85 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 86 | - name: Lint with MyPy 87 | run: | 88 | mypy . --pretty 89 | 90 | test: 91 | name: 'Test 🔬' 92 | needs: build 93 | strategy: 94 | matrix: 95 | os: 96 | - ubuntu-latest 97 | python-version: 98 | - "3.11" 99 | defaults: 100 | run: 101 | working-directory: backend/ 102 | services: 103 | postgres: 104 | image: postgres:14.2-alpine 105 | env: 106 | POSTGRES_DB: ${{ secrets.POSTGRES_DB }} 107 | POSTGRES_USER: ${{ secrets.POSTGRES_USERNAME }} 108 | POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} 109 | ports: 110 | - 5432:5432 111 | options: >- 112 | --health-cmd pg_isready 113 | --health-interval 10s 114 | --health-timeout 5s 115 | --health-retries 5 116 | env: 117 | ENVIRONMENT: ${{ secrets.ENVIRONMENT }} 118 | DEBUG: ${{ secrets.DEBUG }} 119 | POSTGRES_DB: ${{ secrets.POSTGRES_DB }} 120 | POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }} 121 | POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} 122 | POSTGRES_PORT: ${{ secrets.POSTGRES_PORT }} 123 | POSTGRES_SCHEMA: ${{ secrets.POSTGRES_SCHEMA }} 124 | POSTGRES_USERNAME: ${{ secrets.POSTGRES_USERNAME }} 125 | BACKEND_SERVER_HOST: ${{ secrets.BACKEND_SERVER_HOST }} 126 | BACKEND_SERVER_PORT: ${{ secrets.BACKEND_SERVER_PORT }} 127 | BACKEND_SERVER_WORKERS: ${{ secrets.BACKEND_SERVER_WORKERS }} 128 | DB_TIMEOUT: ${{ secrets.DB_TIMEOUT }} 129 | DB_POOL_SIZE: ${{ secrets.DB_POOL_SIZE }} 130 | DB_MAX_POOL_CON: ${{ secrets.DB_MAX_POOL_CON }} 131 | DB_POOL_OVERFLOW: ${{ secrets.DB_POOL_OVERFLOW }} 132 | IS_DB_ECHO_LOG: ${{ secrets.IS_DB_ECHO_LOG }} 133 | IS_DB_EXPIRE_ON_COMMIT: ${{ secrets.IS_DB_EXPIRE_ON_COMMIT }} 134 | IS_DB_FORCE_ROLLBACK: ${{ secrets.IS_DB_FORCE_ROLLBACK }} 135 | IS_ALLOWED_CREDENTIALS: ${{ secrets.IS_ALLOWED_CREDENTIALS }} 136 | API_TOKEN: ${{ secrets.API_TOKEN }} 137 | AUTH_TOKEN: ${{ secrets.AUTH_TOKEN }} 138 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 139 | JWT_SECRET_KEY: ${{ secrets.JWT_SECRET_KEY }} 140 | JWT_SUBJECT: ${{ secrets.JWT_SUBJECT }} 141 | JWT_TOKEN_PREFIX: ${{ secrets.JWT_TOKEN_PREFIX }} 142 | JWT_ALGORITHM: ${{ secrets.JWT_ALGORITHM }} 143 | JWT_MIN: ${{ secrets.JWT_MIN }} 144 | JWT_HOUR: ${{ secrets.JWT_HOUR }} 145 | JWT_DAY: ${{ secrets.JWT_DAY }} 146 | HASHING_ALGORITHM_LAYER_1: ${{ secrets.HASHING_ALGORITHM_LAYER_1 }} 147 | HASHING_ALGORITHM_LAYER_2: ${{ secrets.HASHING_ALGORITHM_LAYER_2 }} 148 | HASHING_SALT: ${{ secrets.HASHING_SALT }} 149 | 150 | runs-on: ${{ matrix.os }} 151 | steps: 152 | - name: Check repository 153 | uses: actions/checkout@v3 154 | - name: Set up Python ${{ matrix.python-version }} 155 | uses: actions/setup-python@v4 156 | with: 157 | python-version: ${{ matrix.python-version }} 158 | cache: 'pip' 159 | - name: Display Python version 160 | run: python -c "import sys; print(sys.version)" 161 | - name: Install dependencies 162 | run: | 163 | python -m pip install --upgrade pip 164 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 165 | - name: Install Dependencies for Testing 166 | run: | 167 | pip install pytest pytest-asyncio pytest pytest-xdist 168 | - name: Test with Pytest-Cov 169 | run: | 170 | pytest --cov --cov-report xml . 171 | - name: Upload coverage to Codecov 172 | uses: codecov/codecov-action@v3 173 | with: 174 | token: ${{ secrets.CODECOV_TOKEN }} 175 | fail_ci_if_error: false 176 | flags: backend_app_tests 177 | name: codecov-umbrella 178 | verbose: true 179 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled, optimized, and DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Builds 7 | /build 8 | */build 9 | *.so 10 | /dist 11 | /lib 12 | /lib-types 13 | /server 14 | 15 | # Cache 16 | .cache 17 | .pytest_cache/ 18 | .webassets-cache 19 | .mypy_cache/ 20 | .mf 21 | .rollup.cache 22 | tsconfig.tsbuildinfo 23 | 24 | # Celery (Python's asynchronous task queues framework) 25 | celerybeat-schedule 26 | 27 | # Code editor (IntelliJ & VSCode) 28 | *.iml 29 | *.ipr 30 | *.iws 31 | .idea/ 32 | .classpath 33 | .project 34 | .settings/ 35 | .vscode/ 36 | !.vscode/extensions.json 37 | .idea 38 | .DS_Store 39 | *.suo 40 | *.ntvs* 41 | *.njsproj 42 | *.sln 43 | *.sw? 44 | 45 | # Database-related 46 | *.sqlite3 47 | *.db 48 | postgres-data 49 | 50 | # Distributions package 51 | .Python 52 | build/ 53 | develop-eggs/ 54 | dist/ 55 | downloads/ 56 | eggs/ 57 | .eggs/ 58 | lib/ 59 | lib64/ 60 | parts/ 61 | sdist/ 62 | var/ 63 | wheels/ 64 | *.egg-info/ 65 | .installed.cfg 66 | *.egg 67 | MANIFEST 68 | .pnpm-store/ 69 | 70 | # Documentation 71 | /site 72 | docs/_build/ 73 | 74 | # Dotenvs 75 | /.pnp 76 | .pnp.js 77 | .env 78 | env/ 79 | ENV/ 80 | env.bak/ 81 | prod_env/ 82 | dev_env/ 83 | test_env/ 84 | test.env 85 | dev.env 86 | prod.env 87 | .DS_Store 88 | .env.local 89 | .env.development.local 90 | .env.test.local 91 | .env.production.local 92 | 93 | # Flutter 94 | *.class 95 | *.lock 96 | *.log 97 | *.pyc 98 | *.swp 99 | .atom/ 100 | .buildlog/ 101 | .history 102 | .svn/ 103 | 104 | # Jupyter Notebook 105 | .ipynb_checkpoints 106 | 107 | # Log Files 108 | logs 109 | *.log 110 | pip-log.txt 111 | npm-debug.log* 112 | yarn-debug.log* 113 | yarn-error.log* 114 | pnpm-debug.log* 115 | lerna-debug.log* 116 | 117 | # Project settings 118 | local_settings.py 119 | instance/ 120 | .spyderproject 121 | .spyproject 122 | .ropeproject 123 | 124 | # PyInstaller 125 | *.manifest 126 | *.spec 127 | 128 | # Rust compiled file 129 | target/ 130 | 131 | # SageMath (Python#s open-source mathematics framework) 132 | *.sage.py 133 | 134 | # Scraping tool 135 | .scrapy 136 | 137 | # Translations: 138 | *.mo 139 | *.pot 140 | 141 | # Tests and coverage reports: 142 | htmlcov/ 143 | .tox/ 144 | .coverage 145 | coverage/** 146 | nosetests.xml 147 | coverage.html 148 | coverage.xml 149 | cov.xml 150 | cov.html 151 | *.cover 152 | .hypothesis/ 153 | 154 | 155 | # Virtual Environment & packages 156 | .python-version 157 | .venv 158 | venv/ 159 | venv.bak/ 160 | node_modules/ 161 | 162 | # Yarn 163 | .yarn/* 164 | !.yarn/releases 165 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_install_hook_types: [pre-commit] 2 | default_stages: [commit, push] 3 | default_language_version: 4 | python: python3.11 5 | ci: 6 | autofix_commit_msg: | 7 | ci(pre-commit): Autofixing commit msg from pre-commit.com hooks 8 | autofix_prs: true 9 | autoupdate_branch: '' 10 | autoupdate_commit_msg: 'ci(autoupdate): Autoupdating commit msg' 11 | autoupdate_schedule: weekly 12 | skip: [] 13 | submodules: false 14 | repos: 15 | - repo: https://github.com/pre-commit/pre-commit-hooks 16 | rev: v4.5.0 17 | hooks: 18 | - id: check-yaml 19 | - id: end-of-file-fixer 20 | - id: trailing-whitespace 21 | files: ^backend/ 22 | - repo: https://github.com/psf/black 23 | rev: 24.3.0 24 | hooks: 25 | - id: black 26 | language_version: python3.11 27 | args: 28 | - --config=backend/pyproject.toml 29 | - repo: https://github.com/pycqa/isort 30 | rev: 5.13.2 31 | hooks: 32 | - id: isort 33 | name: isort (python) 34 | args: 35 | - --settings-path=backend/pyproject.toml 36 | - repo: https://github.com/codespell-project/codespell 37 | rev: v2.2.6 38 | hooks: 39 | - id: codespell 40 | additional_dependencies: 41 | - tomli 42 | - repo: https://github.com/pre-commit/mirrors-mypy 43 | rev: "v1.9.0" 44 | hooks: 45 | - id: mypy 46 | args: 47 | - --config-file=backend/pyproject.toml 48 | - repo: https://github.com/pre-commit/mirrors-prettier 49 | rev: "v4.0.0-alpha.8" 50 | hooks: 51 | - id: prettier 52 | files: \.[jt]sx?$ 53 | types_or: [css, javascript] 54 | - repo: https://github.com/pre-commit/mirrors-eslint 55 | rev: "v9.0.0-rc.0" 56 | hooks: 57 | - id: eslint 58 | files: \.[jt]sx?$ # *.js, *.jsx, *.ts and *.tsx 59 | types: [file] 60 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

FastAPI Backend Application Template

2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | pre-commit 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | check with mypy 26 | 27 |
28 | 29 |
30 | 31 | This is a template repository aimed to kick-start your project with a setup from a real-world application! This template utilizes the following tech stack: 32 | 33 | * 🐳 [Dockerized](https://www.docker.com/) 34 | * 🐘 [Asynchronous PostgreSQL](https://www.postgresql.org/docs/current/libpq-async.html) 35 | * 🐍 [FastAPI](https://fastapi.tiangolo.com/) 36 | 37 | When the `Docker` is started, these are the URL addresses: 38 | 39 | * Backend Application (API docs) $\rightarrow$ `http://localhost:8001/docs` 40 | * Database editor (Adminer) $\rightarrow$ `http//localhost:8081` 41 | 42 | The backend API without `Docker` can be found in `http://localhost:8000/docs`. 43 | 44 | ## Why the above Tech-Stack? 45 | 46 | Well, the easy answer is **Asynchronousity** and **Speed**! 47 | 48 | * **FastAPI** is crowned as the fastest web framework for Python and thus we use it for our backend development. 49 | * The database of my choice is the **asynchronous** version of **PostgreSQL** (via [SQLAlchemy 2.0](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html)). Read [this blog from Packt](https://subscription.packtpub.com/book/programming/9781838821135/6/ch06lvl1sec32/synchronous-asynchronous-and-threaded-execution) if you want to educate yourself further about the topic **Asynchronous, Synchronous, Concurrency,** and **Parallelism**. 50 | * **Docker** is a technology that packages an application into standardized units called containers that have everything the software needs to run including libraries, system tools, code, and runtime. 51 | 52 | ## Other Technologies 53 | 54 | The above-listed technologies are just the main ones. There are other technologies utilized in this project template to ensure that your application is robust and provides the best possible development environment for your team! These technologies are: 55 | 56 | * [TOML](https://toml.io/en/) $\rightarrow$ The one-for-all configuration file. This makes it simpler to setup our project. 57 | * [Pyenv](https://github.com/pyenv/pyenv) $\rightarrow$ The simplest way to manage our Python versions. 58 | * [Pyenv-VirtualEnv](https://github.com/pyenv/pyenv-virtualenv) $\rightarrow$ The plugin for `Pyenv` to manage the virtual environment for our packages. 59 | * [Pre-Commit](https://pre-commit.com/) $\rightarrow$ Git hook scripts to identify issues and quality of your code before pushing it to GitHub. These hooks are implemented for the following linting packages: 60 | * [Black (Python)](https://black.readthedocs.io/en/stable/) $\rightarrow$ Manage your code style with auto-formatting and parallel continuous integration runner for Python. 61 | * [Isort (Python)](https://pycqa.github.io/isort/) $\rightarrow$ Sort your `import` for clarity. Also for Python. 62 | * [MyPy (Python)](https://mypy.readthedocs.io/en/stable/) $\rightarrow$ A static type checker for Python that helps you to write cleaner code. 63 | * [Pre-Commit CI](https://pre-commit.ci/) $\rightarrow$ Continuous integration for our Pre-Commit hook that fixes and updates our hook versions. 64 | * [CodeCov](https://about.codecov.io/) $\rightarrow$ A platform that analyzes the result of your automated tests. 65 | * [PyTest](https://docs.pytest.org/en/7.2.x/) $\rightarrow$ The testing framework for Python code. 66 | * [DBDiagram](https://dbdiagram.io/home) $\rightarrow$ A platform that lets your design your database by writing SQL and converting it into ERD. This platform provides a complete symbol for entity relationships (not like many other platforms!). 67 | * [GitHub Actions](https://github.com/features/actions) $\rightarrow$ The platform to setup our CI/CD by GitHub. 68 | * [SQLAlchemy 2.0](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html) $\rightarrow$ The go-to database interface library for Python. The 2.0 is the most recent update where it provides an asynchronous setup. 69 | * [CODEOWNERS](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) $\rightarrow$ A file for distributing the responsibilities in our project to each team/teammate. 70 | 71 | My choice for a project development workflow is usually the [Trunk-Based Development](https://trunkbaseddevelopment.com/) because of the straightforward approach in the collaboration workflow, hence the name `trunk` for the main branch repository instead of `master` or `main`. 72 | 73 | ## What Code is included? 74 | 75 | For the backend application: 76 | * The project, linter, and test configurations in `backend/pyproject.toml`. 77 | * 3 settings classes (development, staging, production) with the super class in `backend/src/config/settings/base.py`. 78 | * Event logger in `backend/src/config/events.py`. 79 | * The `Account` object table model in `backend/src/models/db/account.py`. 80 | * The `Account` object schema model in `backend/src/models/schemas/account.py`. 81 | * PostgreSQL database connection with asynchronous SQLAlchemy 2.0 in `backend/src/repository/database.py`. 82 | * A custom SQLAlchemy Base class in `backend/src/repository/table.py` 83 | * PostgreSQL database connection with asynchronous SQLAlchemy 2.0 in `backend/src/repository/database.py`. 84 | * Database-related events e.g. database table registration by app startup in `backend/src/repository/events.py`. 85 | * C. R. U. D. methods for `Account` object in `backend/src/repository/crud/account.py`. 86 | * Table classes registration file in `backend/src/repository/base.py`. 87 | * Alembic setup for auto-generating asynchronous database migrations in `backend/src/repository/migration/**`. 88 | * Alembic main configuration file in `backend/alembic.ini`. 89 | * Dependency injection for database session and repository in `backend/src/api/**`. 90 | * API endpoints for `Account` signup and signin in `backend/src/api/routes/authentication.py`. 91 | * API endpoints for `Account` get all, get 1, update, and delete in `backend/src/api/routes/account.py`. 92 | * API endpoints registration file in `backend/src/api/endpoints`. 93 | * Hashing and JWT generators and simple verification functions in `backend/src/securities/**`. 94 | * Helper functions, string messages, and error handling in `backend/src/utilities/**`. 95 | * A comprehensive FastAPI application initialization in `backend/src/main.py`. 96 | 97 | For testing, I have prepared the following simple code to kick-start your test-driven development: 98 | * A simple replication of the backend application for testing purposes and the asynchronous test client in `backend/tests/conftest.py`. 99 | * 2 simple test functions to test the backend application initialization in `tests/unit_tests/test_src.py`. 100 | 101 | For the DevOps: 102 | * A simple `build` job to test the compilation of the source code for the backend application in `.github/workflows/ci-backend.yaml`. 103 | * A simple linting job called `code-style` with black, isort, flake8, and mypy in `.github/workflows/ci-backend.yaml`. 104 | * An automated testing with `PyTest` and an automated test reporting with `Codecov` in in `.github/workflows/ci-backend.yaml`. 105 | * A source code responsibility distribution file in `.github/CODEOWNERS` (Please change the username to your own). 106 | * A `YAML` file for an automated semantic commit message in `.github/workflows/ci-backend.yaml`. 107 | * An automated test report monitoring via `Codecov` in `codecov.yaml` 108 | * A CI for automatically updating all linter version in the pre-commit `YAML` file in `.pre-commit-config.YAML`. 109 | 110 | For containerization: 111 | * A `Docker` configuration that utilizes the latest Python image in `backend/Dockerfile`. 112 | * A script that ensure the backend application will restart when postgres image hasn't started yet in `backend/entrypoint.sh`. 113 | * Setting up `Postgres` image for our database server, `Adminer` for our database editor, and `backend_app` for our backend application's container in `docker-compose.yaml`. 114 | 115 | For the team development environment: 116 | * A pre-commit hooks for `Black`, `Isort`, and `MyPy` to ensure the conventional commit message before pushing an updated code into the remote repository in `.pre-commit-config.YAML`. 117 | * All secret variables are listed in `.env.example`. You need to copy these variables and set the values respectively to your need and save them in a new `.env` in the root directory. 118 | 119 | ## Setup Guide 120 | 121 | This backend application is setup with `Docker`. Nevertheless, you can see the full local setup without `Docker` in [backend/README.md](https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template/blob/trunk/backend/README.md). 122 | 123 | 1. Before setting up the backend app, please create a new directory called `coverage` for the testing report purpose: 124 | ```shell 125 | cd backend && mkdir coverage 126 | ``` 127 | 128 | 2. Backend app setup: 129 | ```shell 130 | # Creating VENV 131 | pyenv virtualenv 3.11.0 any_venv_name 132 | pyenv local any_venv_name 133 | 134 | # Install dependencies 135 | pip3 install -r requirements.txt 136 | 137 | # Test run your backend server 138 | uvicorn src.main:backend_app --reload 139 | ``` 140 | 141 | 3. Testing with `PyTest`: 142 | Make sure that you are in the `backend/` directory. 143 | ```shell 144 | # For testing without Docker 145 | pytest 146 | 147 | # For testing within Docker 148 | docker exec backend_app pytest 149 | ``` 150 | 151 | 4. `Pre-Commit` setup: 152 | ```shell 153 | # Make sure you are in the ROOT project directory 154 | pre-commit install 155 | pre-commit autoupdate 156 | ``` 157 | 158 | 5. Backend app credentials setup: 159 | If you are not used to VIM or Linux CLI, then ignore the `echo` command and do it manually. All the secret variables for this template are located in `.env.example`. 160 | 161 | If you want to have another name for the secret variables, don't forget to change them also in: 162 | 163 | * `backend/src/config/base.py` 164 | * `docker-compose.yaml` 165 | 166 | ```shell 167 | # Make sure you are in the ROOT project directory 168 | touch .env 169 | 170 | echo "SECRET_VARIABLE=SECRET_VARIABLE_VALUE" >> .env 171 | ``` 172 | 173 | 6. `CODEOWNERS` setup: 174 | Go to `.github/` and open `CODEOWNERS` file. This file is to assign the code to a specific team member so you can distribute the weights of the project clearly. 175 | 176 | 7. Docker setup: 177 | ```shell 178 | # Make sure you are in the ROOT project directory 179 | chmod +x backend/entrypoint.sh 180 | 181 | docker-compose build 182 | docker-compose up 183 | 184 | # Every time you write a new code, update your container with: 185 | docker-compose up -d --build 186 | ``` 187 | 188 | 8. (IMPORTANT) Database setup: 189 | ```shell 190 | # (Docker) Generate revision for the database auto-migrations 191 | docker exec backend_app alembic revision --autogenerate -m "YOUR MIGRATION TITLE" 192 | docker exec backend_app alembic upgrade head # to register the database classes 193 | 194 | # (Local) Generate revision for the database auto-migrations 195 | alembic revision --autogenerate -m "YOUR MIGRATION TITLE" 196 | alembic upgrade head # to register the database classes 197 | ``` 198 | 199 | 9. Go to https://about.codecov.io/, and sign up with your github to get the `CODECOV_TOKEN` 200 | 201 | 10. Go to your GitHub and register all the secret variables (look in .env.example) in your repository (`settings` $\rightarrow$ (scroll down a bit) `Secrets` $\rightarrow$ `Actions` $\rightarrow$ `New repository secret`) 202 | 203 | **IMPORTANT**: Without the secrets registered in Codecov and GitHub, your `CI` will fail and life will be horrible 🤮🤬 204 | **IMPORTANT**: Remember to always run the container update every once in a while. Without the arguments `-d --build`, your `Docker` dashboard will be full of junk containers! 205 | 206 | ## Project Structure 207 | 208 | ```shell 209 | .github/ 210 | ├── workflows/ 211 | ├── ci-backend.yaml # A CI file for the backend app that consists of `build`, `code-style`, and `test` 212 | ├── CODEOWNERS # A configuration file to distribute code responsibility 213 | ├── semantic.yaml # A configuration file for ensuring an automated semantic commit message 214 | 215 | backend/ 216 | ├── coverage/ 217 | ├── src/ 218 | ├── api/ 219 | ├── dependencies/ # Dependency injections 220 | ├── session.py 221 | ├──repository.py 222 | ├── routes/ # Endpoints 223 | ├── account.py # Account routes 224 | ├── authentication.py # Signup and Signin routes 225 | ├── endpoints.py # Endpoint registration 226 | ├── config/ 227 | ├── settings/ 228 | ├── base.py # Base settings / settings parent class 229 | ├── development.py # Development settings 230 | ├── environments.py # Enum with PROD, DEV, STAGE environment 231 | ├── production.py # Production settings 232 | ├── staging.py # Test settings 233 | ├── events.py # Registration of global events 234 | ├── manager.py # Manage get settings 235 | ├── models/ 236 | ├── db/ 237 | ├── account.py # Account class for database entity 238 | ├── schemas/ 239 | ├── account.py # Account classes for data validation objects 240 | ├── base.py # Base class for data validation objects 241 | ├── repository/ 242 | ├── crud/ 243 | ├── account.py # C. R. U. D. operations for Account entity 244 | ├── base.py # Base class for C. R. U. D. operations 245 | ├── migrations/ 246 | ├── versions/ 247 | ├── env.py # Generated via alembic for automigration 248 | ├── script.py.mako # Generated via alembic 249 | ├── base.py # Entry point for alembic automigration 250 | ├── database.py # Database class with engine and session 251 | ├── events.py # Registration of database events 252 | ├── table.py # Custom SQLAlchemy Base class 253 | ├── security/ 254 | ├── hashing/ 255 | ├── hash.py # Hash functions with passlib 256 | ├── password.py # Password generator with hash functions 257 | ├── authorizations/ 258 | ├── jwt.py # Generate JWT tokens with python-jose 259 | ├── verifications/ 260 | ├── credentials.py # Check for attributes' availability 261 | ├── utilities/ 262 | ├── exceptions/ 263 | ├── http/ 264 | ├── http_exc_400.py # Custom 400 error handling functions 265 | ├── http_exc_401.py # Custom 401 error handling functions 266 | ├── http_exc_403.py # Custom 403 error handling functions 267 | ├── http_exc_404.py # Custom 404 error handling functions 268 | ├── database.py # Custom `Exception` class 269 | ├── password.py # Custom `Exception` class 270 | ├── formatters/ 271 | ├── datetime_formatter.py # Reformat datetime into the ISO form 272 | ├── field_formatter.py # Reformat snake_case to camelCase 273 | ├── messages/ 274 | ├── http/ 275 | ├── http_exc_details.py # Custom message for HTTP exceptions 276 | ├── main.py # Our main backend server app 277 | ├── tests/ 278 | ├── end_to_end_tests/ # End-to-end tests 279 | ├── integration_tests/ # Integration tests 280 | ├── security_tests/ # Security-related tests 281 | ├── unit_tests/ # Unit tests 282 | ├── test_src.py # Testing the src directory's version 283 | ├── conftest.py # The fixture codes and other base test codes 284 | ├── Dockerfile # Docker configuration file for backend application 285 | ├── README.md # Documentation for backend app 286 | ├── entrypoint.sh # A script to restart backend app container if postgres is not started 287 | ├── alembic.ini # Automatic database migration configuration 288 | ├── pyproject.toml # Linter and test main configuration file 289 | ├── requirements.txt # Packages installed for backend app 290 | .dockerignore # A file that list files to be excluded in Docker container 291 | .gitignore # A file that list files to be excluded in GitHub repository 292 | .pre-commit-config.yaml # A file with Python linter hooks to ensure conventional commit when committing 293 | LICENSE.md # A license to use this template repository (delete this file after using this repository) 294 | README.md # The main documentation file for this template repository 295 | codecov.yaml # The configuration file for automated testing CI with codecov.io 296 | docker-compose.yaml # The main configuration file for setting up a multi-container Docker 297 | ``` 298 | 299 | ## Final Step 300 | 301 | You can delete these 3 files (or change its content based on your need): 302 | - `LICENSE.md` 303 | - `README.md` 304 | - `backend/README.md` 305 | 306 | Enjoy your development and may your technology be forever useful to everyone 😉🚀🧬 307 | 308 | --- 309 | -------------------------------------------------------------------------------- /backend/Dockerfile: -------------------------------------------------------------------------------- 1 | # Pull official latest Python Docker image (Pulished with version 3.11.0) 2 | FROM --platform=linux/amd64 python:latest 3 | 4 | # Set the working directory 5 | WORKDIR /usr/backend 6 | 7 | # Set up Python behaviour 8 | ENV PYTHONDONTWRITEBYTECODE 1 9 | ENV PYTHONUNBUFFERED 1 10 | ENV VIRTUAL_ENV=/opt/venv 11 | 12 | # Switch on virtual environment 13 | RUN python3 -m venv $VIRTUAL_ENV 14 | ENV PATH="$VIRTUAL_ENV/bin:$PATH" 15 | 16 | # Set the server port 17 | EXPOSE 8000 18 | 19 | # Install system dependencies 20 | RUN apt-get update \ 21 | && apt-get -y install netcat gcc postgresql \ 22 | && apt-get clean 23 | 24 | # Install Python dependencies 25 | RUN pip install --upgrade pip 26 | COPY ./requirements.txt ./ 27 | RUN pip3 install -r requirements.txt 28 | 29 | # Copy all files 30 | COPY . . 31 | 32 | # Copy entrypoint.sh for auto connection with account_db service 33 | COPY ./entrypoint.sh . 34 | RUN chmod +x /usr/backend/entrypoint.sh 35 | 36 | # Execute entrypoint.sh 37 | ENTRYPOINT ["/usr/backend/entrypoint.sh" ] 38 | 39 | # Start up the backend server 40 | CMD uvicorn src.main:backend_app --reload --workers 4 --host 0.0.0.0 --port 8000 41 | -------------------------------------------------------------------------------- /backend/README.md: -------------------------------------------------------------------------------- 1 |

Backend Application 🐍

2 | 3 | This backend application template consists of: 4 | 5 | * Configure the [TOML](https://toml.io/en/) file for testing and linting. 6 | * Create the backend server with FastAPI and Uvicorn, 7 | * Connect the backend app with PostgreSQL server via the asynchronous SQLAlchemy with AsyncPG driver. 8 | * Set up Alembic for the auto-generation of database migrations. 9 | * Create `Account` (domain) class as our database entity `account`. 10 | * Create data validation for our database entity with [Pydantic](https://pydantic-docs.helpmanual.io/). 11 | * Create formatters for `json` convention and `datetime`. 12 | * Create authorization with JWT Token generator. 13 | * Create hashing function generator and password generator. 14 | * Create custom error/exception handlers for both source code and HTTP. 15 | * Create dependency injections for utilizing our asynchronous session and C. R. U. D. repository class. 16 | * Create account specific routes: `signup`, `signin`, `get all`, `get by id`, `update by id`, and `delete by id`. 17 | 18 | **P. S. This README will walk you through the local development setup. If you prefer to run your backend app with docker, see the main README.** 19 | 20 | --- 21 | 22 | ## Python, VEnv, & Requirements Installation 23 | 24 | **INFO**: All related to Python will be setup **IN** and **FROM** the `backend/` directory! 25 | 26 | * Step 1 $\rightarrow$ Open your project root directory and set up your Python via `PyEnv`: 27 | 28 | ```shell 29 | pyenv install 3.11.0 30 | ``` 31 | 32 | * Step 2 $\rightarrow$ Create our virtual environment: 33 | 34 | ```shell 35 | pyenv virtualenv 3.11.0 YOUR_VENV_NAME 36 | ``` 37 | 38 | * Step 3 $\rightarrow$ Set the newly created virtual environment as your main Python interpreter in the root directory: 39 | 40 | ```shell 41 | pyenv local YOUR_VENV_NAME 42 | ``` 43 | 44 | * Step 4 $\rightarrow$ Install the initial project requirements with `pip3`: 45 | 46 | ```shell 47 | pip3 install -r requirements.txt 48 | ``` 49 | 50 | --- 51 | 52 | ## SSHhhhttt 🤫 It's a Secret! 53 | 54 | All secret variables are configured in the `.env`, but in this case since it is listed in our `.gitignore` you should create one and save it in the root directory. 55 | 56 | The secret variables are accessed by 2 different files: 57 | 58 | 1. `backend7src/config/settings/base.py` $\rightarrow$ The `BackendBaseSettings` class contains all the secret variables. This allows us to set the values dynamically through out the backend application ("dynamic" because we only need to change the value in `.env` file without breaking any code). 59 | 2. `docker-compose.yaml` $\rightarrow$ When we initialize the `backend_app` container, we register all the secret variables as well for our containerized backend application. 60 | 61 | ## Database 62 | 63 | **INFO**: No postgres server, no connection! 64 | 65 | * Step 1 $\rightarrow$ Run your postgres server (if you use MacOS, I suggest the installation via [postgre14 homebrew](https://formulae.brew.sh/formula/postgresql@14)): 66 | 67 | ```shell 68 | brew services start postgresql@14 69 | ``` 70 | 71 | * Step 2 $\rightarrow$ Go to your database editor choice and create a database for this application. 72 | 73 | * Step 3 $\rightarrow$ Register your database credentials respectively in our `.env` file in the root directory. 74 | 75 | * Step 4 (Optional) $\rightarrow$ To stop your postgres server, run: 76 | ```shell 77 | brew services stop postgres@14 78 | ``` 79 | 80 | ### Alembic for Automigration 81 | 82 | **INFO**: Files generated by `Alembic` can be found in `backend/src/repository/migrations/**` (if you don't see the `versions/` directory, make one!) 83 | 84 | **INFO**: You need to import your domain classes in `backend/src/repository/base.py` for alembic's auto migration! 85 | 86 | * Step 1 $\rightarrow$ Create the initialization of your database migration: 87 | ```shell 88 | alembic revision --autogenerate -m "YOUR NOTES ABOUT THE DATABASE MIGRATION HERE" 89 | ``` 90 | 91 | * Step 2 $\rightarrow$ Push the registered database objects to your database: 92 | ```shell 93 | alembic upgrade head 94 | ``` 95 | 96 | --- 97 | 98 | ## Pre-Commit 99 | 100 | **INFO**: Run **Step 1** every time you `git add` a file to identify any mistakes before `git commit`. Otherwise, you will re-write your perfect commit message again 👿🤬🤮 101 | 102 | * Step 1 $\rightarrow$ Install the pre-commit hook: 103 | ```shell 104 | pre-commit 105 | ``` 106 | 107 | * Step 2 $\rightarrow$ For good practive, let#s update the hooks: 108 | ```shell 109 | pre-commit autoupdate 110 | ``` 111 | 112 | --- 113 | 114 | ## TOML Configuration 115 | 116 | Check the `pyproject.toml` as the main configuration file for the following packages: 117 | 118 | * Project documentation 119 | * Black 120 | * Isort 121 | * MyPy 122 | * PyTest 123 | * Converage 124 | 125 | --- 126 | 127 | ## FastAPI Backend Server 128 | 129 | **INFO**: Make sure that you are in the `backend/` directory! 130 | 131 | * Stp 1 $\rightarrow$ Run the server: 132 | ```shell 133 | uvicorn src.main:backend_app --reload 134 | ``` 135 | 136 | * Step 2 (Optional) $\rightarrow$ To stop the server click simultaneously `control` and `C` 137 | 138 | --- 139 | 140 | ## Test with PyTest 141 | 142 | **INFO**: For running the test, make sure you are in the root directory and NOT in the `backend/` directory! 143 | 144 | **INFO**: The testing report is automatically generated and saved in `backend/coverage/**` 145 | 146 | * Step 1: Run PyTest: 147 | 148 | ```shell 149 | pytest 150 | ``` 151 | 152 | --- 153 | 154 | ## Python Package Info Board 155 | 156 | So what are we actually installing? You can find the main packages in the below table. 157 | 158 | Server | Database | Test | Linter | Others 159 | --|--|--|--|-- 160 | [fastapi](https://fastapi.tiangolo.com/) | [sqlalchemy (version 2.0.0b3)](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html) | [pytest](https://docs.pytest.org/en/7.2.x/) | [black](https://pypi.org/project/black/) | [python-decouple](https://pypi.org/project/python-decouple/) 161 | [uvicorn](https://www.uvicorn.org/) | [alembic](https://alembic.sqlalchemy.org/en/latest/) | [pytest-asyncio](https://pypi.org/project/pytest-asyncio/) | [isort](https://pypi.org/project/isort/) | [email-validator](https://pypi.org/project/email-validator/) 162 | [pydantic](https://docs.pydantic.dev/usage/exporting_models/) | [asyncpg](https://magicstack.github.io/asyncpg/current/) | [pytest-cov](https://pypi.org/project/pytest-cov/) | [mypy](https://pypi.org/project/mypy/) | [python-dotenv](https://pypi.org/project/python-dotenv/) 163 | [starlette](https://www.starlette.io/) | [greenlet](https://pypi.org/project/greenlet/) | [pytest-xdist](https://pypi.org/project/pytest-xdist/) | [pre-commit](https://pypi.org/project/pre-commit/) | [passlib](https://passlib.readthedocs.io/en/stable/) 164 | [asgi_lifespan](https://pypi.org/project/asgi-lifespan/) | - | | [colorama](https://pypi.org/project/colorama/) | [loguru](https://github.com/Delgan/loguru) 165 | [httpx](https://www.python-httpx.org/) | - | - | - | [python-jose](https://python-jose.readthedocs.io/en/latest/) 166 | [trio](https://pypi.org/project/trio/) | - | - | - | [pathlib](https://pathlib.readthedocs.io/en/pep428/) 167 | \- | - | - | - | [python-slugify](https://pypi.org/project/python-slugify/) 168 | 169 | --- 170 | -------------------------------------------------------------------------------- /backend/alembic.ini: -------------------------------------------------------------------------------- 1 | [alembic] 2 | # Path to migration scripts 3 | script_location = src/repository/migrations 4 | 5 | # Template used to generate migration file names; The default value is %%(rev)s_%%(slug)s 6 | file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s 7 | 8 | # sys.path path, will be prepended to sys.path if present. defaults to the current working directory. 9 | prepend_sys_path = . 10 | 11 | # The character used to split version_locations. The default within new alembic.ini files uses os.pathsep. 12 | version_path_separator = os # Use os.pathsep. Default configuration used for new projects. 13 | 14 | # The output encoding used when revision files are written from script.py.mako 15 | # output_encoding = utf-8 16 | 17 | sqlalchemy.url = driver://user:pass@localhost/dbname 18 | 19 | 20 | [post_write_hooks] 21 | # post_write_hooks defines scripts or Python functions that are run 22 | # on newly generated revision scripts. See the documentation for further 23 | # detail and examples 24 | 25 | # format using "black" - use the console_scripts runner, against the "black" entrypoint 26 | # hooks = black 27 | # black.type = console_scripts 28 | # black.entrypoint = black 29 | # black.options = -l 79 REVISION_SCRIPT_FILENAME 30 | 31 | # Logging configuration 32 | [loggers] 33 | keys = root,sqlalchemy,alembic 34 | 35 | [handlers] 36 | keys = console 37 | 38 | [formatters] 39 | keys = generic 40 | 41 | [logger_root] 42 | level = WARN 43 | handlers = console 44 | qualname = 45 | 46 | [logger_sqlalchemy] 47 | level = WARN 48 | handlers = 49 | qualname = sqlalchemy.engine 50 | 51 | [logger_alembic] 52 | level = INFO 53 | handlers = 54 | qualname = alembic 55 | 56 | [handler_console] 57 | class = StreamHandler 58 | args = (sys.stderr,) 59 | level = NOTSET 60 | formatter = generic 61 | 62 | [formatter_generic] 63 | format = %(levelname)-5.5s [%(name)s] %(message)s 64 | datefmt = %H:%M:%S 65 | -------------------------------------------------------------------------------- /backend/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "DB Connection --- Establishing . . ." 4 | 5 | while ! nc -z db 5432; do 6 | 7 | echo "DB Connection -- Failed!" 8 | 9 | sleep 1 10 | 11 | echo "DB Connection -- Retrying . . ." 12 | 13 | done 14 | 15 | echo "DB Connection --- Successfully Established!" 16 | 17 | exec "$@" 18 | -------------------------------------------------------------------------------- /backend/pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "DAPSQL QWIK-Stack Application" 3 | version = "0.0.1" 4 | description = "A comprehensive template to start a real-world quality project." 5 | authors = [ 6 | {name = "Aeternalis-Ingenium", email="aeternalisingenium@proton.me"}, 7 | ] 8 | classifiers = [ 9 | "Topic :: Software Development" 10 | ] 11 | 12 | dynamic = ["dependencies"] 13 | #license = {file = "LICENSE.txt"} 14 | readme = "README.md" 15 | requires-python = ">=3.11" 16 | 17 | [tool.setuptools.dynamic] 18 | dependencies = {file = ["requirements.txt"]} 19 | 20 | [project.urls] 21 | homepage = "https://github.com/Aeternalis-Ingenium/DAPSQL-FAQ-Stack-Template" 22 | documentation = "https://github.com/Aeternalis-Ingenium/DAPSQL-FAQ-Stack-Template" 23 | repository = "https://github.com/Aeternalis-Ingenium/DAPSQL-FAQ-Stack-Template" 24 | 25 | [tool.black] 26 | color=true 27 | exclude = ''' 28 | /( 29 | \.git 30 | | \._build 31 | | \.back.out 32 | | \.build 33 | | \.coverage 34 | | \.dist 35 | | \.hg 36 | | \.mypy_cache 37 | | \.tox 38 | | \.venv 39 | | ./src/coverage 40 | | blib2to3 41 | | tests/data 42 | )/ 43 | ''' 44 | include = '\.pyi?$' 45 | line-length = 119 46 | 47 | [tool.isort] 48 | color_output = true 49 | combine_as_imports = true 50 | ensure_newline_before_comments = true 51 | force_alphabetical_sort_within_sections = true 52 | force_grid_wrap = 0 53 | include_trailing_comma = true 54 | line_length = 119 55 | lines_between_sections = 1 56 | multi_line_output = 3 57 | profile = "black" 58 | skip = [ 59 | ".coverage", 60 | "coverage/*", 61 | "cov.html", 62 | ".dockerignore", 63 | ".env", 64 | ".github", 65 | ".gitignore", 66 | ".html", 67 | ".md", 68 | ".python-version", 69 | ".rst", 70 | ".xml" 71 | ] 72 | skip_gitignore = true 73 | skip_glob = [ 74 | "src/repository/migrations/**", 75 | ] 76 | src_paths = [ 77 | "src/", 78 | "tests/", 79 | ] 80 | use_parentheses = true 81 | 82 | [tool.mypy] 83 | check_untyped_defs = true 84 | color_output = true 85 | error_summary = true 86 | exclude = "(build|data|dist|docs/src|images|logo|logs|output)/" 87 | ignore_missing_imports = true 88 | pretty = true 89 | python_version = "3.11" 90 | strict_optional = true 91 | warn_no_return = true 92 | warn_return_any = false 93 | 94 | [tool.pytest.ini_options] 95 | python_files = ["test_*.py", "*_test.py"] 96 | python_classes = ["Test", "Acceptance"] 97 | python_functions = ["test_*"] 98 | testpaths = "tests" 99 | filterwarnings = "error" 100 | addopts = ''' 101 | --verbose 102 | -p no:warnings 103 | --strict-markers 104 | --tb=short 105 | --cov=src 106 | --cov=tests 107 | --cov-branch 108 | --cov-report=term-missing 109 | --cov-report=html:coverage/cov.html 110 | --cov-report=xml:coverage/cov.xml 111 | --no-cov-on-fail 112 | --cov-fail-under=63 113 | --numprocesses=auto 114 | --asyncio-mode=auto 115 | ''' 116 | -------------------------------------------------------------------------------- /backend/requirements.txt: -------------------------------------------------------------------------------- 1 | alembic 2 | asgi_lifespan 3 | argon2_cffi 4 | asyncio 5 | asyncpg 6 | bcrypt 7 | black 8 | colorama 9 | email-validator 10 | fastapi 11 | greenlet 12 | httpx 13 | isort 14 | loguru 15 | mypy 16 | passlib 17 | pathlib 18 | pre-commit 19 | python-dotenv 20 | python-decouple 21 | python-jose 22 | python-slugify 23 | pytest 24 | pytest-asyncio 25 | pytest-cov 26 | pytest-xdist 27 | SQLAlchemy==2.0.0b3 28 | trio 29 | uvicorn 30 | -------------------------------------------------------------------------------- /backend/src/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.1" 2 | -------------------------------------------------------------------------------- /backend/src/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/api/__init__.py -------------------------------------------------------------------------------- /backend/src/api/dependencies/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/api/dependencies/__init__.py -------------------------------------------------------------------------------- /backend/src/api/dependencies/repository.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | import fastapi 4 | from sqlalchemy.ext.asyncio import ( 5 | async_sessionmaker as sqlalchemy_async_sessionmaker, 6 | AsyncSession as SQLAlchemyAsyncSession, 7 | ) 8 | 9 | from src.api.dependencies.session import get_async_session 10 | from src.repository.crud.base import BaseCRUDRepository 11 | 12 | 13 | def get_repository( 14 | repo_type: typing.Type[BaseCRUDRepository], 15 | ) -> typing.Callable[[SQLAlchemyAsyncSession], BaseCRUDRepository]: 16 | def _get_repo( 17 | async_session: SQLAlchemyAsyncSession = fastapi.Depends(get_async_session), 18 | ) -> BaseCRUDRepository: 19 | return repo_type(async_session=async_session) 20 | 21 | return _get_repo 22 | -------------------------------------------------------------------------------- /backend/src/api/dependencies/session.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import typing 3 | 4 | import fastapi 5 | from sqlalchemy.ext.asyncio import ( 6 | async_sessionmaker as sqlalchemy_async_sessionmaker, 7 | AsyncSession as SQLAlchemyAsyncSession, 8 | AsyncSessionTransaction as SQLAlchemyAsyncSessionTransaction, 9 | ) 10 | 11 | from src.repository.database import async_db 12 | 13 | 14 | async def get_async_session() -> typing.AsyncGenerator[SQLAlchemyAsyncSession, None]: 15 | try: 16 | yield async_db.async_session 17 | except Exception as e: 18 | print(e) 19 | await async_db.async_session.rollback() 20 | finally: 21 | await async_db.async_session.close() 22 | -------------------------------------------------------------------------------- /backend/src/api/endpoints.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | 3 | from src.api.routes.account import router as account_router 4 | from src.api.routes.authentication import router as auth_router 5 | 6 | router = fastapi.APIRouter() 7 | 8 | router.include_router(router=account_router) 9 | router.include_router(router=auth_router) 10 | -------------------------------------------------------------------------------- /backend/src/api/routes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/api/routes/__init__.py -------------------------------------------------------------------------------- /backend/src/api/routes/account.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | import pydantic 3 | 4 | from src.api.dependencies.repository import get_repository 5 | from src.models.schemas.account import AccountInResponse, AccountInUpdate, AccountWithToken 6 | from src.repository.crud.account import AccountCRUDRepository 7 | from src.securities.authorizations.jwt import jwt_generator 8 | from src.utilities.exceptions.database import EntityDoesNotExist 9 | from src.utilities.exceptions.http.exc_404 import ( 10 | http_404_exc_email_not_found_request, 11 | http_404_exc_id_not_found_request, 12 | http_404_exc_username_not_found_request, 13 | ) 14 | 15 | router = fastapi.APIRouter(prefix="/accounts", tags=["accounts"]) 16 | 17 | 18 | @router.get( 19 | path="", 20 | name="accountss:read-accounts", 21 | response_model=list[AccountInResponse], 22 | status_code=fastapi.status.HTTP_200_OK, 23 | ) 24 | async def get_accounts( 25 | account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)), 26 | ) -> list[AccountInResponse]: 27 | db_accounts = await account_repo.read_accounts() 28 | db_account_list: list = list() 29 | 30 | for db_account in db_accounts: 31 | access_token = jwt_generator.generate_access_token(account=db_account) 32 | account = AccountInResponse( 33 | id=db_account.id, 34 | authorized_account=AccountWithToken( 35 | token=access_token, 36 | username=db_account.username, 37 | email=db_account.email, # type: ignore 38 | is_verified=db_account.is_verified, 39 | is_active=db_account.is_active, 40 | is_logged_in=db_account.is_logged_in, 41 | created_at=db_account.created_at, 42 | updated_at=db_account.updated_at, 43 | ), 44 | ) 45 | db_account_list.append(account) 46 | 47 | return db_account_list 48 | 49 | 50 | @router.get( 51 | path="/{id}", 52 | name="accountss:read-account-by-id", 53 | response_model=AccountInResponse, 54 | status_code=fastapi.status.HTTP_200_OK, 55 | ) 56 | async def get_account( 57 | id: int, 58 | account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)), 59 | ) -> AccountInResponse: 60 | try: 61 | db_account = await account_repo.read_account_by_id(id=id) 62 | access_token = jwt_generator.generate_access_token(account=db_account) 63 | 64 | except EntityDoesNotExist: 65 | raise await http_404_exc_id_not_found_request(id=id) 66 | 67 | return AccountInResponse( 68 | id=db_account.id, 69 | authorized_account=AccountWithToken( 70 | token=access_token, 71 | username=db_account.username, 72 | email=db_account.email, # type: ignore 73 | is_verified=db_account.is_verified, 74 | is_active=db_account.is_active, 75 | is_logged_in=db_account.is_logged_in, 76 | created_at=db_account.created_at, 77 | updated_at=db_account.updated_at, 78 | ), 79 | ) 80 | 81 | 82 | @router.patch( 83 | path="/{id}", 84 | name="accountss:update-account-by-id", 85 | response_model=AccountInResponse, 86 | status_code=fastapi.status.HTTP_200_OK, 87 | ) 88 | async def update_account( 89 | query_id: int, 90 | update_username: str | None = None, 91 | update_email: pydantic.EmailStr | None = None, 92 | update_password: str | None = None, 93 | account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)), 94 | ) -> AccountInResponse: 95 | account_update = AccountInUpdate(username=update_username, email=update_email, password=update_password) 96 | try: 97 | updated_db_account = await account_repo.update_account_by_id(id=query_id, account_update=account_update) 98 | 99 | except EntityDoesNotExist: 100 | raise await http_404_exc_id_not_found_request(id=query_id) 101 | 102 | access_token = jwt_generator.generate_access_token(account=updated_db_account) 103 | 104 | return AccountInResponse( 105 | id=updated_db_account.id, 106 | authorized_account=AccountWithToken( 107 | token=access_token, 108 | username=updated_db_account.username, 109 | email=updated_db_account.email, # type: ignore 110 | is_verified=updated_db_account.is_verified, 111 | is_active=updated_db_account.is_active, 112 | is_logged_in=updated_db_account.is_logged_in, 113 | created_at=updated_db_account.created_at, 114 | updated_at=updated_db_account.updated_at, 115 | ), 116 | ) 117 | 118 | 119 | @router.delete(path="", name="accountss:delete-account-by-id", status_code=fastapi.status.HTTP_200_OK) 120 | async def delete_account( 121 | id: int, account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)) 122 | ) -> dict[str, str]: 123 | try: 124 | deletion_result = await account_repo.delete_account_by_id(id=id) 125 | 126 | except EntityDoesNotExist: 127 | raise await http_404_exc_id_not_found_request(id=id) 128 | 129 | return {"notification": deletion_result} 130 | -------------------------------------------------------------------------------- /backend/src/api/routes/authentication.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | 3 | from src.api.dependencies.repository import get_repository 4 | from src.models.schemas.account import AccountInCreate, AccountInLogin, AccountInResponse, AccountWithToken 5 | from src.repository.crud.account import AccountCRUDRepository 6 | from src.securities.authorizations.jwt import jwt_generator 7 | from src.utilities.exceptions.database import EntityAlreadyExists 8 | from src.utilities.exceptions.http.exc_400 import ( 9 | http_exc_400_credentials_bad_signin_request, 10 | http_exc_400_credentials_bad_signup_request, 11 | ) 12 | 13 | router = fastapi.APIRouter(prefix="/auth", tags=["authentication"]) 14 | 15 | 16 | @router.post( 17 | "/signup", 18 | name="auth:signup", 19 | response_model=AccountInResponse, 20 | status_code=fastapi.status.HTTP_201_CREATED, 21 | ) 22 | async def signup( 23 | account_create: AccountInCreate, 24 | account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)), 25 | ) -> AccountInResponse: 26 | try: 27 | await account_repo.is_username_taken(username=account_create.username) 28 | await account_repo.is_email_taken(email=account_create.email) 29 | 30 | except EntityAlreadyExists: 31 | raise await http_exc_400_credentials_bad_signup_request() 32 | 33 | new_account = await account_repo.create_account(account_create=account_create) 34 | access_token = jwt_generator.generate_access_token(account=new_account) 35 | 36 | return AccountInResponse( 37 | id=new_account.id, 38 | authorized_account=AccountWithToken( 39 | token=access_token, 40 | username=new_account.username, 41 | email=new_account.email, # type: ignore 42 | is_verified=new_account.is_verified, 43 | is_active=new_account.is_active, 44 | is_logged_in=new_account.is_logged_in, 45 | created_at=new_account.created_at, 46 | updated_at=new_account.updated_at, 47 | ), 48 | ) 49 | 50 | 51 | @router.post( 52 | path="/signin", 53 | name="auth:signin", 54 | response_model=AccountInResponse, 55 | status_code=fastapi.status.HTTP_202_ACCEPTED, 56 | ) 57 | async def signin( 58 | account_login: AccountInLogin, 59 | account_repo: AccountCRUDRepository = fastapi.Depends(get_repository(repo_type=AccountCRUDRepository)), 60 | ) -> AccountInResponse: 61 | try: 62 | db_account = await account_repo.read_user_by_password_authentication(account_login=account_login) 63 | 64 | except Exception: 65 | raise await http_exc_400_credentials_bad_signin_request() 66 | 67 | access_token = jwt_generator.generate_access_token(account=db_account) 68 | 69 | return AccountInResponse( 70 | id=db_account.id, 71 | authorized_account=AccountWithToken( 72 | token=access_token, 73 | username=db_account.username, 74 | email=db_account.email, # type: ignore 75 | is_verified=db_account.is_verified, 76 | is_active=db_account.is_active, 77 | is_logged_in=db_account.is_logged_in, 78 | created_at=db_account.created_at, 79 | updated_at=db_account.updated_at, 80 | ), 81 | ) 82 | -------------------------------------------------------------------------------- /backend/src/config/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/config/__init__.py -------------------------------------------------------------------------------- /backend/src/config/events.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | import fastapi 4 | import loguru 5 | 6 | from src.repository.events import dispose_db_connection, initialize_db_connection 7 | 8 | 9 | def execute_backend_server_event_handler(backend_app: fastapi.FastAPI) -> typing.Any: 10 | async def launch_backend_server_events() -> None: 11 | await initialize_db_connection(backend_app=backend_app) 12 | 13 | return launch_backend_server_events 14 | 15 | 16 | def terminate_backend_server_event_handler(backend_app: fastapi.FastAPI) -> typing.Any: 17 | @loguru.logger.catch 18 | async def stop_backend_server_events() -> None: 19 | await dispose_db_connection(backend_app=backend_app) 20 | 21 | return stop_backend_server_events 22 | -------------------------------------------------------------------------------- /backend/src/config/manager.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | import decouple 4 | 5 | from src.config.settings.base import BackendBaseSettings 6 | from src.config.settings.development import BackendDevSettings 7 | from src.config.settings.environment import Environment 8 | from src.config.settings.production import BackendProdSettings 9 | from src.config.settings.staging import BackendStageSettings 10 | 11 | 12 | class BackendSettingsFactory: 13 | def __init__(self, environment: str): 14 | self.environment = environment 15 | 16 | def __call__(self) -> BackendBaseSettings: 17 | if self.environment == Environment.DEVELOPMENT.value: 18 | return BackendDevSettings() 19 | elif self.environment == Environment.STAGING.value: 20 | return BackendStageSettings() 21 | return BackendProdSettings() 22 | 23 | 24 | @lru_cache() 25 | def get_settings() -> BackendBaseSettings: 26 | return BackendSettingsFactory(environment=decouple.config("ENVIRONMENT", default="DEV", cast=str))() # type: ignore 27 | 28 | 29 | settings: BackendBaseSettings = get_settings() 30 | -------------------------------------------------------------------------------- /backend/src/config/settings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/config/settings/__init__.py -------------------------------------------------------------------------------- /backend/src/config/settings/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import pathlib 3 | 4 | import decouple 5 | import pydantic 6 | 7 | ROOT_DIR: pathlib.Path = pathlib.Path(__file__).parent.parent.parent.parent.parent.resolve() 8 | 9 | 10 | class BackendBaseSettings(pydantic.BaseSettings): 11 | TITLE: str = "DAPSQL FARN-Stack Template Application" 12 | VERSION: str = "0.1.0" 13 | TIMEZONE: str = "UTC" 14 | DESCRIPTION: str | None = None 15 | DEBUG: bool = False 16 | 17 | SERVER_HOST: str = decouple.config("BACKEND_SERVER_HOST", cast=str) # type: ignore 18 | SERVER_PORT: int = decouple.config("BACKEND_SERVER_PORT", cast=int) # type: ignore 19 | SERVER_WORKERS: int = decouple.config("BACKEND_SERVER_WORKERS", cast=int) # type: ignore 20 | API_PREFIX: str = "/api" 21 | DOCS_URL: str = "/docs" 22 | OPENAPI_URL: str = "/openapi.json" 23 | REDOC_URL: str = "/redoc" 24 | OPENAPI_PREFIX: str = "" 25 | 26 | DB_POSTGRES_HOST: str = decouple.config("POSTGRES_HOST", cast=str) # type: ignore 27 | DB_MAX_POOL_CON: int = decouple.config("DB_MAX_POOL_CON", cast=int) # type: ignore 28 | DB_POSTGRES_NAME: str = decouple.config("POSTGRES_DB", cast=str) # type: ignore 29 | DB_POSTGRES_PASSWORD: str = decouple.config("POSTGRES_PASSWORD", cast=str) # type: ignore 30 | DB_POOL_SIZE: int = decouple.config("DB_POOL_SIZE", cast=int) # type: ignore 31 | DB_POOL_OVERFLOW: int = decouple.config("DB_POOL_OVERFLOW", cast=int) # type: ignore 32 | DB_POSTGRES_PORT: int = decouple.config("POSTGRES_PORT", cast=int) # type: ignore 33 | DB_POSTGRES_SCHEMA: str = decouple.config("POSTGRES_SCHEMA", cast=str) # type: ignore 34 | DB_TIMEOUT: int = decouple.config("DB_TIMEOUT", cast=int) # type: ignore 35 | DB_POSTGRES_USERNAME: str = decouple.config("POSTGRES_USERNAME", cast=str) # type: ignore 36 | 37 | IS_DB_ECHO_LOG: bool = decouple.config("IS_DB_ECHO_LOG", cast=bool) # type: ignore 38 | IS_DB_FORCE_ROLLBACK: bool = decouple.config("IS_DB_FORCE_ROLLBACK", cast=bool) # type: ignore 39 | IS_DB_EXPIRE_ON_COMMIT: bool = decouple.config("IS_DB_EXPIRE_ON_COMMIT", cast=bool) # type: ignore 40 | 41 | API_TOKEN: str = decouple.config("API_TOKEN", cast=str) # type: ignore 42 | AUTH_TOKEN: str = decouple.config("AUTH_TOKEN", cast=str) # type: ignore 43 | JWT_TOKEN_PREFIX: str = decouple.config("JWT_TOKEN_PREFIX", cast=str) # type: ignore 44 | JWT_SECRET_KEY: str = decouple.config("JWT_SECRET_KEY", cast=str) # type: ignore 45 | JWT_SUBJECT: str = decouple.config("JWT_SUBJECT", cast=str) # type: ignore 46 | JWT_MIN: int = decouple.config("JWT_MIN", cast=int) # type: ignore 47 | JWT_HOUR: int = decouple.config("JWT_HOUR", cast=int) # type: ignore 48 | JWT_DAY: int = decouple.config("JWT_DAY", cast=int) # type: ignore 49 | JWT_ACCESS_TOKEN_EXPIRATION_TIME: int = JWT_MIN * JWT_HOUR * JWT_DAY 50 | 51 | IS_ALLOWED_CREDENTIALS: bool = decouple.config("IS_ALLOWED_CREDENTIALS", cast=bool) # type: ignore 52 | ALLOWED_ORIGINS: list[str] = [ 53 | "http://localhost:3000", # React default port 54 | "http://0.0.0.0:3000", 55 | "http://127.0.0.1:3000", # React docker port 56 | "http://127.0.0.1:3001", 57 | "http://localhost:5173", # Qwik default port 58 | "http://0.0.0.0:5173", 59 | "http://127.0.0.1:5173", # Qwik docker port 60 | "http://127.0.0.1:5174", 61 | ] 62 | ALLOWED_METHODS: list[str] = ["*"] 63 | ALLOWED_HEADERS: list[str] = ["*"] 64 | 65 | LOGGING_LEVEL: int = logging.INFO 66 | LOGGERS: tuple[str, str] = ("uvicorn.asgi", "uvicorn.access") 67 | 68 | HASHING_ALGORITHM_LAYER_1: str = decouple.config("HASHING_ALGORITHM_LAYER_1", cast=str) # type: ignore 69 | HASHING_ALGORITHM_LAYER_2: str = decouple.config("HASHING_ALGORITHM_LAYER_2", cast=str) # type: ignore 70 | HASHING_SALT: str = decouple.config("HASHING_SALT", cast=str) # type: ignore 71 | JWT_ALGORITHM: str = decouple.config("JWT_ALGORITHM", cast=str) # type: ignore 72 | 73 | class Config(pydantic.BaseConfig): 74 | case_sensitive: bool = True 75 | env_file: str = f"{str(ROOT_DIR)}/.env" 76 | validate_assignment: bool = True 77 | 78 | @property 79 | def set_backend_app_attributes(self) -> dict[str, str | bool | None]: 80 | """ 81 | Set all `FastAPI` class' attributes with the custom values defined in `BackendBaseSettings`. 82 | """ 83 | return { 84 | "title": self.TITLE, 85 | "version": self.VERSION, 86 | "debug": self.DEBUG, 87 | "description": self.DESCRIPTION, 88 | "docs_url": self.DOCS_URL, 89 | "openapi_url": self.OPENAPI_URL, 90 | "redoc_url": self.REDOC_URL, 91 | "openapi_prefix": self.OPENAPI_PREFIX, 92 | "api_prefix": self.API_PREFIX, 93 | } 94 | -------------------------------------------------------------------------------- /backend/src/config/settings/development.py: -------------------------------------------------------------------------------- 1 | from src.config.settings.base import BackendBaseSettings 2 | from src.config.settings.environment import Environment 3 | 4 | 5 | class BackendDevSettings(BackendBaseSettings): 6 | DESCRIPTION: str | None = "Development Environment." 7 | DEBUG: bool = True 8 | ENVIRONMENT: Environment = Environment.DEVELOPMENT 9 | -------------------------------------------------------------------------------- /backend/src/config/settings/environment.py: -------------------------------------------------------------------------------- 1 | import enum 2 | 3 | 4 | class Environment(str, enum.Enum): 5 | PRODUCTION: str = "PROD" # type: ignore 6 | DEVELOPMENT: str = "DEV" # type: ignore 7 | STAGING: str = "STAGE" # type:ignore 8 | -------------------------------------------------------------------------------- /backend/src/config/settings/production.py: -------------------------------------------------------------------------------- 1 | from src.config.settings.base import BackendBaseSettings 2 | from src.config.settings.environment import Environment 3 | 4 | 5 | class BackendProdSettings(BackendBaseSettings): 6 | DESCRIPTION: str | None = "Production Environment." 7 | ENVIRONMENT: Environment = Environment.PRODUCTION 8 | -------------------------------------------------------------------------------- /backend/src/config/settings/staging.py: -------------------------------------------------------------------------------- 1 | from src.config.settings.base import BackendBaseSettings 2 | from src.config.settings.environment import Environment 3 | 4 | 5 | class BackendStageSettings(BackendBaseSettings): 6 | DESCRIPTION: str | None = "Test Environment." 7 | DEBUG: bool = True 8 | ENVIRONMENT: Environment = Environment.STAGING 9 | -------------------------------------------------------------------------------- /backend/src/main.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | import uvicorn 3 | from fastapi.middleware.cors import CORSMiddleware 4 | 5 | from src.api.endpoints import router as api_endpoint_router 6 | from src.config.events import execute_backend_server_event_handler, terminate_backend_server_event_handler 7 | from src.config.manager import settings 8 | 9 | 10 | def initialize_backend_application() -> fastapi.FastAPI: 11 | app = fastapi.FastAPI(**settings.set_backend_app_attributes) # type: ignore 12 | 13 | app.add_middleware( 14 | CORSMiddleware, 15 | allow_origins=settings.ALLOWED_ORIGINS, 16 | allow_credentials=settings.IS_ALLOWED_CREDENTIALS, 17 | allow_methods=settings.ALLOWED_METHODS, 18 | allow_headers=settings.ALLOWED_HEADERS, 19 | ) 20 | 21 | app.add_event_handler( 22 | "startup", 23 | execute_backend_server_event_handler(backend_app=app), 24 | ) 25 | app.add_event_handler( 26 | "shutdown", 27 | terminate_backend_server_event_handler(backend_app=app), 28 | ) 29 | 30 | app.include_router(router=api_endpoint_router, prefix=settings.API_PREFIX) 31 | 32 | return app 33 | 34 | 35 | backend_app: fastapi.FastAPI = initialize_backend_application() 36 | 37 | if __name__ == "__main__": 38 | uvicorn.run( 39 | app="main:backend_app", 40 | host=settings.SERVER_HOST, 41 | port=settings.SERVER_PORT, 42 | reload=settings.DEBUG, 43 | workers=settings.SERVER_WORKERS, 44 | log_level=settings.LOGGING_LEVEL, 45 | ) 46 | -------------------------------------------------------------------------------- /backend/src/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/models/__init__.py -------------------------------------------------------------------------------- /backend/src/models/db/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/models/db/__init__.py -------------------------------------------------------------------------------- /backend/src/models/db/account.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | import sqlalchemy 4 | from sqlalchemy.orm import Mapped as SQLAlchemyMapped, mapped_column as sqlalchemy_mapped_column 5 | from sqlalchemy.sql import functions as sqlalchemy_functions 6 | 7 | from src.repository.table import Base 8 | 9 | 10 | class Account(Base): # type: ignore 11 | __tablename__ = "account" 12 | 13 | id: SQLAlchemyMapped[int] = sqlalchemy_mapped_column(primary_key=True, autoincrement="auto") 14 | username: SQLAlchemyMapped[str] = sqlalchemy_mapped_column( 15 | sqlalchemy.String(length=64), nullable=False, unique=True 16 | ) 17 | email: SQLAlchemyMapped[str] = sqlalchemy_mapped_column(sqlalchemy.String(length=64), nullable=False, unique=True) 18 | _hashed_password: SQLAlchemyMapped[str] = sqlalchemy_mapped_column(sqlalchemy.String(length=1024), nullable=True) 19 | _hash_salt: SQLAlchemyMapped[str] = sqlalchemy_mapped_column(sqlalchemy.String(length=1024), nullable=True) 20 | is_verified: SQLAlchemyMapped[bool] = sqlalchemy_mapped_column(sqlalchemy.Boolean, nullable=False, default=False) 21 | is_active: SQLAlchemyMapped[bool] = sqlalchemy_mapped_column(sqlalchemy.Boolean, nullable=False, default=False) 22 | is_logged_in: SQLAlchemyMapped[bool] = sqlalchemy_mapped_column(sqlalchemy.Boolean, nullable=False, default=False) 23 | created_at: SQLAlchemyMapped[datetime.datetime] = sqlalchemy_mapped_column( 24 | sqlalchemy.DateTime(timezone=True), nullable=False, server_default=sqlalchemy_functions.now() 25 | ) 26 | updated_at: SQLAlchemyMapped[datetime.datetime] = sqlalchemy_mapped_column( 27 | sqlalchemy.DateTime(timezone=True), 28 | nullable=True, 29 | server_onupdate=sqlalchemy.schema.FetchedValue(for_update=True), 30 | ) 31 | 32 | __mapper_args__ = {"eager_defaults": True} 33 | 34 | @property 35 | def hashed_password(self) -> str: 36 | return self._hashed_password 37 | 38 | def set_hashed_password(self, hashed_password: str) -> None: 39 | self._hashed_password = hashed_password 40 | 41 | @property 42 | def hash_salt(self) -> str: 43 | return self._hash_salt 44 | 45 | def set_hash_salt(self, hash_salt: str) -> None: 46 | self._hash_salt = hash_salt 47 | -------------------------------------------------------------------------------- /backend/src/models/schemas/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/models/schemas/__init__.py -------------------------------------------------------------------------------- /backend/src/models/schemas/account.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | import pydantic 4 | 5 | from src.models.schemas.base import BaseSchemaModel 6 | 7 | 8 | class AccountInCreate(BaseSchemaModel): 9 | username: str 10 | email: pydantic.EmailStr 11 | password: str 12 | 13 | 14 | class AccountInUpdate(BaseSchemaModel): 15 | username: str | None 16 | email: str | None 17 | password: str | None 18 | 19 | 20 | class AccountInLogin(BaseSchemaModel): 21 | username: str 22 | email: pydantic.EmailStr 23 | password: str 24 | 25 | 26 | class AccountWithToken(BaseSchemaModel): 27 | token: str 28 | username: str 29 | email: pydantic.EmailStr 30 | is_verified: bool 31 | is_active: bool 32 | is_logged_in: bool 33 | created_at: datetime.datetime 34 | updated_at: datetime.datetime | None 35 | 36 | 37 | class AccountInResponse(BaseSchemaModel): 38 | id: int 39 | authorized_account: AccountWithToken 40 | -------------------------------------------------------------------------------- /backend/src/models/schemas/base.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import typing 3 | 4 | import pydantic 5 | 6 | from src.utilities.formatters.datetime_formatter import format_datetime_into_isoformat 7 | from src.utilities.formatters.field_formatter import format_dict_key_to_camel_case 8 | 9 | 10 | class BaseSchemaModel(pydantic.BaseModel): 11 | class Config(pydantic.BaseConfig): 12 | orm_mode: bool = True 13 | validate_assignment: bool = True 14 | allow_population_by_field_name: bool = True 15 | json_encoders: dict = {datetime.datetime: format_datetime_into_isoformat} 16 | alias_generator: typing.Any = format_dict_key_to_camel_case 17 | -------------------------------------------------------------------------------- /backend/src/models/schemas/jwt.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | import pydantic 4 | 5 | 6 | class JWToken(pydantic.BaseModel): 7 | exp: datetime.datetime 8 | sub: str 9 | 10 | 11 | class JWTAccount(pydantic.BaseModel): 12 | username: str 13 | email: pydantic.EmailStr 14 | -------------------------------------------------------------------------------- /backend/src/repository/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/repository/__init__.py -------------------------------------------------------------------------------- /backend/src/repository/base.py: -------------------------------------------------------------------------------- 1 | from src.models.db.account import Account 2 | from src.repository.table import Base 3 | -------------------------------------------------------------------------------- /backend/src/repository/crud/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/repository/crud/__init__.py -------------------------------------------------------------------------------- /backend/src/repository/crud/account.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | import sqlalchemy 4 | from sqlalchemy.sql import functions as sqlalchemy_functions 5 | 6 | from src.models.db.account import Account 7 | from src.models.schemas.account import AccountInCreate, AccountInLogin, AccountInUpdate 8 | from src.repository.crud.base import BaseCRUDRepository 9 | from src.securities.hashing.password import pwd_generator 10 | from src.securities.verifications.credentials import credential_verifier 11 | from src.utilities.exceptions.database import EntityAlreadyExists, EntityDoesNotExist 12 | from src.utilities.exceptions.password import PasswordDoesNotMatch 13 | 14 | 15 | class AccountCRUDRepository(BaseCRUDRepository): 16 | async def create_account(self, account_create: AccountInCreate) -> Account: 17 | new_account = Account(username=account_create.username, email=account_create.email, is_logged_in=True) 18 | 19 | new_account.set_hash_salt(hash_salt=pwd_generator.generate_salt) 20 | new_account.set_hashed_password( 21 | hashed_password=pwd_generator.generate_hashed_password( 22 | hash_salt=new_account.hash_salt, new_password=account_create.password 23 | ) 24 | ) 25 | 26 | self.async_session.add(instance=new_account) 27 | await self.async_session.commit() 28 | await self.async_session.refresh(instance=new_account) 29 | 30 | return new_account 31 | 32 | async def read_accounts(self) -> typing.Sequence[Account]: 33 | stmt = sqlalchemy.select(Account) 34 | query = await self.async_session.execute(statement=stmt) 35 | return query.scalars().all() 36 | 37 | async def read_account_by_id(self, id: int) -> Account: 38 | stmt = sqlalchemy.select(Account).where(Account.id == id) 39 | query = await self.async_session.execute(statement=stmt) 40 | 41 | if not query: 42 | raise EntityDoesNotExist("Account with id `{id}` does not exist!") 43 | 44 | return query.scalar() # type: ignore 45 | 46 | async def read_account_by_username(self, username: str) -> Account: 47 | stmt = sqlalchemy.select(Account).where(Account.username == username) 48 | query = await self.async_session.execute(statement=stmt) 49 | 50 | if not query: 51 | raise EntityDoesNotExist("Account with username `{username}` does not exist!") 52 | 53 | return query.scalar() # type: ignore 54 | 55 | async def read_account_by_email(self, email: str) -> Account: 56 | stmt = sqlalchemy.select(Account).where(Account.email == email) 57 | query = await self.async_session.execute(statement=stmt) 58 | 59 | if not query: 60 | raise EntityDoesNotExist("Account with email `{email}` does not exist!") 61 | 62 | return query.scalar() # type: ignore 63 | 64 | async def read_user_by_password_authentication(self, account_login: AccountInLogin) -> Account: 65 | stmt = sqlalchemy.select(Account).where( 66 | Account.username == account_login.username, Account.email == account_login.email 67 | ) 68 | query = await self.async_session.execute(statement=stmt) 69 | db_account = query.scalar() 70 | 71 | if not db_account: 72 | raise EntityDoesNotExist("Wrong username or wrong email!") 73 | 74 | if not pwd_generator.is_password_authenticated(hash_salt=db_account.hash_salt, password=account_login.password, hashed_password=db_account.hashed_password): # type: ignore 75 | raise PasswordDoesNotMatch("Password does not match!") 76 | 77 | return db_account # type: ignore 78 | 79 | async def update_account_by_id(self, id: int, account_update: AccountInUpdate) -> Account: 80 | new_account_data = account_update.dict() 81 | 82 | select_stmt = sqlalchemy.select(Account).where(Account.id == id) 83 | query = await self.async_session.execute(statement=select_stmt) 84 | update_account = query.scalar() 85 | 86 | if not update_account: 87 | raise EntityDoesNotExist(f"Account with id `{id}` does not exist!") # type: ignore 88 | 89 | update_stmt = sqlalchemy.update(table=Account).where(Account.id == update_account.id).values(updated_at=sqlalchemy_functions.now()) # type: ignore 90 | 91 | if new_account_data["username"]: 92 | update_stmt = update_stmt.values(username=new_account_data["username"]) 93 | 94 | if new_account_data["email"]: 95 | update_stmt = update_stmt.values(username=new_account_data["email"]) 96 | 97 | if new_account_data["password"]: 98 | update_account.set_hash_salt(hash_salt=pwd_generator.generate_salt) # type: ignore 99 | update_account.set_hashed_password(hashed_password=pwd_generator.generate_hashed_password(hash_salt=update_account.hash_salt, new_password=new_account_data["password"])) # type: ignore 100 | 101 | await self.async_session.execute(statement=update_stmt) 102 | await self.async_session.commit() 103 | await self.async_session.refresh(instance=update_account) 104 | 105 | return update_account # type: ignore 106 | 107 | async def delete_account_by_id(self, id: int) -> str: 108 | select_stmt = sqlalchemy.select(Account).where(Account.id == id) 109 | query = await self.async_session.execute(statement=select_stmt) 110 | delete_account = query.scalar() 111 | 112 | if not delete_account: 113 | raise EntityDoesNotExist(f"Account with id `{id}` does not exist!") # type: ignore 114 | 115 | stmt = sqlalchemy.delete(table=Account).where(Account.id == delete_account.id) 116 | 117 | await self.async_session.execute(statement=stmt) 118 | await self.async_session.commit() 119 | 120 | return f"Account with id '{id}' is successfully deleted!" 121 | 122 | async def is_username_taken(self, username: str) -> bool: 123 | username_stmt = sqlalchemy.select(Account.username).select_from(Account).where(Account.username == username) 124 | username_query = await self.async_session.execute(username_stmt) 125 | db_username = username_query.scalar() 126 | 127 | if not credential_verifier.is_username_available(username=db_username): 128 | raise EntityAlreadyExists(f"The username `{username}` is already taken!") # type: ignore 129 | 130 | return True 131 | 132 | async def is_email_taken(self, email: str) -> bool: 133 | email_stmt = sqlalchemy.select(Account.email).select_from(Account).where(Account.email == email) 134 | email_query = await self.async_session.execute(email_stmt) 135 | db_email = email_query.scalar() 136 | 137 | if not credential_verifier.is_email_available(email=db_email): 138 | raise EntityAlreadyExists(f"The email `{email}` is already registered!") # type: ignore 139 | 140 | return True 141 | -------------------------------------------------------------------------------- /backend/src/repository/crud/base.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.asyncio import AsyncSession as SQLAlchemyAsyncSession 2 | 3 | 4 | class BaseCRUDRepository: 5 | def __init__(self, async_session: SQLAlchemyAsyncSession): 6 | self.async_session = async_session 7 | -------------------------------------------------------------------------------- /backend/src/repository/database.py: -------------------------------------------------------------------------------- 1 | import pydantic 2 | from sqlalchemy.ext.asyncio import ( 3 | async_sessionmaker as sqlalchemy_async_sessionmaker, 4 | AsyncEngine as SQLAlchemyAsyncEngine, 5 | AsyncSession as SQLAlchemyAsyncSession, 6 | create_async_engine as create_sqlalchemy_async_engine, 7 | ) 8 | from sqlalchemy.pool import Pool as SQLAlchemyPool, QueuePool as SQLAlchemyQueuePool 9 | 10 | from src.config.manager import settings 11 | 12 | 13 | class AsyncDatabase: 14 | def __init__(self): 15 | self.postgres_uri: pydantic.PostgresDsn = pydantic.PostgresDsn( 16 | url=f"{settings.DB_POSTGRES_SCHEMA}://{settings.DB_POSTGRES_USENRAME}:{settings.DB_POSTGRES_PASSWORD}@{settings.DB_POSTGRES_HOST}:{settings.DB_POSTGRES_PORT}/{settings.DB_POSTGRES_NAME}", 17 | scheme=settings.DB_POSTGRES_SCHEMA, 18 | ) 19 | self.async_engine: SQLAlchemyAsyncEngine = create_sqlalchemy_async_engine( 20 | url=self.set_async_db_uri, 21 | echo=settings.IS_DB_ECHO_LOG, 22 | pool_size=settings.DB_POOL_SIZE, 23 | max_overflow=settings.DB_POOL_OVERFLOW, 24 | poolclass=SQLAlchemyQueuePool, 25 | ) 26 | self.async_session: SQLAlchemyAsyncSession = SQLAlchemyAsyncSession(bind=self.async_engine) 27 | self.pool: SQLAlchemyPool = self.async_engine.pool 28 | 29 | @property 30 | def set_async_db_uri(self) -> str | pydantic.PostgresDsn: 31 | """ 32 | Set the synchronous database driver into asynchronous version by utilizing AsyncPG: 33 | 34 | `postgresql://` => `postgresql+asyncpg://` 35 | """ 36 | return ( 37 | self.postgres_uri.replace("postgresql://", "postgresql+asyncpg://") 38 | if self.postgres_uri 39 | else self.postgres_uri 40 | ) 41 | 42 | 43 | async_db: AsyncDatabase = AsyncDatabase() 44 | -------------------------------------------------------------------------------- /backend/src/repository/events.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | import loguru 3 | from sqlalchemy import event 4 | from sqlalchemy.dialects.postgresql.asyncpg import AsyncAdapt_asyncpg_connection 5 | from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSessionTransaction 6 | from sqlalchemy.pool.base import _ConnectionRecord 7 | 8 | from src.repository.database import async_db 9 | from src.repository.table import Base 10 | 11 | 12 | @event.listens_for(target=async_db.async_engine.sync_engine, identifier="connect") 13 | def inspect_db_server_on_connection( 14 | db_api_connection: AsyncAdapt_asyncpg_connection, connection_record: _ConnectionRecord 15 | ) -> None: 16 | loguru.logger.info(f"New DB API Connection ---\n {db_api_connection}") 17 | loguru.logger.info(f"Connection Record ---\n {connection_record}") 18 | 19 | 20 | @event.listens_for(target=async_db.async_engine.sync_engine, identifier="close") 21 | def inspect_db_server_on_close( 22 | db_api_connection: AsyncAdapt_asyncpg_connection, connection_record: _ConnectionRecord 23 | ) -> None: 24 | loguru.logger.info(f"Closing DB API Connection ---\n {db_api_connection}") 25 | loguru.logger.info(f"Closed Connection Record ---\n {connection_record}") 26 | 27 | 28 | async def initialize_db_tables(connection: AsyncConnection) -> None: 29 | loguru.logger.info("Database Table Creation --- Initializing . . .") 30 | 31 | await connection.run_sync(Base.metadata.drop_all) 32 | await connection.run_sync(Base.metadata.create_all) 33 | 34 | loguru.logger.info("Database Table Creation --- Successfully Initialized!") 35 | 36 | 37 | async def initialize_db_connection(backend_app: fastapi.FastAPI) -> None: 38 | loguru.logger.info("Database Connection --- Establishing . . .") 39 | 40 | backend_app.state.db = async_db 41 | 42 | async with backend_app.state.db.async_engine.begin() as connection: 43 | await initialize_db_tables(connection=connection) 44 | 45 | loguru.logger.info("Database Connection --- Successfully Established!") 46 | 47 | 48 | async def dispose_db_connection(backend_app: fastapi.FastAPI) -> None: 49 | loguru.logger.info("Database Connection --- Disposing . . .") 50 | 51 | await backend_app.state.db.async_engine.dispose() 52 | 53 | loguru.logger.info("Database Connection --- Successfully Disposed!") 54 | -------------------------------------------------------------------------------- /backend/src/repository/migrations/env.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from logging.config import fileConfig 3 | 4 | from alembic import context 5 | from sqlalchemy import engine_from_config 6 | from sqlalchemy.engine import Connection 7 | from sqlalchemy.ext.asyncio import AsyncEngine 8 | from sqlalchemy.pool import NullPool as SQLAlchemyNullPool 9 | 10 | from src.repository.base import Base 11 | from src.repository.database import async_db 12 | 13 | config = context.config 14 | config.set_main_option(name="sqlalchemy.url", value=str(async_db.set_async_db_uri)) 15 | target_metadata = Base.metadata 16 | 17 | if config.config_file_name is not None: 18 | fileConfig(config.config_file_name) 19 | 20 | 21 | def run_migrations_offline() -> None: 22 | """Run migrations in 'offline' mode. 23 | 24 | This configures the context with just a URL 25 | and not an Engine, though an Engine is acceptable 26 | here as well. By skipping the Engine creation 27 | we don't even need a DBAPI to be available. 28 | 29 | Calls to context.execute() here emit the given string to the 30 | script output. 31 | 32 | """ 33 | url = config.get_main_option("sqlalchemy.url") 34 | context.configure( 35 | url=url, 36 | target_metadata=target_metadata, 37 | literal_binds=True, 38 | dialect_opts={"paramstyle": "named"}, 39 | ) 40 | 41 | with context.begin_transaction(): 42 | context.run_migrations() 43 | 44 | 45 | def do_run_migrations(connection: Connection) -> None: 46 | context.configure(connection=connection, target_metadata=target_metadata) 47 | 48 | with context.begin_transaction(): 49 | context.run_migrations() 50 | 51 | 52 | async def run_migrations_online() -> None: 53 | """Run migrations in 'online' mode. 54 | 55 | In this scenario we need to create an Engine 56 | and associate a connection with the context. 57 | 58 | """ 59 | connectable = AsyncEngine( 60 | engine_from_config( 61 | config.get_section(config.config_ini_section), # type: ignore 62 | prefix="sqlalchemy.", 63 | poolclass=SQLAlchemyNullPool, 64 | future=True, 65 | ) 66 | ) 67 | 68 | async with connectable.connect() as connection: 69 | await connection.run_sync(do_run_migrations) 70 | 71 | await connectable.dispose() 72 | 73 | 74 | if context.is_offline_mode(): 75 | run_migrations_offline() 76 | else: 77 | asyncio.run(run_migrations_online()) 78 | -------------------------------------------------------------------------------- /backend/src/repository/migrations/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | ${imports if imports else ""} 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = ${repr(up_revision)} 14 | down_revision = ${repr(down_revision)} 15 | branch_labels = ${repr(branch_labels)} 16 | depends_on = ${repr(depends_on)} 17 | 18 | 19 | def upgrade() -> None: 20 | ${upgrades if upgrades else "pass"} 21 | 22 | 23 | def downgrade() -> None: 24 | ${downgrades if downgrades else "pass"} 25 | -------------------------------------------------------------------------------- /backend/src/repository/migrations/versions/2022_12_09_1825-60d1844cb5d3_initial_migration_fo_account_table.py: -------------------------------------------------------------------------------- 1 | """initial migration for account table 2 | 3 | Revision ID: 60d1844cb5d3 4 | Revises: 5 | Create Date: 2022-12-09 18:25:25.301186 6 | 7 | """ 8 | 9 | import sqlalchemy as sa 10 | from alembic import op 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = "60d1844cb5d3" 14 | down_revision = None 15 | branch_labels = None 16 | depends_on = None 17 | 18 | 19 | def upgrade() -> None: 20 | # ### commands auto generated by Alembic - please adjust! ### 21 | op.create_table( 22 | "account", 23 | sa.Column("id", sa.Integer(), nullable=False), 24 | sa.Column("username", sa.String(length=64), nullable=False), 25 | sa.Column("email", sa.String(length=64), nullable=False), 26 | sa.Column("_hashed_password", sa.String(length=1024), nullable=True), 27 | sa.Column("_hash_salt", sa.String(length=1024), nullable=True), 28 | sa.Column("is_verified", sa.Boolean(), nullable=False), 29 | sa.Column("is_active", sa.Boolean(), nullable=False), 30 | sa.Column("is_logged_in", sa.Boolean(), nullable=False), 31 | sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), 32 | sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True), 33 | sa.PrimaryKeyConstraint("id"), 34 | sa.UniqueConstraint("email"), 35 | sa.UniqueConstraint("username"), 36 | ) 37 | # ### end Alembic commands ### 38 | 39 | 40 | def downgrade() -> None: 41 | # ### commands auto generated by Alembic - please adjust! ### 42 | op.drop_table("account") 43 | # ### end Alembic commands ### 44 | -------------------------------------------------------------------------------- /backend/src/repository/table.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | import sqlalchemy 4 | from sqlalchemy.orm import DeclarativeBase 5 | 6 | 7 | class DBTable(DeclarativeBase): 8 | metadata: sqlalchemy.MetaData = sqlalchemy.MetaData() # type: ignore 9 | 10 | 11 | Base: typing.Type[DeclarativeBase] = DBTable 12 | -------------------------------------------------------------------------------- /backend/src/securities/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/securities/__init__.py -------------------------------------------------------------------------------- /backend/src/securities/authorizations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/securities/authorizations/__init__.py -------------------------------------------------------------------------------- /backend/src/securities/authorizations/jwt.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | import pydantic 4 | from jose import jwt as jose_jwt, JWTError as JoseJWTError 5 | 6 | from src.config.manager import settings 7 | from src.models.db.account import Account 8 | from src.models.schemas.jwt import JWTAccount, JWToken 9 | from src.utilities.exceptions.database import EntityDoesNotExist 10 | 11 | 12 | class JWTGenerator: 13 | def __init__(self): 14 | pass 15 | 16 | def _generate_jwt_token( 17 | self, 18 | *, 19 | jwt_data: dict[str, str], 20 | expires_delta: datetime.timedelta | None = None, 21 | ) -> str: 22 | to_encode = jwt_data.copy() 23 | 24 | if expires_delta: 25 | expire = datetime.datetime.utcnow() + expires_delta 26 | 27 | else: 28 | expire = datetime.datetime.utcnow() + datetime.timedelta(minutes=settings.JWT_MIN) 29 | 30 | to_encode.update(JWToken(exp=expire, sub=settings.JWT_SUBJECT).dict()) 31 | 32 | return jose_jwt.encode(to_encode, key=settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM) 33 | 34 | def generate_access_token(self, account: Account) -> str: 35 | if not account: 36 | raise EntityDoesNotExist(f"Cannot generate JWT token for without Account entity!") 37 | 38 | return self._generate_jwt_token( 39 | jwt_data=JWTAccount(username=account.username, email=account.email).dict(), # type: ignore 40 | expires_delta=datetime.timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRATION_TIME), 41 | ) 42 | 43 | def retrieve_details_from_token(self, token: str, secret_key: str) -> list[str]: 44 | try: 45 | payload = jose_jwt.decode(token=token, key=secret_key, algorithms=[settings.JWT_ALGORITHM]) 46 | jwt_account = JWTAccount(username=payload["username"], email=payload["email"]) 47 | 48 | except JoseJWTError as token_decode_error: 49 | raise ValueError("Unable to decode JWT Token") from token_decode_error 50 | 51 | except pydantic.ValidationError as validation_error: 52 | raise ValueError("Invalid payload in token") from validation_error 53 | 54 | return [jwt_account.username, jwt_account.email] 55 | 56 | 57 | def get_jwt_generator() -> JWTGenerator: 58 | return JWTGenerator() 59 | 60 | 61 | jwt_generator: JWTGenerator = get_jwt_generator() 62 | -------------------------------------------------------------------------------- /backend/src/securities/hashing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/securities/hashing/__init__.py -------------------------------------------------------------------------------- /backend/src/securities/hashing/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | from src.config.manager import settings 4 | 5 | 6 | class HashGenerator: 7 | def __init__(self): 8 | self._hash_ctx_layer_1: CryptContext = CryptContext( 9 | schemes=[settings.HASHING_ALGORITHM_LAYER_1], deprecated="auto" 10 | ) 11 | self._hash_ctx_layer_2: CryptContext = CryptContext( 12 | schemes=[settings.HASHING_ALGORITHM_LAYER_2], deprecated="auto" 13 | ) 14 | self._hash_ctx_salt: str = settings.HASHING_SALT 15 | 16 | @property 17 | def _get_hashing_salt(self) -> str: 18 | return self._hash_ctx_salt 19 | 20 | @property 21 | def generate_password_salt_hash(self) -> str: 22 | """ 23 | A function to generate a hash from Bcrypt to append to the user password. 24 | """ 25 | return self._hash_ctx_layer_1.hash(secret=self._get_hashing_salt) 26 | 27 | def generate_password_hash(self, hash_salt: str, password: str) -> str: 28 | """ 29 | A function that adds the user's password with the layer 1 Bcrypt hash, before 30 | hash it for the second time using Argon2 algorithm. 31 | """ 32 | return self._hash_ctx_layer_2.hash(secret=hash_salt + password) 33 | 34 | def is_password_verified(self, password: str, hashed_password: str) -> bool: 35 | """ 36 | A function that decodes users' password and verifies whether it is the correct password. 37 | """ 38 | return self._hash_ctx_layer_2.verify(secret=password, hash=hashed_password) 39 | 40 | 41 | def get_hash_generator() -> HashGenerator: 42 | return HashGenerator() 43 | 44 | 45 | hash_generator: HashGenerator = get_hash_generator() 46 | -------------------------------------------------------------------------------- /backend/src/securities/hashing/password.py: -------------------------------------------------------------------------------- 1 | from src.securities.hashing.hash import hash_generator 2 | 3 | 4 | class PasswordGenerator: 5 | @property 6 | def generate_salt(self) -> str: 7 | return hash_generator.generate_password_salt_hash 8 | 9 | def generate_hashed_password(self, hash_salt: str, new_password: str) -> str: 10 | return hash_generator.generate_password_hash(hash_salt=hash_salt, password=new_password) 11 | 12 | def is_password_authenticated(self, hash_salt: str, password: str, hashed_password: str) -> bool: 13 | return hash_generator.is_password_verified(password=hash_salt + password, hashed_password=hashed_password) 14 | 15 | 16 | def get_pwd_generator() -> PasswordGenerator: 17 | return PasswordGenerator() 18 | 19 | 20 | pwd_generator: PasswordGenerator = get_pwd_generator() 21 | -------------------------------------------------------------------------------- /backend/src/securities/verifications/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/securities/verifications/__init__.py -------------------------------------------------------------------------------- /backend/src/securities/verifications/credentials.py: -------------------------------------------------------------------------------- 1 | class CredentialVerifier: 2 | def is_username_available(self, username: str | None) -> bool: 3 | if username: 4 | return False 5 | return True 6 | 7 | def is_email_available(self, email: str | None) -> bool: 8 | if email: 9 | return False 10 | return True 11 | 12 | 13 | def get_credential_verifier() -> CredentialVerifier: 14 | return CredentialVerifier() 15 | 16 | 17 | credential_verifier: CredentialVerifier = get_credential_verifier() 18 | -------------------------------------------------------------------------------- /backend/src/utilities/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/exceptions/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/database.py: -------------------------------------------------------------------------------- 1 | class EntityDoesNotExist(Exception): 2 | """ 3 | Throw an exception when the data does not exist in the database. 4 | """ 5 | 6 | 7 | class EntityAlreadyExists(Exception): 8 | """ 9 | Throw an exception when the data already exist in the database. 10 | """ 11 | -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/http/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/exceptions/http/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/http/exc_400.py: -------------------------------------------------------------------------------- 1 | """ 2 | The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server 3 | cannot or will not process the request due to something that is perceivedto be a client error 4 | (for example, malformed request syntax, invalid request message framing, or deceptive request routing). 5 | """ 6 | 7 | import fastapi 8 | 9 | from src.utilities.messages.exceptions.http.exc_details import ( 10 | http_400_email_details, 11 | http_400_sigin_credentials_details, 12 | http_400_signup_credentials_details, 13 | http_400_username_details, 14 | ) 15 | 16 | 17 | async def http_exc_400_credentials_bad_signup_request() -> Exception: 18 | return fastapi.HTTPException( 19 | status_code=fastapi.status.HTTP_400_BAD_REQUEST, 20 | detail=http_400_signup_credentials_details(), 21 | ) 22 | 23 | 24 | async def http_exc_400_credentials_bad_signin_request() -> Exception: 25 | return fastapi.HTTPException( 26 | status_code=fastapi.status.HTTP_400_BAD_REQUEST, 27 | detail=http_400_sigin_credentials_details(), 28 | ) 29 | 30 | 31 | async def http_400_exc_bad_username_request(username: str) -> Exception: 32 | return fastapi.HTTPException( 33 | status_code=fastapi.status.HTTP_400_BAD_REQUEST, 34 | detail=http_400_username_details(username=username), 35 | ) 36 | 37 | 38 | async def http_400_exc_bad_email_request(email: str) -> Exception: 39 | return fastapi.HTTPException( 40 | status_code=fastapi.status.HTTP_400_BAD_REQUEST, 41 | detail=http_400_email_details(email=email), 42 | ) 43 | -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/http/exc_401.py: -------------------------------------------------------------------------------- 1 | """ 2 | The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client 3 | request has not been completed because it lacks valid authentication credentials for the requested resource. 4 | """ 5 | 6 | import fastapi 7 | 8 | from src.utilities.messages.exceptions.http.exc_details import http_401_unauthorized_details 9 | 10 | 11 | async def http_exc_401_cunauthorized_request() -> Exception: 12 | return fastapi.HTTPException( 13 | status_code=fastapi.status.HTTP_400_BAD_REQUEST, 14 | detail=http_401_unauthorized_details(), 15 | ) 16 | -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/http/exc_403.py: -------------------------------------------------------------------------------- 1 | """ 2 | The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it. 3 | """ 4 | 5 | import fastapi 6 | 7 | from src.utilities.messages.exceptions.http.exc_details import http_403_forbidden_details 8 | 9 | 10 | async def http_403_exc_forbidden_request() -> Exception: 11 | return fastapi.HTTPException( 12 | status_code=fastapi.status.HTTP_403_FORBIDDEN, 13 | detail=http_403_forbidden_details(), 14 | ) 15 | -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/http/exc_404.py: -------------------------------------------------------------------------------- 1 | """ 2 | The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource. 3 | """ 4 | 5 | import fastapi 6 | 7 | from src.utilities.messages.exceptions.http.exc_details import ( 8 | http_404_email_details, 9 | http_404_id_details, 10 | http_404_username_details, 11 | ) 12 | 13 | 14 | async def http_404_exc_email_not_found_request(email: str) -> Exception: 15 | return fastapi.HTTPException( 16 | status_code=fastapi.status.HTTP_404_NOT_FOUND, 17 | detail=http_404_email_details(email=email), 18 | ) 19 | 20 | 21 | async def http_404_exc_id_not_found_request(id: int) -> Exception: 22 | return fastapi.HTTPException( 23 | status_code=fastapi.status.HTTP_404_NOT_FOUND, 24 | detail=http_404_id_details(id=id), 25 | ) 26 | 27 | 28 | async def http_404_exc_username_not_found_request(username: str) -> Exception: 29 | return fastapi.HTTPException( 30 | status_code=fastapi.status.HTTP_404_NOT_FOUND, 31 | detail=http_404_username_details(username=username), 32 | ) 33 | -------------------------------------------------------------------------------- /backend/src/utilities/exceptions/password.py: -------------------------------------------------------------------------------- 1 | class PasswordDoesNotMatch(Exception): 2 | """ 3 | Throw an exception when the account password does not match the entitiy's hashed password from the database. 4 | """ 5 | -------------------------------------------------------------------------------- /backend/src/utilities/formatters/datetime_formatter.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | 4 | def format_datetime_into_isoformat(date_time: datetime.datetime) -> str: 5 | return date_time.replace(tzinfo=datetime.timezone.utc).isoformat().replace("+00:00", "Z") 6 | -------------------------------------------------------------------------------- /backend/src/utilities/formatters/field_formatter.py: -------------------------------------------------------------------------------- 1 | def format_dict_key_to_camel_case(dict_key: str) -> str: 2 | return "".join(word if idx == 0 else word.capitalize() for idx, word in enumerate(dict_key.split("_"))) 3 | -------------------------------------------------------------------------------- /backend/src/utilities/messages/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/messages/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/messages/exceptions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/messages/exceptions/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/messages/exceptions/database.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/messages/exceptions/database.py -------------------------------------------------------------------------------- /backend/src/utilities/messages/exceptions/http/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/src/utilities/messages/exceptions/http/__init__.py -------------------------------------------------------------------------------- /backend/src/utilities/messages/exceptions/http/exc_details.py: -------------------------------------------------------------------------------- 1 | def http_400_username_details(username: str) -> str: 2 | return f"The username {username} is taken! Be creative and choose another one!" 3 | 4 | 5 | def http_400_email_details(email: str) -> str: 6 | return f"The email {email} is already registered! Be creative and choose another one!" 7 | 8 | 9 | def http_400_signup_credentials_details() -> str: 10 | return "Signup failed! Recheck all your credentials!" 11 | 12 | 13 | def http_400_sigin_credentials_details() -> str: 14 | return "Signin failed! Recheck all your credentials!" 15 | 16 | 17 | def http_401_unauthorized_details() -> str: 18 | return "Refused to complete request due to lack of valid authentication!" 19 | 20 | 21 | def http_403_forbidden_details() -> str: 22 | return "Refused access to the requested resource!" 23 | 24 | 25 | def http_404_id_details(id: int) -> str: 26 | return f"Either the account with id `{id}` doesn't exist, has been deleted, or you are not authorized!" 27 | 28 | 29 | def http_404_username_details(username: str) -> str: 30 | return f"Either the account with username `{username}` doesn't exist, has been deleted, or you are not authorized!" 31 | 32 | 33 | def http_404_email_details(email: str) -> str: 34 | return f"Either the account with email `{email}` doesn't exist, has been deleted, or you are not authorized!" 35 | -------------------------------------------------------------------------------- /backend/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/tests/__init__.py -------------------------------------------------------------------------------- /backend/tests/conftest.py: -------------------------------------------------------------------------------- 1 | import asgi_lifespan 2 | import fastapi 3 | import httpx 4 | import pytest 5 | 6 | from src.main import initialize_backend_application 7 | 8 | 9 | @pytest.fixture(name="backend_test_app") 10 | def backend_test_app() -> fastapi.FastAPI: 11 | """ 12 | A fixture that re-initializes the FastAPI instance for test application. 13 | """ 14 | 15 | return initialize_backend_application() 16 | 17 | 18 | @pytest.fixture(name="initialize_backend_test_application") 19 | async def initialize_backend_test_application(backend_test_app: fastapi.FastAPI) -> fastapi.FastAPI: # type: ignore 20 | async with asgi_lifespan.LifespanManager(backend_test_app): 21 | yield backend_test_app 22 | 23 | 24 | @pytest.fixture(name="async_client") 25 | async def async_client(initialize_backend_test_application: fastapi.FastAPI) -> httpx.AsyncClient: # type: ignore 26 | async with httpx.AsyncClient( 27 | app=initialize_backend_test_application, 28 | base_url="http://testserver", 29 | headers={"Content-Type": "application/json"}, 30 | ) as client: 31 | yield client 32 | -------------------------------------------------------------------------------- /backend/tests/end_to_end_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/tests/end_to_end_tests/__init__.py -------------------------------------------------------------------------------- /backend/tests/integration_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/tests/integration_tests/__init__.py -------------------------------------------------------------------------------- /backend/tests/security_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/tests/security_tests/__init__.py -------------------------------------------------------------------------------- /backend/tests/unit_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aeternalis-Ingenium/FastAPI-Backend-Template/d2e931b9639aa5fbca2a85c1711e47c8ee39b254/backend/tests/unit_tests/__init__.py -------------------------------------------------------------------------------- /backend/tests/unit_tests/test_src.py: -------------------------------------------------------------------------------- 1 | import fastapi 2 | 3 | import src 4 | from src.main import backend_app 5 | 6 | 7 | def test_src_version() -> None: 8 | assert src.__version__ == "0.0.1" 9 | 10 | 11 | def test_application_is_fastapi_instance() -> None: 12 | assert isinstance(backend_app, fastapi.FastAPI) 13 | assert backend_app.redoc_url == "/redoc" 14 | assert backend_app.docs_url == "/docs" 15 | assert backend_app.openapi_url == "/openapi.json" 16 | assert backend_app.redoc_url == "/redoc" 17 | -------------------------------------------------------------------------------- /codecov.yaml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: False 4 | patch: False 5 | 6 | flag_management: 7 | individual_flags: 8 | - name: backend 9 | paths: 10 | - backend/ 11 | statuses: 12 | - type: project 13 | target: 60% 14 | threshold: 1% 15 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | services: 4 | db: 5 | image: postgres:latest 6 | container_name: db 7 | restart: always 8 | environment: 9 | - POSTGRES_USER=${POSTGRES_USERNAME} 10 | - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} 11 | - POSTGRES_DB=${POSTGRES_DB} 12 | - PGDATA=/var/lib/postgresql/data/ 13 | volumes: 14 | - postgresql_db_data:/var/lib/postgresql/data/ 15 | expose: 16 | - 5432 17 | ports: 18 | - 5433:5432 19 | 20 | db_editor: 21 | image: adminer 22 | container_name: db_editor 23 | restart: always 24 | environment: 25 | - POSTGRES_USER=${POSTGRES_USERNAME} 26 | - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} 27 | - POSTGRES_HOST=${POSTGRES_HOST} 28 | - POSTGRES_PORT=${POSTGRES_PORT} 29 | - POSTGRES_DB=${POSTGRES_DB} 30 | expose: 31 | - 8080 32 | ports: 33 | - 8081:8080 34 | depends_on: 35 | - db 36 | 37 | backend_app: 38 | container_name: backend_app 39 | restart: always 40 | build: 41 | dockerfile: Dockerfile 42 | context: ./backend/ 43 | environment: 44 | - ENVIRONMENT=${ENVIRONMENT} 45 | - DEBUG=${DEBUG} 46 | - POSTGRES_DB=${POSTGRES_DB} 47 | - POSTGRES_HOST=${POSTGRES_HOST} 48 | - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} 49 | - POSTGRES_PORT=${POSTGRES_PORT} 50 | - POSTGRES_SCHEMA=${POSTGRES_SCHEMA} 51 | - POSTGRES_USERNAME=${POSTGRES_USERNAME} 52 | - BACKEND_SERVER_HOST=${BACKEND_SERVER_HOST} 53 | - BACKEND_SERVER_PORT=${BACKEND_SERVER_PORT} 54 | - BACKEND_SERVER_WORKERS=${BACKEND_SERVER_WORKERS} 55 | - DB_TIMEOUT=${DB_TIMEOUT} 56 | - DB_POOL_SIZE=${DB_POOL_SIZE} 57 | - DB_MAX_POOL_CON=${DB_MAX_POOL_CON} 58 | - DB_POOL_OVERFLOW=${DB_POOL_OVERFLOW} 59 | - IS_DB_ECHO_LOG=${IS_DB_ECHO_LOG} 60 | - IS_DB_EXPIRE_ON_COMMIT=${IS_DB_EXPIRE_ON_COMMIT} 61 | - IS_DB_FORCE_ROLLBACK=${IS_DB_FORCE_ROLLBACK} 62 | - IS_ALLOWED_CREDENTIALS=${IS_ALLOWED_CREDENTIALS} 63 | - API_TOKEN=${API_TOKEN} 64 | - AUTH_TOKEN=${AUTH_TOKEN} 65 | - JWT_SECRET_KEY=${JWT_SECRET_KEY} 66 | - JWT_SUBJECT=${JWT_SUBJECT} 67 | - JWT_TOKEN_PREFIX=${JWT_TOKEN_PREFIX} 68 | - JWT_ALGORITHM=${JWT_ALGORITHM} 69 | - JWT_MIN=${JWT_MIN} 70 | - JWT_HOUR=${JWT_HOUR} 71 | - JWT_DAY=${JWT_DAY} 72 | - HASHING_ALGORITHM_LAYER_1=${HASHING_ALGORITHM_LAYER_1} 73 | - HASHING_ALGORITHM_LAYER_2=${HASHING_ALGORITHM_LAYER_2} 74 | - HASHING_SALT=${HASHING_SALT} 75 | volumes: 76 | - ./backend/:/usr/backend/ 77 | expose: 78 | - 8000 79 | ports: 80 | - 8001:8000 81 | depends_on: 82 | - db 83 | 84 | volumes: 85 | postgresql_db_data: 86 | --------------------------------------------------------------------------------