mirror of
https://github.com/fastapi/full-stack-fastapi-template.git
synced 2026-09-22 22:05:00 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b8b78415f | ||
|
|
52b602681d | ||
|
|
dd4efc1687 | ||
|
|
cffdd96fa8 | ||
|
|
c432e5140c | ||
|
|
dad8959597 | ||
|
|
655261742b | ||
|
|
f01617a982 | ||
|
|
a69c22334e | ||
|
|
3cce5b0fa5 | ||
|
|
b95bdca83e | ||
|
|
76b28895e0 | ||
|
|
b32dea360c | ||
|
|
964e605bcd | ||
|
|
c2555c363f | ||
|
|
6ed353a072 | ||
|
|
12202b6f4d | ||
|
|
461a257713 | ||
|
|
03eb49aa4d | ||
|
|
55245e1ca4 | ||
|
|
5cf7ab0a6b | ||
|
|
73a1300464 | ||
|
|
98c78e4683 | ||
|
|
5373286d8a | ||
|
|
1e256bce5d | ||
|
|
63eb8b5ef8 | ||
|
|
204f46d651 | ||
|
|
208a541160 | ||
|
|
37a6e350d1 | ||
|
|
237c5a31c8 | ||
|
|
a62b1682e0 | ||
|
|
fdf45a00c8 | ||
|
|
559812a9b2 | ||
|
|
b8d03f455a | ||
|
|
f67af697eb | ||
|
|
22a7d7a09b | ||
|
|
66e26e1bfb | ||
|
|
ee092bdad8 | ||
|
|
691443c7cd | ||
|
|
87099ec8c3 | ||
|
|
5e5e4edd8c | ||
|
|
ee03380284 | ||
|
|
ab7d6df725 | ||
|
|
f6fce60ffc | ||
|
|
7e59206936 | ||
|
|
daaa2aff78 | ||
|
|
2db5805622 | ||
|
|
0885aabc65 | ||
|
|
e15531674f | ||
|
|
2b7d3c296a | ||
|
|
5ea1695e1c | ||
|
|
aa481ff89e | ||
|
|
d360b92bc6 | ||
|
|
cc0ea3c3b5 | ||
|
|
709f1d4ab2 | ||
|
|
15ce944a37 | ||
|
|
069cb30b71 | ||
|
|
49bc9b33c9 | ||
|
|
5ad33845c9 | ||
|
|
c3f77eb713 | ||
|
|
2f027567c6 | ||
|
|
a4358db5bc | ||
|
|
4e2c6bd6ba | ||
|
|
64e21bb0d5 | ||
|
|
11fe2a00ed | ||
|
|
1e08434ca9 | ||
|
|
6adafdc13d | ||
|
|
6d5db02b35 | ||
|
|
8131bb3bab | ||
|
|
6f48d6a2a8 | ||
|
|
381227d2dc | ||
|
|
f3b9d07337 | ||
|
|
3527df959e | ||
|
|
209992a929 | ||
|
|
2a20c4bac6 | ||
|
|
36f1082f20 | ||
|
|
619b230e47 | ||
|
|
4617e2e7e4 | ||
|
|
10f7b23c9c | ||
|
|
c60938013d | ||
|
|
8fedbd17b8 | ||
|
|
63b0a0e05d | ||
|
|
eed628a43e | ||
|
|
6b40df55d4 | ||
|
|
ed9958bc1e | ||
|
|
20f6020c7c | ||
|
|
e56cee9c1d | ||
|
|
d43918eebf | ||
|
|
7cf9577ebb | ||
|
|
4ef4b27b10 | ||
|
|
710e2f8c2b | ||
|
|
8f9650b661 | ||
|
|
6851eea1fe | ||
|
|
d52fc65491 | ||
|
|
e12262078a | ||
|
|
e165897df7 | ||
|
|
b9cbb4f8f4 | ||
|
|
bb7da40c87 | ||
|
|
a230f4fb2c | ||
|
|
6607eaded4 | ||
|
|
be82eb585c | ||
|
|
f3571b6b52 | ||
|
|
f5ccd4a59c | ||
|
|
449889b994 | ||
|
|
d04f758433 | ||
|
|
6d1c47e67d | ||
|
|
d4e35a0dfd | ||
|
|
c048a61d81 | ||
|
|
9989016c56 | ||
|
|
d8e529a4c2 | ||
|
|
4de4777e4b | ||
|
|
424d66b791 | ||
|
|
07064ae5e0 | ||
|
|
3de18e5fc0 | ||
|
|
38e59c0efd | ||
|
|
d25af0f79c | ||
|
|
7f87c0f5d5 | ||
|
|
44c1be1008 | ||
|
|
9d703df254 | ||
|
|
3b44537361 | ||
|
|
5e48da384e | ||
|
|
21fdff93c6 | ||
|
|
4900b2e676 | ||
|
|
c5da9752fb | ||
|
|
458d712d44 | ||
|
|
55c19b3196 | ||
|
|
fba645a30a | ||
|
|
88c162ba01 | ||
|
|
0231740213 | ||
|
|
75adf755b4 | ||
|
|
2d138b4622 | ||
|
|
6a3e47b7c9 | ||
|
|
3398a77ad1 | ||
|
|
2482ceb159 | ||
|
|
fd9e8e0803 | ||
|
|
92a5550011 | ||
|
|
541dd75ce9 | ||
|
|
c6703e41b2 | ||
|
|
1b8b42cee5 | ||
|
|
6c41e30263 | ||
|
|
7e2e724c4a | ||
|
|
cfb42d1bef | ||
|
|
4c1f75ce72 | ||
|
|
7a82434ab5 | ||
|
|
11c09b50b2 | ||
|
|
7c2b617c09 | ||
|
|
a44d2fd666 | ||
|
|
f3d6b1c435 | ||
|
|
8558cf00a2 | ||
|
|
ae83b89113 | ||
|
|
06766f3cb3 | ||
|
|
0ca52bfca9 | ||
|
|
cab869eac2 | ||
|
|
0ebd1de9f4 | ||
|
|
e6a6819c57 | ||
|
|
d0c9a6831c | ||
|
|
a22da4b1b5 | ||
|
|
1893602d61 | ||
|
|
01c40d4bda | ||
|
|
7bc569f006 | ||
|
|
2d0f77421f | ||
|
|
ad0abb08ef | ||
|
|
4531952aa7 | ||
|
|
732ab9c3e6 | ||
|
|
f0c433ae5f | ||
|
|
c49bf29b0e | ||
|
|
a4b151112b | ||
|
|
14f63707c4 | ||
|
|
0122fa2f11 | ||
|
|
5b802e96bb | ||
|
|
cfd66d2eee | ||
|
|
53a0aebadf | ||
|
|
0dd6ce699f | ||
|
|
9fc4045bc0 | ||
|
|
9fccee6fd5 | ||
|
|
bb124f91ff | ||
|
|
aa678e92a9 | ||
|
|
0602722f8c | ||
|
|
52ee514d8c | ||
|
|
9507f4b54b | ||
|
|
76081da4c3 | ||
|
|
d5cef0da2d | ||
|
|
c0d9e6e701 | ||
|
|
9cff2434a9 | ||
|
|
922bf1f6ce | ||
|
|
61ea8fcee3 | ||
|
|
701eb4815c | ||
|
|
7a8870b7b2 | ||
|
|
26fac55651 | ||
|
|
84c1a8fd68 | ||
|
|
dbd2050362 | ||
|
|
f71706b077 | ||
|
|
e4a4bed5b6 | ||
|
|
08395759fe | ||
|
|
2346b81c51 | ||
|
|
e44777f919 | ||
|
|
544f89f253 | ||
|
|
42726193d0 | ||
|
|
0cc802eec8 | ||
|
|
2802a4df9e | ||
|
|
73b2884057 | ||
|
|
a065f9c9e8 | ||
|
|
72f835a6b4 | ||
|
|
f41f4432fe | ||
|
|
176b6fb1c9 | ||
|
|
fe95750e3a | ||
|
|
93e03184d6 | ||
|
|
b470f59ce2 | ||
|
|
b18783f642 | ||
|
|
a88f637ed8 | ||
|
|
b4a1da918d | ||
|
|
2014a3bcf5 | ||
|
|
889d97f057 | ||
|
|
78b4d5d5fa | ||
|
|
cbba08d565 | ||
|
|
4bbab503cd | ||
|
|
b950fd7389 | ||
|
|
16f26df0c6 | ||
|
|
68ae0970f1 | ||
|
|
fa473bed72 | ||
|
|
52150b3d10 | ||
|
|
bd54967db8 | ||
|
|
6ecc8a06ec | ||
|
|
d91ed067a8 | ||
|
|
7966d3fb1b | ||
|
|
5a4b0ed2e4 | ||
|
|
6faa5f66d5 | ||
|
|
47d30b75c3 | ||
|
|
d5982236ac | ||
|
|
570ca7b9d9 | ||
|
|
047e6884be | ||
|
|
73798ba60c | ||
|
|
c1538fd1fb | ||
|
|
5679d04a29 | ||
|
|
49d610e443 | ||
|
|
311939e640 | ||
|
|
8155761cf4 | ||
|
|
229191061a | ||
|
|
28808e071c | ||
|
|
1864e7e5b0 | ||
|
|
3f109aee1f | ||
|
|
85de4ce362 | ||
|
|
6f29eb2438 | ||
|
|
2189b9f43b | ||
|
|
870d45fa36 | ||
|
|
9befa33a9f | ||
|
|
a66a9256dd | ||
|
|
2d92cd70a4 | ||
|
|
e4877b7a9f | ||
|
|
bd2236b842 | ||
|
|
fa4ea018c3 | ||
|
|
02223e1e1b | ||
|
|
8b317cafd1 | ||
|
|
68d48be306 | ||
|
|
7705fe89df | ||
|
|
edae7ba371 | ||
|
|
c892fc200e | ||
|
|
9fb69ba140 | ||
|
|
455de4d9a9 | ||
|
|
30c722339b | ||
|
|
dceca9c1e5 | ||
|
|
370b5c1345 | ||
|
|
64e4d37ee2 | ||
|
|
ef615cf8e9 | ||
|
|
f3823edaed | ||
|
|
6c9f70281b | ||
|
|
e0db713f6b | ||
|
|
04664a9ce9 | ||
|
|
ea544e903c | ||
|
|
5c5de0fa5d | ||
|
|
6e5c3375c7 | ||
|
|
20d93b0284 | ||
|
|
d148958782 | ||
|
|
b57ae43bcf | ||
|
|
5729eceb83 | ||
|
|
490c554e23 | ||
|
|
aab833bae2 | ||
|
|
45fdd880ce | ||
|
|
27fabe01ea | ||
|
|
6967ce1b0c | ||
|
|
20fa4ce8fb | ||
|
|
1a64656267 | ||
|
|
e4c668d7cd | ||
|
|
bdc40a17f6 | ||
|
|
b88a0fc5fa | ||
|
|
b02e4633dc | ||
|
|
43d5b49bd1 | ||
|
|
41a2f15d8f | ||
|
|
7b768879f5 | ||
|
|
eed33d276d | ||
|
|
4b80bdfdce | ||
|
|
7d57876bda | ||
|
|
3678eb9d57 | ||
|
|
f09fb854bf | ||
|
|
a7fd258e18 | ||
|
|
2afe4159ab | ||
|
|
283bc7c95b | ||
|
|
8f9c2bac42 | ||
|
|
a7d3671a72 | ||
|
|
894b0a5587 | ||
|
|
a25f2c14e4 | ||
|
|
122d983415 | ||
|
|
d08d9314ce | ||
|
|
ff55b778ba | ||
|
|
8812ca6635 | ||
|
|
2e8da3a590 | ||
|
|
00297f974f | ||
|
|
c8bcc0ba0a | ||
|
|
0a194b3b00 | ||
|
|
94b2474438 | ||
|
|
af4e0cfe10 | ||
|
|
001dbda103 | ||
|
|
34f6f9ae54 | ||
|
|
0c8e682a90 | ||
|
|
67b384f308 | ||
|
|
4bd791c11d | ||
|
|
697b4da6b0 | ||
|
|
854cc709d1 | ||
|
|
21c4d11659 | ||
|
|
bcee2427b9 | ||
|
|
8a2252f654 | ||
|
|
8ff61e813e | ||
|
|
fb874fea35 | ||
|
|
2b9ed9333a | ||
|
|
45510b4f80 | ||
|
|
5a79f4e427 | ||
|
|
79631c7619 | ||
|
|
cd875e5bef | ||
|
|
1a92a0a6f1 | ||
|
|
2eb5b030bd | ||
|
|
7c2c2276d9 | ||
|
|
baf584a6cd | ||
|
|
970a182ec8 | ||
|
|
1d8678235d | ||
|
|
71f430616c | ||
|
|
43e508239c | ||
|
|
dc712ac4ec | ||
|
|
141f6cdb6e | ||
|
|
fc403c9bc1 | ||
|
|
4b93dc709f | ||
|
|
2db416d3c1 | ||
|
|
ab46165387 | ||
|
|
1c975c7f2d | ||
|
|
248ea56c6e | ||
|
|
44d8a4358b | ||
|
|
9b4108fdae | ||
|
|
b4fa418e65 | ||
|
|
a612765b83 | ||
|
|
de7140f1e7 | ||
|
|
546dc8bdcb | ||
|
|
eae33cda72 | ||
|
|
1d30172e7a | ||
|
|
6fc9a37eb5 | ||
|
|
170231783a | ||
|
|
5216fcfd77 | ||
|
|
8bf3607d2b | ||
|
|
8ce745b7ef | ||
|
|
6bbd58c76f | ||
|
|
1aeb3208bf | ||
|
|
45317e54c7 | ||
|
|
47e0fe56e3 | ||
|
|
42ee0fe0ba | ||
|
|
92b757fc96 | ||
|
|
bece399368 | ||
|
|
5dd83c6350 | ||
|
|
f365a4d026 | ||
|
|
ecd634e497 | ||
|
|
1fe4908b0a | ||
|
|
cd86803daa | ||
|
|
cf5516cda6 | ||
|
|
151f7ed79b | ||
|
|
9c23d69f36 |
@@ -0,0 +1 @@
|
|||||||
|
{{ _copier_answers|to_json -}}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
|
||||||
|
# Update the .env file with the answers from the .copier-answers.yml file
|
||||||
|
# without using Jinja2 templates in the .env file, this way the code works as is
|
||||||
|
# without needing Copier, but if Copier is used, the .env file will be updated
|
||||||
|
root_path = Path(__file__).parent.parent
|
||||||
|
answers_path = Path(__file__).parent / ".copier-answers.yml"
|
||||||
|
answers = json.loads(answers_path.read_text())
|
||||||
|
env_path = root_path / ".env"
|
||||||
|
env_content = env_path.read_text()
|
||||||
|
lines = []
|
||||||
|
for line in env_content.splitlines():
|
||||||
|
for key, value in answers.items():
|
||||||
|
upper_key = key.upper()
|
||||||
|
if line.startswith(f"{upper_key}="):
|
||||||
|
if " " in value:
|
||||||
|
content = f"{upper_key}={value!r}"
|
||||||
|
else:
|
||||||
|
content = f"{upper_key}={value}"
|
||||||
|
new_line = line.replace(line, content)
|
||||||
|
lines.append(new_line)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
lines.append(line)
|
||||||
|
env_path.write_text("\n".join(lines))
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Domain
|
||||||
|
# This would be set to the production domain with an env var on deployment
|
||||||
|
DOMAIN=localhost
|
||||||
|
|
||||||
|
# Environment: local, staging, production
|
||||||
|
ENVIRONMENT=local
|
||||||
|
|
||||||
|
PROJECT_NAME="Full Stack FastAPI Project"
|
||||||
|
STACK_NAME=full-stack-fastapi-project
|
||||||
|
|
||||||
|
# Backend
|
||||||
|
BACKEND_CORS_ORIGINS="http://localhost,http://localhost:5173,https://localhost,https://localhost:5173,http://localhost.tiangolo.com"
|
||||||
|
SECRET_KEY=changethis
|
||||||
|
FIRST_SUPERUSER=admin@example.com
|
||||||
|
FIRST_SUPERUSER_PASSWORD=changethis
|
||||||
|
USERS_OPEN_REGISTRATION=False
|
||||||
|
|
||||||
|
# Emails
|
||||||
|
SMTP_HOST=
|
||||||
|
SMTP_USER=
|
||||||
|
SMTP_PASSWORD=
|
||||||
|
EMAILS_FROM_EMAIL=info@example.com
|
||||||
|
SMTP_TLS=True
|
||||||
|
SMTP_SSL=False
|
||||||
|
SMTP_PORT=587
|
||||||
|
|
||||||
|
# Postgres
|
||||||
|
POSTGRES_SERVER=localhost
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
POSTGRES_DB=app
|
||||||
|
POSTGRES_USER=postgres
|
||||||
|
POSTGRES_PASSWORD=changethis
|
||||||
|
|
||||||
|
SENTRY_DSN=
|
||||||
|
|
||||||
|
# Configure these with your own Docker registry images
|
||||||
|
DOCKER_IMAGE_BACKEND=backend
|
||||||
|
DOCKER_IMAGE_FRONTEND=frontend
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
* text=auto
|
||||||
|
*.sh text eol=lf
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
github: [tiangolo]
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# GitHub Actions
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
commit-message:
|
||||||
|
prefix: ⬆
|
||||||
|
# Python
|
||||||
|
- package-ecosystem: "pip"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
commit-message:
|
||||||
|
prefix: ⬆
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
name: Deploy to Production
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on:
|
||||||
|
- self-hosted
|
||||||
|
- production
|
||||||
|
env:
|
||||||
|
ENVIRONMENT: production
|
||||||
|
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
|
||||||
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
|
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
||||||
|
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
||||||
|
SMTP_HOST: ${{ secrets.SMTP_HOST }}
|
||||||
|
SMTP_USER: ${{ secrets.SMTP_USER }}
|
||||||
|
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
|
||||||
|
EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
|
||||||
|
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- run: docker compose -f docker-compose.yml build
|
||||||
|
- run: docker compose -f docker-compose.yml up -d
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
name: Deploy to Staging
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on:
|
||||||
|
- self-hosted
|
||||||
|
- staging
|
||||||
|
env:
|
||||||
|
ENVIRONMENT: staging
|
||||||
|
DOMAIN: ${{ secrets.DOMAIN_STAGING }}
|
||||||
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
|
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
||||||
|
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
||||||
|
SMTP_HOST: ${{ secrets.SMTP_HOST }}
|
||||||
|
SMTP_USER: ${{ secrets.SMTP_USER }}
|
||||||
|
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
|
||||||
|
EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
|
||||||
|
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- run: docker compose -f docker-compose.yml build
|
||||||
|
- run: docker compose -f docker-compose.yml up -d
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: Issue Manager
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * *"
|
||||||
|
issue_comment:
|
||||||
|
types:
|
||||||
|
- created
|
||||||
|
- edited
|
||||||
|
issues:
|
||||||
|
types:
|
||||||
|
- labeled
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
issue-manager:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: tiangolo/issue-manager@0.5.0
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
config: >
|
||||||
|
{
|
||||||
|
"answered": {
|
||||||
|
"users": ["tiangolo"],
|
||||||
|
"delay": 864000,
|
||||||
|
"message": "Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
name: Latest Changes
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
types:
|
||||||
|
- closed
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
number:
|
||||||
|
description: PR number
|
||||||
|
required: true
|
||||||
|
debug_enabled:
|
||||||
|
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
|
||||||
|
required: false
|
||||||
|
default: 'false'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
latest-changes:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Dump GitHub context
|
||||||
|
env:
|
||||||
|
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||||
|
run: echo "$GITHUB_CONTEXT"
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# To allow latest-changes to commit to the main branch
|
||||||
|
token: ${{ secrets.FULL_STACK_FASTAPI_POSTGRESQL_LATEST_CHANGES }}
|
||||||
|
- uses: docker://tiangolo/latest-changes:0.3.0
|
||||||
|
# - uses: tiangolo/latest-changes@main
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
latest_changes_file: ./release-notes.md
|
||||||
|
latest_changes_header: '## Latest Changes'
|
||||||
|
end_regex: '^## '
|
||||||
|
debug_logs: true
|
||||||
|
label_header_prefix: '### '
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
name: Smokeshow
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: [Test]
|
||||||
|
types: [completed]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
statuses: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
smokeshow:
|
||||||
|
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.9'
|
||||||
|
|
||||||
|
- run: pip install smokeshow
|
||||||
|
|
||||||
|
- uses: dawidd6/action-download-artifact@v3.1.2
|
||||||
|
with:
|
||||||
|
workflow: test.yml
|
||||||
|
commit: ${{ github.event.workflow_run.head_sha }}
|
||||||
|
|
||||||
|
- run: smokeshow upload coverage-html
|
||||||
|
env:
|
||||||
|
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
|
||||||
|
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
|
||||||
|
SMOKESHOW_GITHUB_CONTEXT: coverage
|
||||||
|
SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||||
|
SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
name: Test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.10'
|
||||||
|
|
||||||
|
- run: docker compose build
|
||||||
|
- run: docker compose down -v --remove-orphans
|
||||||
|
- run: docker compose up -d
|
||||||
|
- name: Lint
|
||||||
|
run: docker compose exec -T backend bash /app/scripts/lint.sh
|
||||||
|
- name: Run tests
|
||||||
|
run: docker compose exec -T backend bash /app/tests-start.sh "Coverage for ${{ github.sha }}"
|
||||||
|
- run: docker compose down -v --remove-orphans
|
||||||
|
- name: Store coverage files
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: coverage-html
|
||||||
|
path: backend/htmlcov
|
||||||
|
|
||||||
|
# https://github.com/marketplace/actions/alls-green#why
|
||||||
|
alls-green: # This job does nothing and is only used for the branch protection
|
||||||
|
if: always()
|
||||||
|
needs:
|
||||||
|
- test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Decide whether the needed jobs succeeded or failed
|
||||||
|
uses: re-actors/alls-green@release/v1
|
||||||
|
with:
|
||||||
|
jobs: ${{ toJSON(needs) }}
|
||||||
@@ -1,3 +1 @@
|
|||||||
.vscode
|
.vscode
|
||||||
testing-project
|
|
||||||
.mypy_cache
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# See https://pre-commit.com for more information
|
||||||
|
# See https://pre-commit.com/hooks.html for more hooks
|
||||||
|
repos:
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v4.4.0
|
||||||
|
hooks:
|
||||||
|
- id: check-added-large-files
|
||||||
|
- id: check-toml
|
||||||
|
- id: check-yaml
|
||||||
|
args:
|
||||||
|
- --unsafe
|
||||||
|
- id: end-of-file-fixer
|
||||||
|
- id: trailing-whitespace
|
||||||
|
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||||
|
rev: v0.2.2
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args:
|
||||||
|
- --fix
|
||||||
|
- id: ruff-format
|
||||||
|
ci:
|
||||||
|
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
|
||||||
|
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
sudo: required
|
|
||||||
|
|
||||||
language: python
|
|
||||||
|
|
||||||
install:
|
|
||||||
- pip install cookiecutter
|
|
||||||
|
|
||||||
services:
|
|
||||||
- docker
|
|
||||||
|
|
||||||
script:
|
|
||||||
- bash ./test.sh
|
|
||||||
Vendored
+28
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Debug FastAPI Project backend: Python Debugger",
|
||||||
|
"type": "debugpy",
|
||||||
|
"request": "launch",
|
||||||
|
"module": "uvicorn",
|
||||||
|
"args": [
|
||||||
|
"app.main:app",
|
||||||
|
"--reload"
|
||||||
|
],
|
||||||
|
"cwd": "${workspaceFolder}/backend",
|
||||||
|
"jinja": true,
|
||||||
|
"envFile": "${workspaceFolder}/.env",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "chrome",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Debug Frontend: Launch Chrome against http://localhost:5173",
|
||||||
|
"url": "http://localhost:5173",
|
||||||
|
"webRoot": "${workspaceFolder}/frontend"
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,181 +1,168 @@
|
|||||||
# Full Stack FastAPI and PostgreSQL - Base Project Generator
|
# Full Stack FastAPI Template
|
||||||
|
|
||||||
[](https://travis-ci.org/tiangolo/full-stack-fastapi-postgresql)
|
<a href="https://github.com/tiangolo/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/tiangolo/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a>
|
||||||
|
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/full-stack-fastapi-template.svg" alt="Coverage"></a>
|
||||||
|
|
||||||
Generate a backend and frontend stack using Python, including interactive API documentation.
|
### Dashboard - Dark Mode
|
||||||
|
|
||||||
### Interactive API documentation
|
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
## Technology Stack and Features
|
||||||
|
|
||||||
|
|
||||||
### Alternative API documentation
|
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
|
||||||
|
|
||||||
|
- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API.
|
||||||
|
- 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM).
|
||||||
|
- 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management.
|
||||||
|
- 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database.
|
||||||
|
- 🚀 [React](https://react.dev) for the frontend.
|
||||||
|
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
|
||||||
|
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
|
||||||
|
- 🤖 An automatically generated frontend client.
|
||||||
|
- 🦇 Dark mode support.
|
||||||
|
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
|
||||||
|
- 🔒 Secure password hashing by default.
|
||||||
|
- 🔑 JWT token authentication.
|
||||||
|
- 📫 Email based password recovery.
|
||||||
|
- ✅ Tests with [Pytest](https://pytest.org).
|
||||||
|
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
|
||||||
|
- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates.
|
||||||
|
- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions.
|
||||||
|
|
||||||
### Dashboard Login
|
### Dashboard Login
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
|
### Dashboard - Admin
|
||||||
|
|
||||||
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Dashboard - Create User
|
### Dashboard - Create User
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
|
### Dashboard - Items
|
||||||
|
|
||||||
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
|
### Dashboard - User Settings
|
||||||
|
|
||||||
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
|
### Interactive API documentation
|
||||||
|
|
||||||
|
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
* Full **Docker** integration (Docker based).
|
|
||||||
* Docker Swarm Mode deployment.
|
|
||||||
* **Docker Compose** integration and optimization for local development
|
|
||||||
* **Production ready** Python web server using Uvicorn and Gunicorn.
|
|
||||||
* Python **[FastAPI](https://github.com/tiangolo/fastapi)** backend:
|
|
||||||
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
|
|
||||||
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
|
|
||||||
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
|
|
||||||
* **Short**: Minimize code duplication. Multiple features from each parameter declaration.
|
|
||||||
* **Robust**: Get production-ready code. With automatic interactive documentation.
|
|
||||||
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
|
|
||||||
* [**Many other features**](https://github.com/tiangolo/fastapi) including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
|
|
||||||
* **Secure password** hashing by default.
|
|
||||||
* **JWT token** authentication.
|
|
||||||
* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
|
|
||||||
* Basic starting models for users (modify and remove as you need).
|
|
||||||
* **Alembic** migrations.
|
|
||||||
* **CORS** (Cross Origin Resource Sharing).
|
|
||||||
* **Celery** worker that can import and use models and code from the rest of the backend selectively (you don't have to install the complete app in each worker).
|
|
||||||
* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
|
|
||||||
* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
|
|
||||||
* **Vue** frontend:
|
|
||||||
* Generated with Vue CLI.
|
|
||||||
* **JWT Authentication** handling.
|
|
||||||
* Login view.
|
|
||||||
* After login, main dashboard view.
|
|
||||||
* Main dashboard with user creation and edition.
|
|
||||||
* Self user edition.
|
|
||||||
* **Vuex**.
|
|
||||||
* **Vue-router**.
|
|
||||||
* **Vuetify** for beautiful material design components.
|
|
||||||
* **TypeScript**.
|
|
||||||
* Docker server based on **Nginx** (configured to play nicely with Vue-router).
|
|
||||||
* Docker multi-stage building, so you don't need to save or commit compiled code.
|
|
||||||
* Frontend tests ran at build time (can be disabled too).
|
|
||||||
* Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
|
|
||||||
* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily.
|
|
||||||
* **Flower** for Celery jobs monitoring.
|
|
||||||
* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
|
|
||||||
* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
|
|
||||||
* GitLab **CI** (continuous integration), including frontend and backend testing.
|
|
||||||
|
|
||||||
## How to use it
|
## How to use it
|
||||||
|
|
||||||
Go to the directoy where you want to create your project and run:
|
You can **just fork or clone** this repository and use it as is.
|
||||||
|
|
||||||
|
✨ It just works. ✨
|
||||||
|
|
||||||
|
### Configure
|
||||||
|
|
||||||
|
You can then update configs in the `.env` files to customize your configurations.
|
||||||
|
|
||||||
|
Before deploying it, make sure you change at least the values for:
|
||||||
|
|
||||||
|
- `SECRET_KEY`
|
||||||
|
- `FIRST_SUPERUSER_PASSWORD`
|
||||||
|
- `POSTGRES_PASSWORD`
|
||||||
|
|
||||||
|
### Generate secret keys
|
||||||
|
|
||||||
|
Some environment variables in the `.env` file have a default value of `changethis`.
|
||||||
|
|
||||||
|
You have to change them with a secret key, to generate secret keys you can run the following command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install cookiecutter
|
python -c "import secrets; print(secrets.token_urlsafe(32))"
|
||||||
cookiecutter https://github.com/tiangolo/full-stack-fastapi-postgresql
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Generate passwords
|
Copy the content and use that as password / secret key. And run that again to generate another secure key.
|
||||||
|
|
||||||
You will be asked to provide passwords and secret keys for several components. Open another terminal and run:
|
## How to use it - alternative with Copier
|
||||||
|
|
||||||
|
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
|
||||||
|
|
||||||
|
It will copy all the files, ask you configuration questions, and update the `.env` files with your answers.
|
||||||
|
|
||||||
|
### Install Copier
|
||||||
|
|
||||||
|
You can install Copier with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
openssl rand -hex 32
|
pip install copier
|
||||||
# Outputs something like: 99d3b1f01aa639e4a76f4fc281fc834747a543720ba4c8a8648ba755aef9be7f
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy the contents and use that as password / secret key. And run that again to generate another secure key.
|
Or better, if you have [`pipx`](https://pipx.pypa.io/), you can run it with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pipx install copier
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: If you have `pipx`, installing copier is optional, you could run it directly.
|
||||||
|
|
||||||
|
### Generate a Project with Copier
|
||||||
|
|
||||||
|
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`.
|
||||||
|
|
||||||
|
Go to the directory that will be the parent of your project, and run the command with your project's name:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust
|
||||||
|
```
|
||||||
|
|
||||||
|
If you have `pipx` and you didn't install `copier`, you can run it directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pipx run copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/tiangolo/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files.
|
||||||
|
|
||||||
### Input variables
|
### Input variables
|
||||||
|
|
||||||
The generator (cookiecutter) will ask you for some data, you might want to have at hand before generating the project.
|
Copier will ask you for some data, you might want to have at hand before generating the project.
|
||||||
|
|
||||||
|
But don't worry, you can just update any of that in the `.env` files afterwards.
|
||||||
|
|
||||||
The input variables, with their default values (some auto generated) are:
|
The input variables, with their default values (some auto generated) are:
|
||||||
|
|
||||||
* `project_name`: The name of the project
|
- `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
|
||||||
* `project_slug`: The development friendly name of the project. By default, based on the project name
|
- `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels (no spaces) (in .env).
|
||||||
* `domain_main`: The domain in where to deploy the project for production (from the branch `production`), used by the load balancer, backend, etc. By default, based on the project slug.
|
- `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
|
||||||
* `domain_staging`: The domain in where to deploy while staging (before production) (from the branch `master`). By default, based on the main domain.
|
- `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
|
||||||
|
- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
|
||||||
|
- `smtp_host`: (default: "") The SMTP server host to send emails, you can set it later in .env.
|
||||||
|
- `smtp_user`: (default: "") The SMTP server user to send emails, you can set it later in .env.
|
||||||
|
- `smtp_password`: (default: "") The SMTP server password to send emails, you can set it later in .env.
|
||||||
|
- `emails_from_email`: (default: `"info@example.com"`) The email account to send emails from, you can set it later in .env.
|
||||||
|
- `postgres_password`: (default: `"changethis"`) The password for the PostgreSQL database, stored in .env, you can generate one with the method above.
|
||||||
|
- `sentry_dsn`: (default: "") The DSN for Sentry, if you are using it, you can set it later in .env.
|
||||||
|
|
||||||
* `docker_swarm_stack_name_main`: The name of the stack while deploying to Docker in Swarm mode for production. By default, based on the domain.
|
## Backend Development
|
||||||
* `docker_swarm_stack_name_staging`: The name of the stack while deploying to Docker in Swarm mode for staging. By default, based on the domain.
|
|
||||||
|
|
||||||
* `secret_key`: Backend server secret key. Use the method above to generate it.
|
Backend docs: [backend/README.md](./backend/README.md).
|
||||||
* `first_superuser`: The first superuser generated, with it you will be able to create more users, etc. By default, based on the domain.
|
|
||||||
* `first_superuser_password`: First superuser password. Use the method above to generate it.
|
|
||||||
* `backend_cors_origins`: Origins (domains, more or less) that are enabled for CORS (Cross Origin Resource Sharing). This allows a frontend in one domain (e.g. `https://dashboard.example.com`) to communicate with this backend, that could be living in another domain (e.g. `https://api.example.com`). It can also be used to allow your local frontend (with a custom `hosts` domain mapping, as described in the project's `README.md`) that could be living in `http://dev.example.com:8080` to cummunicate with the backend at `https://stag.example.com`. Notice the `http` vs `https` and the `dev.` prefix for local development vs the "staging" `stag.` prefix. By default, it includes origins for production, staging and development, with ports commonly used during local development by several popular frontend frameworks (Vue with `:8080`, React, Angular).
|
|
||||||
* `smtp_port`: Port to use to send emails via SMTP. By default `587`.
|
|
||||||
* `smtp_host`: Host to use to send emails, it would be given by your email provider, like Mailgun, Sparkpost, etc.
|
|
||||||
* `smtp_user`: The user to use in the SMTP connection. The value will be given by your email provider.
|
|
||||||
* `smtp_password`: The password to be used in the SMTP connection. The value will be given by the email provider.
|
|
||||||
* `smtp_emails_from_email`: The email account to use as the sender in the notification emails, it would be something like `info@your-custom-domain.com`.
|
|
||||||
|
|
||||||
* `postgres_password`: Postgres database password. Use the method above to generate it. (You could easily modify it to use MySQL, MariaDB, etc).
|
## Frontend Development
|
||||||
* `pgadmin_default_user`: PGAdmin default user, to log-in to the PGAdmin interface.
|
|
||||||
* `pgadmin_default_user_password`: PGAdmin default user password. Generate it with the method above.
|
|
||||||
|
|
||||||
* `traefik_constraint_tag`: The tag to be used by the internal Traefik load balancer (for example, to divide requests between backend and frontend) for production. Used to separate this stack from any other stack you might have. This should identify each stack in each environment (production, staging, etc).
|
Frontend docs: [frontend/README.md](./frontend/README.md).
|
||||||
* `traefik_constraint_tag_staging`: The Traefik tag to be used while on staging.
|
|
||||||
* `traefik_public_network`: This assumes you have another separate publicly facing Traefik at the server / cluster level. This is the network that main Traefik lives in.
|
|
||||||
* `traefik_public_constraint_tag`: The tag that should be used by stack services that should communicate with the public.
|
|
||||||
|
|
||||||
* `flower_auth`: Basic HTTP authentication for flower, in the form`user:password`. By default: "`root:changethis`".
|
## Deployment
|
||||||
|
|
||||||
* `sentry_dsn`: Key URL (DSN) of Sentry, for live error reporting. If you are not using it yet, you should, is open source. E.g.: `https://1234abcd:5678ef@sentry.example.com/30`.
|
Deployment docs: [deployment.md](./deployment.md).
|
||||||
|
|
||||||
* `docker_image_prefix`: Prefix to use for Docker image names. If you are using GitLab Docker registry it would be based on your code repository. E.g.: `git.example.com/development-team/my-awesome-project/`.
|
## Development
|
||||||
* `docker_image_backend`: Docker image name for the backend. By default, it will be based on your Docker image prefix, e.g.: `git.example.com/development-team/my-awesome-project/backend`. And depending on your environment, a different tag will be appended ( `prod`, `stag`, `branch` ). So, the final image names used will be like: `git.example.com/development-team/my-awesome-project/backend:prod`.
|
|
||||||
* `docker_image_celeryworker`: Docker image for the celery worker. By default, based on your Docker image prefix.
|
|
||||||
* `docker_image_frontend`: Docker image for the frontend. By default, based on your Docker image prefix.
|
|
||||||
|
|
||||||
## How to deploy
|
General development docs: [development.md](./development.md).
|
||||||
|
|
||||||
This stack can be adjusted and used with several deployment options that are compatible with Docker Compose, but it is designed to be used in a cluster controlled with pure Docker in Swarm Mode with a Traefik main load balancer proxy handling automatic HTTPS certificates, using the ideas from <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a>.
|
This includes using Docker Compose, custom local domains, `.env` configurations, etc.
|
||||||
|
|
||||||
Please refer to <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a> to see how to deploy such a cluster in 20 minutes.
|
|
||||||
|
|
||||||
## More details
|
|
||||||
|
|
||||||
After using this generator, your new project (the directory created) will contain an extensive `README.md` with instructions for development, deployment, etc. You can pre-read [the project `README.md` template here too](./{{cookiecutter.project_slug}}/README.md).
|
|
||||||
|
|
||||||
## Sibling project generators
|
|
||||||
|
|
||||||
* Based on Couchbase: [https://github.com/tiangolo/full-stack-fastapi-couchbase](https://github.com/tiangolo/full-stack-fastapi-couchbase).
|
|
||||||
|
|
||||||
## Release Notes
|
## Release Notes
|
||||||
|
|
||||||
### Next
|
Check the file [release-notes.md](./release-notes.md).
|
||||||
|
|
||||||
* Set `/start-reload.sh` as a command override for development by default.
|
|
||||||
|
|
||||||
* Update generated README.
|
|
||||||
|
|
||||||
### 0.2.0
|
|
||||||
|
|
||||||
**<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/2" target="_blank">PR #2</a>**:
|
|
||||||
|
|
||||||
* Simplify and update backend `Dockerfile`s.
|
|
||||||
* Refactor and simplify backend code, improve naming, imports, modules and "namespaces".
|
|
||||||
* Improve and simplify Vuex integration with TypeScript accessors.
|
|
||||||
* Standardize frontend components layout, buttons order, etc.
|
|
||||||
* Add local development scripts (to develop this project generator itself).
|
|
||||||
* Add logs to startup modules to detect errors early.
|
|
||||||
* Improve FastAPI dependency utilities, to simplify and reduce code (to require a superuser).
|
|
||||||
|
|
||||||
### 0.1.2
|
|
||||||
|
|
||||||
* Fix path operation to update self-user, set parameters as body payload.
|
|
||||||
|
|
||||||
### 0.1.1
|
|
||||||
|
|
||||||
Several bug fixes since initial publication, including:
|
|
||||||
|
|
||||||
* Order of path operations for users.
|
|
||||||
* Frontend sending login data in the correct format.
|
|
||||||
* Add https://localhost variants to CORS.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the terms of the MIT license.
|
The Full Stack FastAPI Template is licensed under the terms of the MIT license.
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__
|
||||||
|
app.egg-info
|
||||||
|
*.pyc
|
||||||
|
.mypy_cache
|
||||||
|
.coverage
|
||||||
|
htmlcov
|
||||||
|
.venv
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
__pycache__
|
||||||
|
app.egg-info
|
||||||
|
*.pyc
|
||||||
|
.mypy_cache
|
||||||
|
.coverage
|
||||||
|
htmlcov
|
||||||
|
.cache
|
||||||
|
.venv
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.10
|
||||||
|
|
||||||
|
WORKDIR /app/
|
||||||
|
|
||||||
|
# Install Poetry
|
||||||
|
RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \
|
||||||
|
cd /usr/local/bin && \
|
||||||
|
ln -s /opt/poetry/bin/poetry && \
|
||||||
|
poetry config virtualenvs.create false
|
||||||
|
|
||||||
|
# Copy poetry.lock* in case it doesn't exist in the repo
|
||||||
|
COPY ./pyproject.toml ./poetry.lock* /app/
|
||||||
|
|
||||||
|
# Allow installing dev dependencies to run tests
|
||||||
|
ARG INSTALL_DEV=false
|
||||||
|
RUN bash -c "if [ $INSTALL_DEV == 'true' ] ; then poetry install --no-root ; else poetry install --no-root --only main ; fi"
|
||||||
|
|
||||||
|
ENV PYTHONPATH=/app
|
||||||
|
|
||||||
|
COPY ./scripts/ /app/
|
||||||
|
|
||||||
|
COPY ./alembic.ini /app/
|
||||||
|
|
||||||
|
COPY ./prestart.sh /app/
|
||||||
|
|
||||||
|
COPY ./tests-start.sh /app/
|
||||||
|
|
||||||
|
COPY ./app /app/app
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
# FastAPI Project - Backend
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
* [Docker](https://www.docker.com/).
|
||||||
|
* [Poetry](https://python-poetry.org/) for Python package and environment management.
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
|
* Start the stack with Docker Compose:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
* Now you can open your browser and interact with these URLs:
|
||||||
|
|
||||||
|
Frontend, built with Docker, with routes handled based on the path: http://localhost
|
||||||
|
|
||||||
|
Backend, JSON based web API based on OpenAPI: http://localhost/api/
|
||||||
|
|
||||||
|
Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost/docs
|
||||||
|
|
||||||
|
Adminer, database web administration: http://localhost:8080
|
||||||
|
|
||||||
|
Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
|
||||||
|
|
||||||
|
**Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it.
|
||||||
|
|
||||||
|
To check the logs, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose logs
|
||||||
|
```
|
||||||
|
|
||||||
|
To check the logs of a specific service, add the name of the service, e.g.:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose logs backend
|
||||||
|
```
|
||||||
|
|
||||||
|
If your Docker is not running in `localhost` (the URLs above wouldn't work) you would need to use the IP or domain where your Docker is running.
|
||||||
|
|
||||||
|
## Backend local development, additional details
|
||||||
|
|
||||||
|
### General workflow
|
||||||
|
|
||||||
|
By default, the dependencies are managed with [Poetry](https://python-poetry.org/), go there and install it.
|
||||||
|
|
||||||
|
From `./backend/` you can install all the dependencies with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ poetry install
|
||||||
|
```
|
||||||
|
|
||||||
|
Then you can start a shell session with the new environment with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ poetry shell
|
||||||
|
```
|
||||||
|
|
||||||
|
Make sure your editor is using the correct Python virtual environment.
|
||||||
|
|
||||||
|
Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`.
|
||||||
|
|
||||||
|
### VS Code
|
||||||
|
|
||||||
|
There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc.
|
||||||
|
|
||||||
|
The setup is also already configured so you can run the tests through the VS Code Python tests tab.
|
||||||
|
|
||||||
|
### Docker Compose Override
|
||||||
|
|
||||||
|
During development, you can change Docker Compose settings that will only affect the local development environment in the file `docker-compose.override.yml`.
|
||||||
|
|
||||||
|
The changes to that file only affect the local development environment, not the production environment. So, you can add "temporary" changes that help the development workflow.
|
||||||
|
|
||||||
|
For example, the directory with the backend code is mounted as a Docker "host volume", mapping the code you change live to the directory inside the container. That allows you to test your changes right away, without having to build the Docker image again. It should only be done during development, for production, you should build the Docker image with a recent version of the backend code. But during development, it allows you to iterate very fast.
|
||||||
|
|
||||||
|
There is also a command override that runs `/start-reload.sh` (included in the base image) instead of the default `/start.sh` (also included in the base image). It starts a single server process (instead of multiple, as would be for production) and reloads the process whenever the code changes. Have in mind that if you have a syntax error and save the Python file, it will break and exit, and the container will stop. After that, you can restart the container by fixing the error and running again:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes.
|
||||||
|
|
||||||
|
To get inside the container with a `bash` session you can start the stack with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
and then `exec` inside the running container:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ docker compose exec backend bash
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see an output like:
|
||||||
|
|
||||||
|
```console
|
||||||
|
root@7f2607af31c3:/app#
|
||||||
|
```
|
||||||
|
|
||||||
|
that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`.
|
||||||
|
|
||||||
|
There you can use the script `/start-reload.sh` to run the debug live reloading server. You can run that script from inside the container with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ bash /start-reload.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
...it will look like:
|
||||||
|
|
||||||
|
```console
|
||||||
|
root@7f2607af31c3:/app# bash /start-reload.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
and then hit enter. That runs the live reloading server that auto reloads when it detects code changes.
|
||||||
|
|
||||||
|
Nevertheless, if it doesn't detect a change but a syntax error, it will just stop with an error. But as the container is still alive and you are in a Bash session, you can quickly restart it after fixing the error, running the same command ("up arrow" and "Enter").
|
||||||
|
|
||||||
|
...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server.
|
||||||
|
|
||||||
|
### Backend tests
|
||||||
|
|
||||||
|
To test the backend run:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ bash ./scripts/test.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The tests run with Pytest, modify and add tests to `./backend/app/tests/`.
|
||||||
|
|
||||||
|
If you use GitHub Actions the tests will run automatically.
|
||||||
|
|
||||||
|
#### Test running stack
|
||||||
|
|
||||||
|
If your stack is already up and you just want to run the tests, you can use:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec backend bash /app/tests-start.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
That `/app/tests-start.sh` script just calls `pytest` after making sure that the rest of the stack is running. If you need to pass extra arguments to `pytest`, you can pass them to that command and they will be forwarded.
|
||||||
|
|
||||||
|
For example, to stop on first error:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec backend bash /app/tests-start.sh -x
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Test Coverage
|
||||||
|
|
||||||
|
When the tests are run, a file `htmlcov/index.html` is generated, you can open it in your browser to see the coverage of the tests.
|
||||||
|
|
||||||
|
### Migrations
|
||||||
|
|
||||||
|
As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository.
|
||||||
|
|
||||||
|
Make sure you create a "revision" of your models and that you "upgrade" your database with that revision every time you change them. As this is what will update the tables in your database. Otherwise, your application will have errors.
|
||||||
|
|
||||||
|
* Start an interactive session in the backend container:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ docker compose exec backend bash
|
||||||
|
```
|
||||||
|
|
||||||
|
* Alembic is already configured to import your SQLModel models from `./backend/app/models.py`.
|
||||||
|
|
||||||
|
* After changing a model (for example, adding a column), inside the container, create a revision, e.g.:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ alembic revision --autogenerate -m "Add column last_name to User model"
|
||||||
|
```
|
||||||
|
|
||||||
|
* Commit to the git repository the files generated in the alembic directory.
|
||||||
|
|
||||||
|
* After creating the revision, run the migration in the database (this is what will actually change the database):
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/db/init_db.py` that end in:
|
||||||
|
|
||||||
|
```python
|
||||||
|
SQLModel.metadata.create_all(engine)
|
||||||
|
```
|
||||||
|
|
||||||
|
and comment the line in the file `prestart.sh` that contains:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[alembic]
|
[alembic]
|
||||||
# path to migration scripts
|
# path to migration scripts
|
||||||
script_location = alembic
|
script_location = app/alembic
|
||||||
|
|
||||||
# template used to generate migration files
|
# template used to generate migration files
|
||||||
# file_template = %%(rev)s_%%(slug)s
|
# file_template = %%(rev)s_%%(slug)s
|
||||||
@@ -35,9 +35,6 @@ script_location = alembic
|
|||||||
# are written from script.py.mako
|
# are written from script.py.mako
|
||||||
# output_encoding = utf-8
|
# output_encoding = utf-8
|
||||||
|
|
||||||
sqlalchemy.url = postgresql://postgres:{{cookiecutter.postgres_password}}@db/app
|
|
||||||
|
|
||||||
|
|
||||||
# Logging configuration
|
# Logging configuration
|
||||||
[loggers]
|
[loggers]
|
||||||
keys = root,sqlalchemy,alembic
|
keys = root,sqlalchemy,alembic
|
||||||
Executable
+1
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
+18
-6
@@ -1,7 +1,8 @@
|
|||||||
from __future__ import with_statement
|
import os
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
from alembic import context
|
from alembic import context
|
||||||
from sqlalchemy import engine_from_config, pool
|
from sqlalchemy import engine_from_config, pool
|
||||||
from logging.config import fileConfig
|
|
||||||
|
|
||||||
# this is the Alembic Config object, which provides
|
# this is the Alembic Config object, which provides
|
||||||
# access to the values within the .ini file in use.
|
# access to the values within the .ini file in use.
|
||||||
@@ -17,9 +18,9 @@ fileConfig(config.config_file_name)
|
|||||||
# target_metadata = mymodel.Base.metadata
|
# target_metadata = mymodel.Base.metadata
|
||||||
# target_metadata = None
|
# target_metadata = None
|
||||||
|
|
||||||
from app.db.base import Base # noqa
|
from app.models import SQLModel # noqa
|
||||||
|
|
||||||
target_metadata = Base.metadata
|
target_metadata = SQLModel.metadata
|
||||||
|
|
||||||
# other values from the config, defined by the needs of env.py,
|
# other values from the config, defined by the needs of env.py,
|
||||||
# can be acquired:
|
# can be acquired:
|
||||||
@@ -27,6 +28,15 @@ target_metadata = Base.metadata
|
|||||||
# ... etc.
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def get_url():
|
||||||
|
user = os.getenv("POSTGRES_USER", "postgres")
|
||||||
|
password = os.getenv("POSTGRES_PASSWORD", "")
|
||||||
|
server = os.getenv("POSTGRES_SERVER", "db")
|
||||||
|
port = os.getenv("POSTGRES_PORT", "5432")
|
||||||
|
db = os.getenv("POSTGRES_DB", "app")
|
||||||
|
return f"postgresql+psycopg://{user}:{password}@{server}:{port}/{db}"
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_offline():
|
def run_migrations_offline():
|
||||||
"""Run migrations in 'offline' mode.
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
@@ -39,7 +49,7 @@ def run_migrations_offline():
|
|||||||
script output.
|
script output.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
url = config.get_main_option("sqlalchemy.url")
|
url = get_url()
|
||||||
context.configure(
|
context.configure(
|
||||||
url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
|
url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
|
||||||
)
|
)
|
||||||
@@ -55,8 +65,10 @@ def run_migrations_online():
|
|||||||
and associate a connection with the context.
|
and associate a connection with the context.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
configuration = config.get_section(config.config_ini_section)
|
||||||
|
configuration["sqlalchemy.url"] = get_url()
|
||||||
connectable = engine_from_config(
|
connectable = engine_from_config(
|
||||||
config.get_section(config.config_ini_section),
|
configuration,
|
||||||
prefix="sqlalchemy.",
|
prefix="sqlalchemy.",
|
||||||
poolclass=pool.NullPool,
|
poolclass=pool.NullPool,
|
||||||
)
|
)
|
||||||
+1
@@ -7,6 +7,7 @@ Create Date: ${create_date}
|
|||||||
"""
|
"""
|
||||||
from alembic import op
|
from alembic import op
|
||||||
import sqlalchemy as sa
|
import sqlalchemy as sa
|
||||||
|
import sqlmodel.sql.sqltypes
|
||||||
${imports if imports else ""}
|
${imports if imports else ""}
|
||||||
|
|
||||||
# revision identifiers, used by Alembic.
|
# revision identifiers, used by Alembic.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Initialize models
|
||||||
|
|
||||||
|
Revision ID: e2412789c190
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-11-24 22:55:43.195942
|
||||||
|
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
import sqlmodel.sql.sqltypes
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "e2412789c190"
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
"user",
|
||||||
|
sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("is_superuser", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("full_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"hashed_password", sqlmodel.sql.sqltypes.AutoString(), nullable=False
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_user_email"), "user", ["email"], unique=True)
|
||||||
|
op.create_table(
|
||||||
|
"item",
|
||||||
|
sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||||
|
sa.Column("owner_id", sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["owner_id"],
|
||||||
|
["user.id"],
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table("item")
|
||||||
|
op.drop_index(op.f("ix_user_email"), table_name="user")
|
||||||
|
op.drop_table("user")
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from collections.abc import Generator
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app.core import security
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.core.db import engine
|
||||||
|
from app.models import TokenPayload, User
|
||||||
|
|
||||||
|
reusable_oauth2 = OAuth2PasswordBearer(
|
||||||
|
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator[Session, None, None]:
|
||||||
|
with Session(engine) as session:
|
||||||
|
yield session
|
||||||
|
|
||||||
|
|
||||||
|
SessionDep = Annotated[Session, Depends(get_db)]
|
||||||
|
TokenDep = Annotated[str, Depends(reusable_oauth2)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(session: SessionDep, token: TokenDep) -> User:
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(
|
||||||
|
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
||||||
|
)
|
||||||
|
token_data = TokenPayload(**payload)
|
||||||
|
except (JWTError, ValidationError):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Could not validate credentials",
|
||||||
|
)
|
||||||
|
user = session.get(User, token_data.sub)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_active_superuser(current_user: CurrentUser) -> User:
|
||||||
|
if not current_user.is_superuser:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="The user doesn't have enough privileges"
|
||||||
|
)
|
||||||
|
return current_user
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.routes import items, login, users, utils
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
api_router.include_router(login.router, tags=["login"])
|
||||||
|
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||||
|
api_router.include_router(utils.router, prefix="/utils", tags=["utils"])
|
||||||
|
api_router.include_router(items.router, prefix="/items", tags=["items"])
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from sqlmodel import func, select
|
||||||
|
|
||||||
|
from app.api.deps import CurrentUser, SessionDep
|
||||||
|
from app.models import Item, ItemCreate, ItemOut, ItemsOut, ItemUpdate, Message
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=ItemsOut)
|
||||||
|
def read_items(
|
||||||
|
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve items.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if current_user.is_superuser:
|
||||||
|
statment = select(func.count()).select_from(Item)
|
||||||
|
count = session.exec(statment).one()
|
||||||
|
statement = select(Item).offset(skip).limit(limit)
|
||||||
|
items = session.exec(statement).all()
|
||||||
|
else:
|
||||||
|
statment = (
|
||||||
|
select(func.count())
|
||||||
|
.select_from(Item)
|
||||||
|
.where(Item.owner_id == current_user.id)
|
||||||
|
)
|
||||||
|
count = session.exec(statment).one()
|
||||||
|
statement = (
|
||||||
|
select(Item)
|
||||||
|
.where(Item.owner_id == current_user.id)
|
||||||
|
.offset(skip)
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
items = session.exec(statement).all()
|
||||||
|
|
||||||
|
return ItemsOut(data=items, count=count)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{id}", response_model=ItemOut)
|
||||||
|
def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
|
||||||
|
"""
|
||||||
|
Get item by ID.
|
||||||
|
"""
|
||||||
|
item = session.get(Item, id)
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
if not current_user.is_superuser and (item.owner_id != current_user.id):
|
||||||
|
raise HTTPException(status_code=400, detail="Not enough permissions")
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=ItemOut)
|
||||||
|
def create_item(
|
||||||
|
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new item.
|
||||||
|
"""
|
||||||
|
item = Item.model_validate(item_in, update={"owner_id": current_user.id})
|
||||||
|
session.add(item)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(item)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{id}", response_model=ItemOut)
|
||||||
|
def update_item(
|
||||||
|
*, session: SessionDep, current_user: CurrentUser, id: int, item_in: ItemUpdate
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update an item.
|
||||||
|
"""
|
||||||
|
item = session.get(Item, id)
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
if not current_user.is_superuser and (item.owner_id != current_user.id):
|
||||||
|
raise HTTPException(status_code=400, detail="Not enough permissions")
|
||||||
|
update_dict = item_in.model_dump(exclude_unset=True)
|
||||||
|
item.sqlmodel_update(update_dict)
|
||||||
|
session.add(item)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(item)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{id}")
|
||||||
|
def delete_item(session: SessionDep, current_user: CurrentUser, id: int) -> Message:
|
||||||
|
"""
|
||||||
|
Delete an item.
|
||||||
|
"""
|
||||||
|
item = session.get(Item, id)
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
if not current_user.is_superuser and (item.owner_id != current_user.id):
|
||||||
|
raise HTTPException(status_code=400, detail="Not enough permissions")
|
||||||
|
session.delete(item)
|
||||||
|
session.commit()
|
||||||
|
return Message(message="Item deleted successfully")
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
|
||||||
|
from app.core import security
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.core.security import get_password_hash
|
||||||
|
from app.models import Message, NewPassword, Token, UserOut
|
||||||
|
from app.utils import (
|
||||||
|
generate_password_reset_token,
|
||||||
|
generate_reset_password_email,
|
||||||
|
send_email,
|
||||||
|
verify_password_reset_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login/access-token")
|
||||||
|
def login_access_token(
|
||||||
|
session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
|
||||||
|
) -> Token:
|
||||||
|
"""
|
||||||
|
OAuth2 compatible token login, get an access token for future requests
|
||||||
|
"""
|
||||||
|
user = crud.authenticate(
|
||||||
|
session=session, email=form_data.username, password=form_data.password
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=400, detail="Incorrect email or password")
|
||||||
|
elif not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
return Token(
|
||||||
|
access_token=security.create_access_token(
|
||||||
|
user.id, expires_delta=access_token_expires
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login/test-token", response_model=UserOut)
|
||||||
|
def test_token(current_user: CurrentUser) -> Any:
|
||||||
|
"""
|
||||||
|
Test access token
|
||||||
|
"""
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/password-recovery/{email}")
|
||||||
|
def recover_password(email: str, session: SessionDep) -> Message:
|
||||||
|
"""
|
||||||
|
Password Recovery
|
||||||
|
"""
|
||||||
|
user = crud.get_user_by_email(session=session, email=email)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this email does not exist in the system.",
|
||||||
|
)
|
||||||
|
password_reset_token = generate_password_reset_token(email=email)
|
||||||
|
email_data = generate_reset_password_email(
|
||||||
|
email_to=user.email, email=email, token=password_reset_token
|
||||||
|
)
|
||||||
|
send_email(
|
||||||
|
email_to=user.email,
|
||||||
|
subject=email_data.subject,
|
||||||
|
html_content=email_data.html_content,
|
||||||
|
)
|
||||||
|
return Message(message="Password recovery email sent")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/reset-password/")
|
||||||
|
def reset_password(session: SessionDep, body: NewPassword) -> Message:
|
||||||
|
"""
|
||||||
|
Reset password
|
||||||
|
"""
|
||||||
|
email = verify_password_reset_token(token=body.token)
|
||||||
|
if not email:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid token")
|
||||||
|
user = crud.get_user_by_email(session=session, email=email)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this email does not exist in the system.",
|
||||||
|
)
|
||||||
|
elif not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
hashed_password = get_password_hash(password=body.new_password)
|
||||||
|
user.hashed_password = hashed_password
|
||||||
|
session.add(user)
|
||||||
|
session.commit()
|
||||||
|
return Message(message="Password updated successfully")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/password-recovery-html-content/{email}",
|
||||||
|
dependencies=[Depends(get_current_active_superuser)],
|
||||||
|
response_class=HTMLResponse,
|
||||||
|
)
|
||||||
|
def recover_password_html_content(email: str, session: SessionDep) -> Any:
|
||||||
|
"""
|
||||||
|
HTML Content for Password Recovery
|
||||||
|
"""
|
||||||
|
user = crud.get_user_by_email(session=session, email=email)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this username does not exist in the system.",
|
||||||
|
)
|
||||||
|
password_reset_token = generate_password_reset_token(email=email)
|
||||||
|
email_data = generate_reset_password_email(
|
||||||
|
email_to=user.email, email=email, token=password_reset_token
|
||||||
|
)
|
||||||
|
|
||||||
|
return HTMLResponse(
|
||||||
|
content=email_data.html_content, headers={"subject:": email_data.subject}
|
||||||
|
)
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlmodel import col, delete, func, select
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.api.deps import (
|
||||||
|
CurrentUser,
|
||||||
|
SessionDep,
|
||||||
|
get_current_active_superuser,
|
||||||
|
)
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.models import (
|
||||||
|
Item,
|
||||||
|
Message,
|
||||||
|
UpdatePassword,
|
||||||
|
User,
|
||||||
|
UserCreate,
|
||||||
|
UserCreateOpen,
|
||||||
|
UserOut,
|
||||||
|
UsersOut,
|
||||||
|
UserUpdate,
|
||||||
|
UserUpdateMe,
|
||||||
|
)
|
||||||
|
from app.utils import generate_new_account_email, send_email
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersOut
|
||||||
|
)
|
||||||
|
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve users.
|
||||||
|
"""
|
||||||
|
|
||||||
|
statment = select(func.count()).select_from(User)
|
||||||
|
count = session.exec(statment).one()
|
||||||
|
|
||||||
|
statement = select(User).offset(skip).limit(limit)
|
||||||
|
users = session.exec(statement).all()
|
||||||
|
|
||||||
|
return UsersOut(data=users, count=count)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserOut
|
||||||
|
)
|
||||||
|
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
|
||||||
|
"""
|
||||||
|
Create new user.
|
||||||
|
"""
|
||||||
|
user = crud.get_user_by_email(session=session, email=user_in.email)
|
||||||
|
if user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The user with this email already exists in the system.",
|
||||||
|
)
|
||||||
|
|
||||||
|
user = crud.create_user(session=session, user_create=user_in)
|
||||||
|
if settings.emails_enabled and user_in.email:
|
||||||
|
email_data = generate_new_account_email(
|
||||||
|
email_to=user_in.email, username=user_in.email, password=user_in.password
|
||||||
|
)
|
||||||
|
send_email(
|
||||||
|
email_to=user_in.email,
|
||||||
|
subject=email_data.subject,
|
||||||
|
html_content=email_data.html_content,
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/me", response_model=UserOut)
|
||||||
|
def update_user_me(
|
||||||
|
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update own user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if user_in.email:
|
||||||
|
existing_user = crud.get_user_by_email(session=session, email=user_in.email)
|
||||||
|
if existing_user and existing_user.id != current_user.id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409, detail="User with this email already exists"
|
||||||
|
)
|
||||||
|
user_data = user_in.model_dump(exclude_unset=True)
|
||||||
|
current_user.sqlmodel_update(user_data)
|
||||||
|
session.add(current_user)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(current_user)
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/me/password", response_model=Message)
|
||||||
|
def update_password_me(
|
||||||
|
*, session: SessionDep, body: UpdatePassword, current_user: CurrentUser
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update own password.
|
||||||
|
"""
|
||||||
|
if not verify_password(body.current_password, current_user.hashed_password):
|
||||||
|
raise HTTPException(status_code=400, detail="Incorrect password")
|
||||||
|
if body.current_password == body.new_password:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="New password cannot be the same as the current one"
|
||||||
|
)
|
||||||
|
hashed_password = get_password_hash(body.new_password)
|
||||||
|
current_user.hashed_password = hashed_password
|
||||||
|
session.add(current_user)
|
||||||
|
session.commit()
|
||||||
|
return Message(message="Password updated successfully")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserOut)
|
||||||
|
def read_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
|
||||||
|
"""
|
||||||
|
Get current user.
|
||||||
|
"""
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/open", response_model=UserOut)
|
||||||
|
def create_user_open(session: SessionDep, user_in: UserCreateOpen) -> Any:
|
||||||
|
"""
|
||||||
|
Create new user without the need to be logged in.
|
||||||
|
"""
|
||||||
|
if not settings.USERS_OPEN_REGISTRATION:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Open user registration is forbidden on this server",
|
||||||
|
)
|
||||||
|
user = crud.get_user_by_email(session=session, email=user_in.email)
|
||||||
|
if user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The user with this email already exists in the system",
|
||||||
|
)
|
||||||
|
user_create = UserCreate.from_orm(user_in)
|
||||||
|
user = crud.create_user(session=session, user_create=user_create)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}", response_model=UserOut)
|
||||||
|
def read_user_by_id(
|
||||||
|
user_id: int, session: SessionDep, current_user: CurrentUser
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get a specific user by id.
|
||||||
|
"""
|
||||||
|
user = session.get(User, user_id)
|
||||||
|
if user == current_user:
|
||||||
|
return user
|
||||||
|
if not current_user.is_superuser:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="The user doesn't have enough privileges",
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch(
|
||||||
|
"/{user_id}",
|
||||||
|
dependencies=[Depends(get_current_active_superuser)],
|
||||||
|
response_model=UserOut,
|
||||||
|
)
|
||||||
|
def update_user(
|
||||||
|
*,
|
||||||
|
session: SessionDep,
|
||||||
|
user_id: int,
|
||||||
|
user_in: UserUpdate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
db_user = session.get(User, user_id)
|
||||||
|
if not db_user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this id does not exist in the system",
|
||||||
|
)
|
||||||
|
if user_in.email:
|
||||||
|
existing_user = crud.get_user_by_email(session=session, email=user_in.email)
|
||||||
|
if existing_user and existing_user.id != user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409, detail="User with this email already exists"
|
||||||
|
)
|
||||||
|
|
||||||
|
db_user = crud.update_user(session=session, db_user=db_user, user_in=user_in)
|
||||||
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}")
|
||||||
|
def delete_user(
|
||||||
|
session: SessionDep, current_user: CurrentUser, user_id: int
|
||||||
|
) -> Message:
|
||||||
|
"""
|
||||||
|
Delete a user.
|
||||||
|
"""
|
||||||
|
user = session.get(User, user_id)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
elif user != current_user and not current_user.is_superuser:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403, detail="The user doesn't have enough privileges"
|
||||||
|
)
|
||||||
|
elif user == current_user and current_user.is_superuser:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403, detail="Super users are not allowed to delete themselves"
|
||||||
|
)
|
||||||
|
|
||||||
|
statement = delete(Item).where(col(Item.owner_id) == user_id)
|
||||||
|
session.exec(statement) # type: ignore
|
||||||
|
session.delete(user)
|
||||||
|
session.commit()
|
||||||
|
return Message(message="User deleted successfully")
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic.networks import EmailStr
|
||||||
|
|
||||||
|
from app.api.deps import get_current_active_superuser
|
||||||
|
from app.models import Message
|
||||||
|
from app.utils import generate_test_email, send_email
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/test-email/",
|
||||||
|
dependencies=[Depends(get_current_active_superuser)],
|
||||||
|
status_code=201,
|
||||||
|
)
|
||||||
|
def test_email(email_to: EmailStr) -> Message:
|
||||||
|
"""
|
||||||
|
Test emails.
|
||||||
|
"""
|
||||||
|
email_data = generate_test_email(email_to=email_to)
|
||||||
|
send_email(
|
||||||
|
email_to=email_to,
|
||||||
|
subject=email_data.subject,
|
||||||
|
html_content=email_data.html_content,
|
||||||
|
)
|
||||||
|
return Message(message="Test email sent")
|
||||||
+9
-9
@@ -1,9 +1,10 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from sqlalchemy import Engine
|
||||||
|
from sqlmodel import Session, select
|
||||||
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
||||||
|
|
||||||
from app.db.session import db_session
|
from app.core.db import engine
|
||||||
from app.tests.api.api_v1.test_token import test_get_access_token
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -18,20 +19,19 @@ wait_seconds = 1
|
|||||||
before=before_log(logger, logging.INFO),
|
before=before_log(logger, logging.INFO),
|
||||||
after=after_log(logger, logging.WARN),
|
after=after_log(logger, logging.WARN),
|
||||||
)
|
)
|
||||||
def init():
|
def init(db_engine: Engine) -> None:
|
||||||
try:
|
try:
|
||||||
# Try to create session to check if DB is awake
|
with Session(db_engine) as session:
|
||||||
db_session.execute("SELECT 1")
|
# Try to create session to check if DB is awake
|
||||||
# Wait for API to be awake, run one simple tests to authenticate
|
session.exec(select(1))
|
||||||
test_get_access_token()
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
logger.info("Initializing service")
|
logger.info("Initializing service")
|
||||||
init()
|
init(engine)
|
||||||
logger.info("Service finished initializing")
|
logger.info("Service finished initializing")
|
||||||
|
|
||||||
|
|
||||||
+8
-5
@@ -1,8 +1,10 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from sqlalchemy import Engine
|
||||||
|
from sqlmodel import Session, select
|
||||||
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
||||||
|
|
||||||
from app.db.session import db_session
|
from app.core.db import engine
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -17,18 +19,19 @@ wait_seconds = 1
|
|||||||
before=before_log(logger, logging.INFO),
|
before=before_log(logger, logging.INFO),
|
||||||
after=after_log(logger, logging.WARN),
|
after=after_log(logger, logging.WARN),
|
||||||
)
|
)
|
||||||
def init():
|
def init(db_engine: Engine) -> None:
|
||||||
try:
|
try:
|
||||||
# Try to create session to check if DB is awake
|
# Try to create session to check if DB is awake
|
||||||
db_session.execute("SELECT 1")
|
with Session(db_engine) as session:
|
||||||
|
session.exec(select(1))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
logger.info("Initializing service")
|
logger.info("Initializing service")
|
||||||
init()
|
init(engine)
|
||||||
logger.info("Service finished initializing")
|
logger.info("Service finished initializing")
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import secrets
|
||||||
|
import warnings
|
||||||
|
from typing import Annotated, Any, Literal
|
||||||
|
|
||||||
|
from pydantic import (
|
||||||
|
AnyUrl,
|
||||||
|
BeforeValidator,
|
||||||
|
HttpUrl,
|
||||||
|
PostgresDsn,
|
||||||
|
computed_field,
|
||||||
|
model_validator,
|
||||||
|
)
|
||||||
|
from pydantic_core import MultiHostUrl
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
from typing_extensions import Self
|
||||||
|
|
||||||
|
|
||||||
|
def parse_cors(v: Any) -> list[str] | str:
|
||||||
|
if isinstance(v, str) and not v.startswith("["):
|
||||||
|
return [i.strip() for i in v.split(",")]
|
||||||
|
elif isinstance(v, list | str):
|
||||||
|
return v
|
||||||
|
raise ValueError(v)
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env", env_ignore_empty=True, extra="ignore"
|
||||||
|
)
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
SECRET_KEY: str = secrets.token_urlsafe(32)
|
||||||
|
# 60 minutes * 24 hours * 8 days = 8 days
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
|
||||||
|
DOMAIN: str = "localhost"
|
||||||
|
ENVIRONMENT: Literal["local", "staging", "production"] = "local"
|
||||||
|
|
||||||
|
@computed_field # type: ignore[misc]
|
||||||
|
@property
|
||||||
|
def server_host(self) -> str:
|
||||||
|
# Use HTTPS for anything other than local development
|
||||||
|
if self.ENVIRONMENT == "local":
|
||||||
|
return f"http://{self.DOMAIN}"
|
||||||
|
return f"https://{self.DOMAIN}"
|
||||||
|
|
||||||
|
BACKEND_CORS_ORIGINS: Annotated[
|
||||||
|
list[AnyUrl] | str, BeforeValidator(parse_cors)
|
||||||
|
] = []
|
||||||
|
|
||||||
|
PROJECT_NAME: str
|
||||||
|
SENTRY_DSN: HttpUrl | None = None
|
||||||
|
POSTGRES_SERVER: str
|
||||||
|
POSTGRES_PORT: int = 5432
|
||||||
|
POSTGRES_USER: str
|
||||||
|
POSTGRES_PASSWORD: str
|
||||||
|
POSTGRES_DB: str = ""
|
||||||
|
|
||||||
|
@computed_field # type: ignore[misc]
|
||||||
|
@property
|
||||||
|
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
|
||||||
|
return MultiHostUrl.build(
|
||||||
|
scheme="postgresql+psycopg",
|
||||||
|
username=self.POSTGRES_USER,
|
||||||
|
password=self.POSTGRES_PASSWORD,
|
||||||
|
host=self.POSTGRES_SERVER,
|
||||||
|
port=self.POSTGRES_PORT,
|
||||||
|
path=self.POSTGRES_DB,
|
||||||
|
)
|
||||||
|
|
||||||
|
SMTP_TLS: bool = True
|
||||||
|
SMTP_SSL: bool = False
|
||||||
|
SMTP_PORT: int = 587
|
||||||
|
SMTP_HOST: str | None = None
|
||||||
|
SMTP_USER: str | None = None
|
||||||
|
SMTP_PASSWORD: str | None = None
|
||||||
|
# TODO: update type to EmailStr when sqlmodel supports it
|
||||||
|
EMAILS_FROM_EMAIL: str | None = None
|
||||||
|
EMAILS_FROM_NAME: str | None = None
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _set_default_emails_from(self) -> Self:
|
||||||
|
if not self.EMAILS_FROM_NAME:
|
||||||
|
self.EMAILS_FROM_NAME = self.PROJECT_NAME
|
||||||
|
return self
|
||||||
|
|
||||||
|
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
|
||||||
|
|
||||||
|
@computed_field # type: ignore[misc]
|
||||||
|
@property
|
||||||
|
def emails_enabled(self) -> bool:
|
||||||
|
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
|
||||||
|
|
||||||
|
# TODO: update type to EmailStr when sqlmodel supports it
|
||||||
|
EMAIL_TEST_USER: str = "test@example.com"
|
||||||
|
# TODO: update type to EmailStr when sqlmodel supports it
|
||||||
|
FIRST_SUPERUSER: str
|
||||||
|
FIRST_SUPERUSER_PASSWORD: str
|
||||||
|
USERS_OPEN_REGISTRATION: bool = False
|
||||||
|
|
||||||
|
def _check_default_secret(self, var_name: str, value: str | None) -> None:
|
||||||
|
if value == "changethis":
|
||||||
|
message = (
|
||||||
|
f'The value of {var_name} is "changethis", '
|
||||||
|
"for security, please change it, at least for deployments."
|
||||||
|
)
|
||||||
|
if self.ENVIRONMENT == "local":
|
||||||
|
warnings.warn(message, stacklevel=1)
|
||||||
|
else:
|
||||||
|
raise ValueError(message)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _enforce_non_default_secrets(self) -> Self:
|
||||||
|
self._check_default_secret("SECRET_KEY", self.SECRET_KEY)
|
||||||
|
self._check_default_secret("POSTGRES_PASSWORD", self.POSTGRES_PASSWORD)
|
||||||
|
self._check_default_secret(
|
||||||
|
"FIRST_SUPERUSER_PASSWORD", self.FIRST_SUPERUSER_PASSWORD
|
||||||
|
)
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings() # type: ignore
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from sqlmodel import Session, create_engine, select
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.models import User, UserCreate
|
||||||
|
|
||||||
|
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
|
||||||
|
|
||||||
|
|
||||||
|
# make sure all SQLModel models are imported (app.models) before initializing DB
|
||||||
|
# otherwise, SQLModel might fail to initialize relationships properly
|
||||||
|
# for more details: https://github.com/tiangolo/full-stack-fastapi-template/issues/28
|
||||||
|
|
||||||
|
|
||||||
|
def init_db(session: Session) -> None:
|
||||||
|
# Tables should be created with Alembic migrations
|
||||||
|
# But if you don't want to use migrations, create
|
||||||
|
# the tables un-commenting the next lines
|
||||||
|
# from sqlmodel import SQLModel
|
||||||
|
|
||||||
|
# from app.core.engine import engine
|
||||||
|
# This works because the models are already imported and registered from app.models
|
||||||
|
# SQLModel.metadata.create_all(engine)
|
||||||
|
|
||||||
|
user = session.exec(
|
||||||
|
select(User).where(User.email == settings.FIRST_SUPERUSER)
|
||||||
|
).first()
|
||||||
|
if not user:
|
||||||
|
user_in = UserCreate(
|
||||||
|
email=settings.FIRST_SUPERUSER,
|
||||||
|
password=settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
is_superuser=True,
|
||||||
|
)
|
||||||
|
user = crud.create_user(session=session, user_create=user_in)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jose import jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
|
||||||
|
expire = datetime.utcnow() + expires_delta
|
||||||
|
to_encode = {"exp": expire, "sub": str(subject)}
|
||||||
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
|
||||||
|
return encoded_jwt
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
return pwd_context.verify(plain_password, hashed_password)
|
||||||
|
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.models import Item, ItemCreate, User, UserCreate, UserUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(*, session: Session, user_create: UserCreate) -> User:
|
||||||
|
db_obj = User.model_validate(
|
||||||
|
user_create, update={"hashed_password": get_password_hash(user_create.password)}
|
||||||
|
)
|
||||||
|
session.add(db_obj)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def update_user(*, session: Session, db_user: User, user_in: UserUpdate) -> Any:
|
||||||
|
user_data = user_in.model_dump(exclude_unset=True)
|
||||||
|
extra_data = {}
|
||||||
|
if "password" in user_data:
|
||||||
|
password = user_data["password"]
|
||||||
|
hashed_password = get_password_hash(password)
|
||||||
|
extra_data["hashed_password"] = hashed_password
|
||||||
|
db_user.sqlmodel_update(user_data, update=extra_data)
|
||||||
|
session.add(db_user)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(db_user)
|
||||||
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_by_email(*, session: Session, email: str) -> User | None:
|
||||||
|
statement = select(User).where(User.email == email)
|
||||||
|
session_user = session.exec(statement).first()
|
||||||
|
return session_user
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate(*, session: Session, email: str, password: str) -> User | None:
|
||||||
|
db_user = get_user_by_email(session=session, email=email)
|
||||||
|
if not db_user:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, db_user.hashed_password):
|
||||||
|
return None
|
||||||
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
|
def create_item(*, session: Session, item_in: ItemCreate, owner_id: int) -> Item:
|
||||||
|
db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
|
||||||
|
session.add(db_item)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(db_item)
|
||||||
|
return db_item
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
|
||||||
|
.ReadMsgBody { width:100%; }
|
||||||
|
.ExternalClass { width:100%; }
|
||||||
|
.ExternalClass * { line-height:100%; }
|
||||||
|
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
|
||||||
|
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
|
||||||
|
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
|
||||||
|
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
|
||||||
|
@-ms-viewport { width:320px; }
|
||||||
|
@viewport { width:320px; }
|
||||||
|
}</style><!--<![endif]--><!--[if mso]>
|
||||||
|
<xml>
|
||||||
|
<o:OfficeDocumentSettings>
|
||||||
|
<o:AllowPNG/>
|
||||||
|
<o:PixelsPerInch>96</o:PixelsPerInch>
|
||||||
|
</o:OfficeDocumentSettings>
|
||||||
|
</xml>
|
||||||
|
<![endif]--><!--[if lte mso 11]>
|
||||||
|
<style type="text/css">
|
||||||
|
.outlook-group-fix { width:100% !important; }
|
||||||
|
</style>
|
||||||
|
<![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
|
||||||
|
.mj-column-per-100 { width:100% !important; max-width: 100%; }
|
||||||
|
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - New Account</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Welcome to your new account!</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Here are your account details:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Username: {{ username }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Password: {{ password }}</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Go to Dashboard</a></td></tr></table></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;">
|
||||||
|
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
|
||||||
|
.ReadMsgBody { width:100%; }
|
||||||
|
.ExternalClass { width:100%; }
|
||||||
|
.ExternalClass * { line-height:100%; }
|
||||||
|
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
|
||||||
|
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
|
||||||
|
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
|
||||||
|
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
|
||||||
|
@-ms-viewport { width:320px; }
|
||||||
|
@viewport { width:320px; }
|
||||||
|
}</style><!--<![endif]--><!--[if mso]>
|
||||||
|
<xml>
|
||||||
|
<o:OfficeDocumentSettings>
|
||||||
|
<o:AllowPNG/>
|
||||||
|
<o:PixelsPerInch>96</o:PixelsPerInch>
|
||||||
|
</o:OfficeDocumentSettings>
|
||||||
|
</xml>
|
||||||
|
<![endif]--><!--[if lte mso 11]>
|
||||||
|
<style type="text/css">
|
||||||
|
.outlook-group-fix { width:100% !important; }
|
||||||
|
</style>
|
||||||
|
<![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
|
||||||
|
.mj-column-per-100 { width:100% !important; max-width: 100%; }
|
||||||
|
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - Password Recovery</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Hello {{ username }}</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">We've received a request to reset your password. You can do it by clicking the button below:</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Reset password</a></td></tr></table></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Or copy and paste the following link into your browser:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><a href="{{ link }}">{{ link }}</a></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">This password will expire in {{ valid_hours }} hours.</div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;">
|
||||||
|
</td></tr></table><![endif]--></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:1;text-align:center;color:#555555;">If you didn't request a password recovery you can disregard this email.</div></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
|
||||||
|
.ReadMsgBody { width:100%; }
|
||||||
|
.ExternalClass { width:100%; }
|
||||||
|
.ExternalClass * { line-height:100%; }
|
||||||
|
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
|
||||||
|
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
|
||||||
|
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
|
||||||
|
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
|
||||||
|
@-ms-viewport { width:320px; }
|
||||||
|
@viewport { width:320px; }
|
||||||
|
}</style><!--<![endif]--><!--[if mso]>
|
||||||
|
<xml>
|
||||||
|
<o:OfficeDocumentSettings>
|
||||||
|
<o:AllowPNG/>
|
||||||
|
<o:PixelsPerInch>96</o:PixelsPerInch>
|
||||||
|
</o:OfficeDocumentSettings>
|
||||||
|
</xml>
|
||||||
|
<![endif]--><!--[if lte mso 11]>
|
||||||
|
<style type="text/css">
|
||||||
|
.outlook-group-fix { width:100% !important; }
|
||||||
|
</style>
|
||||||
|
<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
|
||||||
|
.mj-column-per-100 { width:100% !important; max-width: 100%; }
|
||||||
|
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Test email for: {{ email }}</span></div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;">
|
||||||
|
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<mjml>
|
||||||
|
<mj-body background-color="#fafbfc">
|
||||||
|
<mj-section background-color="#fff" padding="40px 20px">
|
||||||
|
<mj-column vertical-align="middle" width="100%">
|
||||||
|
<mj-text align="center" padding="35px" font-size="20px" color="#333">{{ project_name }} - New Account</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Welcome to your new account!</span></mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Here are your account details:</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Username: {{ username }}</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Password: {{ password }}</mj-text>
|
||||||
|
<mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Go to Dashboard</mj-button>
|
||||||
|
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
|
||||||
|
</mj-column>
|
||||||
|
</mj-section>
|
||||||
|
</mj-body>
|
||||||
|
</mjml>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<mjml>
|
||||||
|
<mj-body background-color="#fafbfc">
|
||||||
|
<mj-section background-color="#fff" padding="40px 20px">
|
||||||
|
<mj-column vertical-align="middle" width="100%">
|
||||||
|
<mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }} - Password Recovery</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Hello {{ username }}</span></mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">We've received a request to reset your password. You can do it by clicking the button below:</mj-text>
|
||||||
|
<mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Reset password</mj-button>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Or copy and paste the following link into your browser:</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><a href="{{ link }}">{{ link }}</a></mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">This password will expire in {{ valid_hours }} hours.</mj-text>
|
||||||
|
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
|
||||||
|
<mj-text align="center" font-size="14px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">If you didn't request a password recovery you can disregard this email.</mj-text>
|
||||||
|
</mj-column>
|
||||||
|
</mj-section>
|
||||||
|
</mj-body>
|
||||||
|
</mjml>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<mjml>
|
||||||
|
<mj-body background-color="#fafbfc">
|
||||||
|
<mj-section background-color="#fff" padding="40px 20px">
|
||||||
|
<mj-column vertical-align="middle" width="100%">
|
||||||
|
<mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }}</mj-text>
|
||||||
|
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family=", sans-serif" color="#555"><span>Test email for: {{ email }}</span></mj-text>
|
||||||
|
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
|
||||||
|
</mj-column>
|
||||||
|
</mj-section>
|
||||||
|
</mj-body>
|
||||||
|
</mjml>
|
||||||
+7
-5
@@ -1,17 +1,19 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from app.db.init_db import init_db
|
from sqlmodel import Session
|
||||||
from app.db.session import db_session
|
|
||||||
|
from app.core.db import engine, init_db
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def init():
|
def init() -> None:
|
||||||
init_db(db_session)
|
with Session(engine) as session:
|
||||||
|
init_db(session)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
logger.info("Creating initial data")
|
logger.info("Creating initial data")
|
||||||
init()
|
init()
|
||||||
logger.info("Initial data created")
|
logger.info("Initial data created")
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.routing import APIRoute
|
||||||
|
from starlette.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.api.main import api_router
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
def custom_generate_unique_id(route: APIRoute) -> str:
|
||||||
|
return f"{route.tags[0]}-{route.name}"
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
||||||
|
generate_unique_id_function=custom_generate_unique_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set all CORS enabled origins
|
||||||
|
if settings.BACKEND_CORS_ORIGINS:
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=[
|
||||||
|
str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
|
||||||
|
],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
# TODO replace email str with EmailStr when sqlmodel supports it
|
||||||
|
class UserBase(SQLModel):
|
||||||
|
email: str = Field(unique=True, index=True)
|
||||||
|
is_active: bool = True
|
||||||
|
is_superuser: bool = False
|
||||||
|
full_name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on creation
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
# TODO replace email str with EmailStr when sqlmodel supports it
|
||||||
|
class UserCreateOpen(SQLModel):
|
||||||
|
email: str
|
||||||
|
password: str
|
||||||
|
full_name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on update, all are optional
|
||||||
|
# TODO replace email str with EmailStr when sqlmodel supports it
|
||||||
|
class UserUpdate(UserBase):
|
||||||
|
email: str | None = None # type: ignore
|
||||||
|
password: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# TODO replace email str with EmailStr when sqlmodel supports it
|
||||||
|
class UserUpdateMe(SQLModel):
|
||||||
|
full_name: str | None = None
|
||||||
|
email: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class UpdatePassword(SQLModel):
|
||||||
|
current_password: str
|
||||||
|
new_password: str
|
||||||
|
|
||||||
|
|
||||||
|
# Database model, database table inferred from class name
|
||||||
|
class User(UserBase, table=True):
|
||||||
|
id: int | None = Field(default=None, primary_key=True)
|
||||||
|
hashed_password: str
|
||||||
|
items: list["Item"] = Relationship(back_populates="owner")
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to return via API, id is always required
|
||||||
|
class UserOut(UserBase):
|
||||||
|
id: int
|
||||||
|
|
||||||
|
|
||||||
|
class UsersOut(SQLModel):
|
||||||
|
data: list[UserOut]
|
||||||
|
count: int
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class ItemBase(SQLModel):
|
||||||
|
title: str
|
||||||
|
description: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item creation
|
||||||
|
class ItemCreate(ItemBase):
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item update
|
||||||
|
class ItemUpdate(ItemBase):
|
||||||
|
title: str | None = None # type: ignore
|
||||||
|
|
||||||
|
|
||||||
|
# Database model, database table inferred from class name
|
||||||
|
class Item(ItemBase, table=True):
|
||||||
|
id: int | None = Field(default=None, primary_key=True)
|
||||||
|
title: str
|
||||||
|
owner_id: int | None = Field(default=None, foreign_key="user.id", nullable=False)
|
||||||
|
owner: User | None = Relationship(back_populates="items")
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to return via API, id is always required
|
||||||
|
class ItemOut(ItemBase):
|
||||||
|
id: int
|
||||||
|
owner_id: int
|
||||||
|
|
||||||
|
|
||||||
|
class ItemsOut(SQLModel):
|
||||||
|
data: list[ItemOut]
|
||||||
|
count: int
|
||||||
|
|
||||||
|
|
||||||
|
# Generic message
|
||||||
|
class Message(SQLModel):
|
||||||
|
message: str
|
||||||
|
|
||||||
|
|
||||||
|
# JSON payload containing access token
|
||||||
|
class Token(SQLModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
# Contents of JWT token
|
||||||
|
class TokenPayload(SQLModel):
|
||||||
|
sub: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class NewPassword(SQLModel):
|
||||||
|
token: str
|
||||||
|
new_password: str
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.tests.utils.item import create_random_item
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_item(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
data = {"title": "Foo", "description": "Fighters"}
|
||||||
|
response = client.post(
|
||||||
|
f"{settings.API_V1_STR}/items/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
content = response.json()
|
||||||
|
assert content["title"] == data["title"]
|
||||||
|
assert content["description"] == data["description"]
|
||||||
|
assert "id" in content
|
||||||
|
assert "owner_id" in content
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_item(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
response = client.get(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
content = response.json()
|
||||||
|
assert content["title"] == item.title
|
||||||
|
assert content["description"] == item.description
|
||||||
|
assert content["id"] == item.id
|
||||||
|
assert content["owner_id"] == item.owner_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_item_not_found(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
response = client.get(
|
||||||
|
f"{settings.API_V1_STR}/items/999",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 404
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Item not found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_item_not_enough_permissions(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
response = client.get(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Not enough permissions"
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_items(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
create_random_item(db)
|
||||||
|
create_random_item(db)
|
||||||
|
response = client.get(
|
||||||
|
f"{settings.API_V1_STR}/items/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
content = response.json()
|
||||||
|
assert len(content["data"]) >= 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_item(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
data = {"title": "Updated title", "description": "Updated description"}
|
||||||
|
response = client.put(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
content = response.json()
|
||||||
|
assert content["title"] == data["title"]
|
||||||
|
assert content["description"] == data["description"]
|
||||||
|
assert content["id"] == item.id
|
||||||
|
assert content["owner_id"] == item.owner_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_item_not_found(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
data = {"title": "Updated title", "description": "Updated description"}
|
||||||
|
response = client.put(
|
||||||
|
f"{settings.API_V1_STR}/items/999",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert response.status_code == 404
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Item not found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_item_not_enough_permissions(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
data = {"title": "Updated title", "description": "Updated description"}
|
||||||
|
response = client.put(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Not enough permissions"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_item(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
response = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
content = response.json()
|
||||||
|
assert content["message"] == "Item deleted successfully"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_item_not_found(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
response = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/items/999",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 404
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Item not found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_item_not_enough_permissions(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
item = create_random_item(db)
|
||||||
|
response = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/items/{item.id}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
content = response.json()
|
||||||
|
assert content["detail"] == "Not enough permissions"
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pytest_mock import MockerFixture
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.utils import generate_password_reset_token
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_access_token(client: TestClient) -> None:
|
||||||
|
login_data = {
|
||||||
|
"username": settings.FIRST_SUPERUSER,
|
||||||
|
"password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
}
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
|
||||||
|
tokens = r.json()
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "access_token" in tokens
|
||||||
|
assert tokens["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_access_token_incorrect_password(client: TestClient) -> None:
|
||||||
|
login_data = {
|
||||||
|
"username": settings.FIRST_SUPERUSER,
|
||||||
|
"password": "incorrect",
|
||||||
|
}
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
|
||||||
|
assert r.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_use_access_token(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/login/test-token",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
result = r.json()
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "email" in result
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovery_password(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], mocker: MockerFixture
|
||||||
|
) -> None:
|
||||||
|
mocker.patch("app.utils.send_email", return_value=None)
|
||||||
|
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
|
||||||
|
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
|
||||||
|
email = "test@example.com"
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/password-recovery/{email}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json() == {"message": "Password recovery email sent"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovery_password_user_not_exits(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
email = "jVgQr@example.com"
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/password-recovery/{email}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER)
|
||||||
|
data = {"new_password": "changethis", "token": token}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/reset-password/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json() == {"message": "Password updated successfully"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_invalid_token(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
data = {"new_password": "changethis", "token": "invalid"}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/reset-password/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
response = r.json()
|
||||||
|
|
||||||
|
assert "detail" in response
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert response["detail"] == "Invalid token"
|
||||||
@@ -0,0 +1,455 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pytest_mock import MockerFixture
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.models import UserCreate
|
||||||
|
from app.tests.utils.utils import random_email, random_lower_string
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_users_superuser_me(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
r = client.get(f"{settings.API_V1_STR}/users/me", headers=superuser_token_headers)
|
||||||
|
current_user = r.json()
|
||||||
|
assert current_user
|
||||||
|
assert current_user["is_active"] is True
|
||||||
|
assert current_user["is_superuser"]
|
||||||
|
assert current_user["email"] == settings.FIRST_SUPERUSER
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_users_normal_user_me(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
r = client.get(f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers)
|
||||||
|
current_user = r.json()
|
||||||
|
assert current_user
|
||||||
|
assert current_user["is_active"] is True
|
||||||
|
assert current_user["is_superuser"] is False
|
||||||
|
assert current_user["email"] == settings.EMAIL_TEST_USER
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_new_email(
|
||||||
|
client: TestClient,
|
||||||
|
superuser_token_headers: dict[str, str],
|
||||||
|
db: Session,
|
||||||
|
mocker: MockerFixture,
|
||||||
|
) -> None:
|
||||||
|
mocker.patch("app.utils.send_email")
|
||||||
|
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
|
||||||
|
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
data = {"email": username, "password": password}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert 200 <= r.status_code < 300
|
||||||
|
created_user = r.json()
|
||||||
|
user = crud.get_user_by_email(session=db, email=username)
|
||||||
|
assert user
|
||||||
|
assert user.email == created_user["email"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_existing_user(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_id = user.id
|
||||||
|
r = client.get(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert 200 <= r.status_code < 300
|
||||||
|
api_user = r.json()
|
||||||
|
existing_user = crud.get_user_by_email(session=db, email=username)
|
||||||
|
assert existing_user
|
||||||
|
assert existing_user.email == api_user["email"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_existing_user_current_user(client: TestClient, db: Session) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_id = user.id
|
||||||
|
|
||||||
|
login_data = {
|
||||||
|
"username": username,
|
||||||
|
"password": password,
|
||||||
|
}
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
|
||||||
|
tokens = r.json()
|
||||||
|
a_token = tokens["access_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {a_token}"}
|
||||||
|
|
||||||
|
r = client.get(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert 200 <= r.status_code < 300
|
||||||
|
api_user = r.json()
|
||||||
|
existing_user = crud.get_user_by_email(session=db, email=username)
|
||||||
|
assert existing_user
|
||||||
|
assert existing_user.email == api_user["email"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_existing_user_permissions_error(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
r = client.get(
|
||||||
|
f"{settings.API_V1_STR}/users/999999",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
assert r.json() == {"detail": "The user doesn't have enough privileges"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_existing_username(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
# username = email
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
crud.create_user(session=db, user_create=user_in)
|
||||||
|
data = {"email": username, "password": password}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
created_user = r.json()
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert "_id" not in created_user
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_by_normal_user(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
data = {"email": username, "password": password}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_retrieve_users(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
crud.create_user(session=db, user_create=user_in)
|
||||||
|
|
||||||
|
username2 = random_email()
|
||||||
|
password2 = random_lower_string()
|
||||||
|
user_in2 = UserCreate(email=username2, password=password2)
|
||||||
|
crud.create_user(session=db, user_create=user_in2)
|
||||||
|
|
||||||
|
r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers)
|
||||||
|
all_users = r.json()
|
||||||
|
|
||||||
|
assert len(all_users["data"]) > 1
|
||||||
|
assert "count" in all_users
|
||||||
|
for item in all_users["data"]:
|
||||||
|
assert "email" in item
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user_me(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
full_name = "Updated Name"
|
||||||
|
email = random_email()
|
||||||
|
data = {"full_name": full_name, "email": email}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
updated_user = r.json()
|
||||||
|
assert updated_user["email"] == email
|
||||||
|
assert updated_user["full_name"] == full_name
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_password_me(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
new_password = random_lower_string()
|
||||||
|
data = {
|
||||||
|
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
"new_password": new_password,
|
||||||
|
}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me/password",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
updated_user = r.json()
|
||||||
|
assert updated_user["message"] == "Password updated successfully"
|
||||||
|
|
||||||
|
# Revert to the old password to keep consistency in test
|
||||||
|
old_data = {
|
||||||
|
"current_password": new_password,
|
||||||
|
"new_password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me/password",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=old_data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_password_me_incorrect_password(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
new_password = random_lower_string()
|
||||||
|
data = {"current_password": new_password, "new_password": new_password}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me/password",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 400
|
||||||
|
updated_user = r.json()
|
||||||
|
assert updated_user["detail"] == "Incorrect password"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user_me_email_exists(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
|
||||||
|
data = {"email": user.email}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 409
|
||||||
|
assert r.json()["detail"] == "User with this email already exists"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_password_me_same_password_error(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
data = {
|
||||||
|
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
"new_password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/me/password",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 400
|
||||||
|
updated_user = r.json()
|
||||||
|
assert (
|
||||||
|
updated_user["detail"] == "New password cannot be the same as the current one"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
|
||||||
|
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
full_name = random_lower_string()
|
||||||
|
data = {"email": username, "password": password, "full_name": full_name}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/open",
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
created_user = r.json()
|
||||||
|
assert created_user["email"] == username
|
||||||
|
assert created_user["full_name"] == full_name
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_open_forbidden_error(
|
||||||
|
client: TestClient, mocker: MockerFixture
|
||||||
|
) -> None:
|
||||||
|
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", False)
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
full_name = random_lower_string()
|
||||||
|
data = {"email": username, "password": password, "full_name": full_name}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/open",
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
assert r.json()["detail"] == "Open user registration is forbidden on this server"
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_open_already_exists_error(
|
||||||
|
client: TestClient, mocker: MockerFixture
|
||||||
|
) -> None:
|
||||||
|
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
|
||||||
|
password = random_lower_string()
|
||||||
|
full_name = random_lower_string()
|
||||||
|
data = {
|
||||||
|
"email": settings.FIRST_SUPERUSER,
|
||||||
|
"password": password,
|
||||||
|
"full_name": full_name,
|
||||||
|
}
|
||||||
|
r = client.post(
|
||||||
|
f"{settings.API_V1_STR}/users/open",
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert r.json()["detail"] == "The user with this email already exists in the system"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
|
||||||
|
data = {"full_name": "Updated_full_name"}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/{user.id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
updated_user = r.json()
|
||||||
|
assert updated_user["full_name"] == "Updated_full_name"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user_not_exists(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
data = {"full_name": "Updated_full_name"}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/99999999",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 404
|
||||||
|
assert r.json()["detail"] == "The user with this id does not exist in the system"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user_email_exists(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
|
||||||
|
username2 = random_email()
|
||||||
|
password2 = random_lower_string()
|
||||||
|
user_in2 = UserCreate(email=username2, password=password2)
|
||||||
|
user2 = crud.create_user(session=db, user_create=user_in2)
|
||||||
|
|
||||||
|
data = {"email": user2.email}
|
||||||
|
r = client.patch(
|
||||||
|
f"{settings.API_V1_STR}/users/{user.id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
assert r.status_code == 409
|
||||||
|
assert r.json()["detail"] == "User with this email already exists"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_super_user(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_id = user.id
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
deleted_user = r.json()
|
||||||
|
assert deleted_user["message"] == "User deleted successfully"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_current_user(client: TestClient, db: Session) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_id = user.id
|
||||||
|
|
||||||
|
login_data = {
|
||||||
|
"username": username,
|
||||||
|
"password": password,
|
||||||
|
}
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
|
||||||
|
tokens = r.json()
|
||||||
|
a_token = tokens["access_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {a_token}"}
|
||||||
|
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
deleted_user = r.json()
|
||||||
|
assert deleted_user["message"] == "User deleted successfully"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_not_found(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/99999999",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 404
|
||||||
|
assert r.json()["detail"] == "User not found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_current_super_user_error(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
super_user = crud.get_user_by_email(session=db, email=settings.FIRST_SUPERUSER)
|
||||||
|
assert super_user
|
||||||
|
user_id = super_user.id
|
||||||
|
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
assert r.json()["detail"] == "Super users are not allowed to delete themselves"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_without_privileges(
|
||||||
|
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/{user.id}",
|
||||||
|
headers=normal_user_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
assert r.json()["detail"] == "The user doesn't have enough privileges"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from collections.abc import Generator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlmodel import Session, delete
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.core.db import engine, init_db
|
||||||
|
from app.main import app
|
||||||
|
from app.models import Item, User
|
||||||
|
from app.tests.utils.user import authentication_token_from_email
|
||||||
|
from app.tests.utils.utils import get_superuser_token_headers
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def db() -> Generator[Session, None, None]:
|
||||||
|
with Session(engine) as session:
|
||||||
|
init_db(session)
|
||||||
|
yield session
|
||||||
|
statement = delete(Item)
|
||||||
|
session.execute(statement)
|
||||||
|
statement = delete(User)
|
||||||
|
session.execute(statement)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client() -> Generator[TestClient, None, None]:
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def superuser_token_headers(client: TestClient) -> dict[str, str]:
|
||||||
|
return get_superuser_token_headers(client)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def normal_user_token_headers(client: TestClient, db: Session) -> dict[str, str]:
|
||||||
|
return authentication_token_from_email(
|
||||||
|
client=client, email=settings.EMAIL_TEST_USER, db=db
|
||||||
|
)
|
||||||
Executable → Regular
@@ -0,0 +1,91 @@
|
|||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.core.security import verify_password
|
||||||
|
from app.models import User, UserCreate, UserUpdate
|
||||||
|
from app.tests.utils.utils import random_email, random_lower_string
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
assert user.email == email
|
||||||
|
assert hasattr(user, "hashed_password")
|
||||||
|
|
||||||
|
|
||||||
|
def test_authenticate_user(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
authenticated_user = crud.authenticate(session=db, email=email, password=password)
|
||||||
|
assert authenticated_user
|
||||||
|
assert user.email == authenticated_user.email
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_authenticate_user(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user = crud.authenticate(session=db, email=email, password=password)
|
||||||
|
assert user is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_if_user_is_active(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
assert user.is_active is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_if_user_is_active_inactive(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password, disabled=True)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
assert user.is_active
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_if_user_is_superuser(db: Session) -> None:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password, is_superuser=True)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
assert user.is_superuser is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_if_user_is_superuser_normal_user(db: Session) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
assert user.is_superuser is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_user(db: Session) -> None:
|
||||||
|
password = random_lower_string()
|
||||||
|
username = random_email()
|
||||||
|
user_in = UserCreate(email=username, password=password, is_superuser=True)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_2 = db.get(User, user.id)
|
||||||
|
assert user_2
|
||||||
|
assert user.email == user_2.email
|
||||||
|
assert jsonable_encoder(user) == jsonable_encoder(user_2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_user(db: Session) -> None:
|
||||||
|
password = random_lower_string()
|
||||||
|
email = random_email()
|
||||||
|
user_in = UserCreate(email=email, password=password, is_superuser=True)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
new_password = random_lower_string()
|
||||||
|
user_in_update = UserUpdate(password=new_password, is_superuser=True)
|
||||||
|
if user.id is not None:
|
||||||
|
crud.update_user(session=db, db_user=user, user_in=user_in_update)
|
||||||
|
user_2 = db.get(User, user.id)
|
||||||
|
assert user_2
|
||||||
|
assert user.email == user_2.email
|
||||||
|
assert verify_password(new_password, user_2.hashed_password)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
from pytest_mock import MockerFixture
|
||||||
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from app.backend_pre_start import init, logger
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_successful_connection(mocker: MockerFixture) -> None:
|
||||||
|
engine_mock = MagicMock()
|
||||||
|
|
||||||
|
session_mock = MagicMock()
|
||||||
|
exec_mock = MagicMock(return_value=True)
|
||||||
|
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
||||||
|
mocker.patch("sqlmodel.Session", return_value=session_mock)
|
||||||
|
|
||||||
|
mocker.patch.object(logger, "info")
|
||||||
|
mocker.patch.object(logger, "error")
|
||||||
|
mocker.patch.object(logger, "warn")
|
||||||
|
|
||||||
|
try:
|
||||||
|
init(engine_mock)
|
||||||
|
connection_successful = True
|
||||||
|
except Exception:
|
||||||
|
connection_successful = False
|
||||||
|
|
||||||
|
assert (
|
||||||
|
connection_successful
|
||||||
|
), "The database connection should be successful and not raise an exception."
|
||||||
|
|
||||||
|
assert session_mock.exec.called_once_with(
|
||||||
|
select(1)
|
||||||
|
), "The session should execute a select statement once."
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
from pytest_mock import MockerFixture
|
||||||
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from app.tests_pre_start import init, logger
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_successful_connection(mocker: MockerFixture) -> None:
|
||||||
|
engine_mock = MagicMock()
|
||||||
|
|
||||||
|
session_mock = MagicMock()
|
||||||
|
exec_mock = MagicMock(return_value=True)
|
||||||
|
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
||||||
|
mocker.patch("sqlmodel.Session", return_value=session_mock)
|
||||||
|
|
||||||
|
mocker.patch.object(logger, "info")
|
||||||
|
mocker.patch.object(logger, "error")
|
||||||
|
mocker.patch.object(logger, "warn")
|
||||||
|
|
||||||
|
try:
|
||||||
|
init(engine_mock)
|
||||||
|
connection_successful = True
|
||||||
|
except Exception:
|
||||||
|
connection_successful = False
|
||||||
|
|
||||||
|
assert (
|
||||||
|
connection_successful
|
||||||
|
), "The database connection should be successful and not raise an exception."
|
||||||
|
|
||||||
|
assert session_mock.exec.called_once_with(
|
||||||
|
select(1)
|
||||||
|
), "The session should execute a select statement once."
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.models import Item, ItemCreate
|
||||||
|
from app.tests.utils.user import create_random_user
|
||||||
|
from app.tests.utils.utils import random_lower_string
|
||||||
|
|
||||||
|
|
||||||
|
def create_random_item(db: Session) -> Item:
|
||||||
|
user = create_random_user(db)
|
||||||
|
owner_id = user.id
|
||||||
|
assert owner_id is not None
|
||||||
|
title = random_lower_string()
|
||||||
|
description = random_lower_string()
|
||||||
|
item_in = ItemCreate(title=title, description=description)
|
||||||
|
return crud.create_item(session=db, item_in=item_in, owner_id=owner_id)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.models import User, UserCreate, UserUpdate
|
||||||
|
from app.tests.utils.utils import random_email, random_lower_string
|
||||||
|
|
||||||
|
|
||||||
|
def user_authentication_headers(
|
||||||
|
*, client: TestClient, email: str, password: str
|
||||||
|
) -> dict[str, str]:
|
||||||
|
data = {"username": email, "password": password}
|
||||||
|
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data)
|
||||||
|
response = r.json()
|
||||||
|
auth_token = response["access_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {auth_token}"}
|
||||||
|
return headers
|
||||||
|
|
||||||
|
|
||||||
|
def create_random_user(db: Session) -> User:
|
||||||
|
email = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=email, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def authentication_token_from_email(
|
||||||
|
*, client: TestClient, email: str, db: Session
|
||||||
|
) -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
Return a valid token for the user with given email.
|
||||||
|
|
||||||
|
If the user doesn't exist it is created first.
|
||||||
|
"""
|
||||||
|
password = random_lower_string()
|
||||||
|
user = crud.get_user_by_email(session=db, email=email)
|
||||||
|
if not user:
|
||||||
|
user_in_create = UserCreate(email=email, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in_create)
|
||||||
|
else:
|
||||||
|
user_in_update = UserUpdate(password=password)
|
||||||
|
if not user.id:
|
||||||
|
raise Exception("User id not set")
|
||||||
|
user = crud.update_user(session=db, db_user=user, user_in=user_in_update)
|
||||||
|
|
||||||
|
return user_authentication_headers(client=client, email=email, password=password)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import random
|
||||||
|
import string
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
def random_lower_string() -> str:
|
||||||
|
return "".join(random.choices(string.ascii_lowercase, k=32))
|
||||||
|
|
||||||
|
|
||||||
|
def random_email() -> str:
|
||||||
|
return f"{random_lower_string()}@{random_lower_string()}.com"
|
||||||
|
|
||||||
|
|
||||||
|
def get_superuser_token_headers(client: TestClient) -> dict[str, str]:
|
||||||
|
login_data = {
|
||||||
|
"username": settings.FIRST_SUPERUSER,
|
||||||
|
"password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
|
}
|
||||||
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
|
||||||
|
tokens = r.json()
|
||||||
|
a_token = tokens["access_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {a_token}"}
|
||||||
|
return headers
|
||||||
+8
-5
@@ -1,8 +1,10 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from sqlalchemy import Engine
|
||||||
|
from sqlmodel import Session, select
|
||||||
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
||||||
|
|
||||||
from app.db.session import db_session
|
from app.core.db import engine
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -17,18 +19,19 @@ wait_seconds = 1
|
|||||||
before=before_log(logger, logging.INFO),
|
before=before_log(logger, logging.INFO),
|
||||||
after=after_log(logger, logging.WARN),
|
after=after_log(logger, logging.WARN),
|
||||||
)
|
)
|
||||||
def init():
|
def init(db_engine: Engine) -> None:
|
||||||
try:
|
try:
|
||||||
# Try to create session to check if DB is awake
|
# Try to create session to check if DB is awake
|
||||||
db_session.execute("SELECT 1")
|
with Session(db_engine) as session:
|
||||||
|
session.exec(select(1))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
logger.info("Initializing service")
|
logger.info("Initializing service")
|
||||||
init()
|
init(engine)
|
||||||
logger.info("Service finished initializing")
|
logger.info("Service finished initializing")
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import logging
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import emails # type: ignore
|
||||||
|
from jinja2 import Template
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EmailData:
|
||||||
|
html_content: str
|
||||||
|
subject: str
|
||||||
|
|
||||||
|
|
||||||
|
def render_email_template(*, template_name: str, context: dict[str, Any]) -> str:
|
||||||
|
template_str = (
|
||||||
|
Path(__file__).parent / "email-templates" / "build" / template_name
|
||||||
|
).read_text()
|
||||||
|
html_content = Template(template_str).render(context)
|
||||||
|
return html_content
|
||||||
|
|
||||||
|
|
||||||
|
def send_email(
|
||||||
|
*,
|
||||||
|
email_to: str,
|
||||||
|
subject: str = "",
|
||||||
|
html_content: str = "",
|
||||||
|
) -> None:
|
||||||
|
assert settings.emails_enabled, "no provided configuration for email variables"
|
||||||
|
message = emails.Message(
|
||||||
|
subject=subject,
|
||||||
|
html=html_content,
|
||||||
|
mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
|
||||||
|
)
|
||||||
|
smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
|
||||||
|
if settings.SMTP_TLS:
|
||||||
|
smtp_options["tls"] = True
|
||||||
|
elif settings.SMTP_SSL:
|
||||||
|
smtp_options["ssl"] = True
|
||||||
|
if settings.SMTP_USER:
|
||||||
|
smtp_options["user"] = settings.SMTP_USER
|
||||||
|
if settings.SMTP_PASSWORD:
|
||||||
|
smtp_options["password"] = settings.SMTP_PASSWORD
|
||||||
|
response = message.send(to=email_to, smtp=smtp_options)
|
||||||
|
logging.info(f"send email result: {response}")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_test_email(email_to: str) -> EmailData:
|
||||||
|
project_name = settings.PROJECT_NAME
|
||||||
|
subject = f"{project_name} - Test email"
|
||||||
|
html_content = render_email_template(
|
||||||
|
template_name="test_email.html",
|
||||||
|
context={"project_name": settings.PROJECT_NAME, "email": email_to},
|
||||||
|
)
|
||||||
|
return EmailData(html_content=html_content, subject=subject)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData:
|
||||||
|
project_name = settings.PROJECT_NAME
|
||||||
|
subject = f"{project_name} - Password recovery for user {email}"
|
||||||
|
link = f"{settings.server_host}/reset-password?token={token}"
|
||||||
|
html_content = render_email_template(
|
||||||
|
template_name="reset_password.html",
|
||||||
|
context={
|
||||||
|
"project_name": settings.PROJECT_NAME,
|
||||||
|
"username": email,
|
||||||
|
"email": email_to,
|
||||||
|
"valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS,
|
||||||
|
"link": link,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return EmailData(html_content=html_content, subject=subject)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_new_account_email(
|
||||||
|
email_to: str, username: str, password: str
|
||||||
|
) -> EmailData:
|
||||||
|
project_name = settings.PROJECT_NAME
|
||||||
|
subject = f"{project_name} - New account for user {username}"
|
||||||
|
html_content = render_email_template(
|
||||||
|
template_name="new_account.html",
|
||||||
|
context={
|
||||||
|
"project_name": settings.PROJECT_NAME,
|
||||||
|
"username": username,
|
||||||
|
"password": password,
|
||||||
|
"email": email_to,
|
||||||
|
"link": settings.server_host,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return EmailData(html_content=html_content, subject=subject)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_password_reset_token(email: str) -> str:
|
||||||
|
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
|
||||||
|
now = datetime.utcnow()
|
||||||
|
expires = now + delta
|
||||||
|
exp = expires.timestamp()
|
||||||
|
encoded_jwt = jwt.encode(
|
||||||
|
{"exp": exp, "nbf": now, "sub": email},
|
||||||
|
settings.SECRET_KEY,
|
||||||
|
algorithm="HS256",
|
||||||
|
)
|
||||||
|
return encoded_jwt
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password_reset_token(token: str) -> str | None:
|
||||||
|
try:
|
||||||
|
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
||||||
|
return str(decoded_token["sub"])
|
||||||
|
except JWTError:
|
||||||
|
return None
|
||||||
Generated
+2257
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,75 @@
|
|||||||
|
[tool.poetry]
|
||||||
|
name = "app"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = ""
|
||||||
|
authors = ["Admin <admin@example.com>"]
|
||||||
|
|
||||||
|
[tool.poetry.dependencies]
|
||||||
|
python = "^3.10"
|
||||||
|
uvicorn = {extras = ["standard"], version = "^0.24.0.post1"}
|
||||||
|
fastapi = "^0.109.1"
|
||||||
|
python-multipart = "^0.0.7"
|
||||||
|
email-validator = "^2.1.0.post1"
|
||||||
|
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
|
||||||
|
tenacity = "^8.2.3"
|
||||||
|
pydantic = ">2.0"
|
||||||
|
emails = "^0.6"
|
||||||
|
|
||||||
|
gunicorn = "^21.2.0"
|
||||||
|
jinja2 = "^3.1.2"
|
||||||
|
alembic = "^1.12.1"
|
||||||
|
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
|
||||||
|
httpx = "^0.25.1"
|
||||||
|
psycopg = {extras = ["binary"], version = "^3.1.13"}
|
||||||
|
sqlmodel = "^0.0.16"
|
||||||
|
# Pin bcrypt until passlib supports the latest
|
||||||
|
bcrypt = "4.0.1"
|
||||||
|
pydantic-settings = "^2.2.1"
|
||||||
|
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
|
||||||
|
|
||||||
|
[tool.poetry.group.dev.dependencies]
|
||||||
|
pytest = "^7.4.3"
|
||||||
|
pytest-cov = "^4.1.0"
|
||||||
|
mypy = "^1.8.0"
|
||||||
|
ruff = "^0.2.2"
|
||||||
|
pre-commit = "^3.6.2"
|
||||||
|
pytest-mock = "^3.12.0"
|
||||||
|
types-python-jose = "^3.3.4.20240106"
|
||||||
|
types-passlib = "^1.7.7.20240106"
|
||||||
|
|
||||||
|
[tool.isort]
|
||||||
|
multi_line_output = 3
|
||||||
|
include_trailing_comma = true
|
||||||
|
force_grid_wrap = 0
|
||||||
|
line_length = 88
|
||||||
|
[build-system]
|
||||||
|
requires = ["poetry>=0.12"]
|
||||||
|
build-backend = "poetry.masonry.api"
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
strict = true
|
||||||
|
exclude = ["venv", "alembic"]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = [
|
||||||
|
"E", # pycodestyle errors
|
||||||
|
"W", # pycodestyle warnings
|
||||||
|
"F", # pyflakes
|
||||||
|
"I", # isort
|
||||||
|
"B", # flake8-bugbear
|
||||||
|
"C4", # flake8-comprehensions
|
||||||
|
"UP", # pyupgrade
|
||||||
|
]
|
||||||
|
ignore = [
|
||||||
|
"E501", # line too long, handled by black
|
||||||
|
"B008", # do not perform function calls in argument defaults
|
||||||
|
"W191", # indentation contains tabs
|
||||||
|
"B904", # Allow raising exceptions without from e, for HTTPException
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint.pyupgrade]
|
||||||
|
# Preserve types, even if a file imports `from __future__ import annotations`.
|
||||||
|
keep-runtime-typing = true
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh -e
|
||||||
|
set -x
|
||||||
|
|
||||||
|
# Sort imports one per line, so autoflake can remove unused imports
|
||||||
|
isort --recursive --force-single-line-imports --apply app
|
||||||
|
sh ./scripts/format.sh
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh -e
|
||||||
|
set -x
|
||||||
|
|
||||||
|
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place app --exclude=__init__.py
|
||||||
|
black app
|
||||||
|
isort --recursive --apply app
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
set -x
|
||||||
|
|
||||||
|
mypy app
|
||||||
|
ruff app
|
||||||
|
ruff format app --check
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
set -x
|
||||||
|
|
||||||
|
bash scripts/test.sh --cov-report=html "${@}"
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
set -x
|
||||||
|
|
||||||
|
coverage run --source=app -m pytest
|
||||||
|
coverage report --show-missing
|
||||||
|
coverage html --title "${@-coverage}"
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#! /usr/bin/env bash
|
#! /usr/bin/env bash
|
||||||
set -e
|
set -e
|
||||||
|
set -x
|
||||||
|
|
||||||
python /app/app/tests_pre_start.py
|
python /app/app/tests_pre_start.py
|
||||||
|
|
||||||
pytest /app/app/tests/
|
bash ./scripts/test.sh "$@"
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
{
|
|
||||||
"project_name": "Base Project",
|
|
||||||
"project_slug": "{{ cookiecutter.project_name|lower|replace(' ', '-') }}",
|
|
||||||
"domain_main": "{{cookiecutter.project_slug}}.com",
|
|
||||||
"domain_staging": "stag.{{cookiecutter.domain_main}}",
|
|
||||||
|
|
||||||
"docker_swarm_stack_name_main": "{{cookiecutter.domain_main|replace('.', '-')}}",
|
|
||||||
"docker_swarm_stack_name_staging": "{{cookiecutter.domain_staging|replace('.', '-')}}",
|
|
||||||
|
|
||||||
"secret_key": "changethis",
|
|
||||||
"first_superuser": "admin@{{cookiecutter.domain_main}}",
|
|
||||||
"first_superuser_password": "changethis",
|
|
||||||
"backend_cors_origins": "http://localhost, http://localhost:4200, http://localhost:3000, http://localhost:8080, https://localhost, https://localhost:4200, https://localhost:3000, https://localhost:8080, http://dev.{{cookiecutter.domain_main}}, https://{{cookiecutter.domain_staging}}, https://{{cookiecutter.domain_main}}, http://local.dockertoolbox.tiangolo.com, http://localhost.tiangolo.com",
|
|
||||||
"smtp_port": "587",
|
|
||||||
"smtp_host": "",
|
|
||||||
"smtp_user": "",
|
|
||||||
"smtp_password": "",
|
|
||||||
"smtp_emails_from_email": "info@{{cookiecutter.domain_main}}",
|
|
||||||
|
|
||||||
"postgres_password": "changethis",
|
|
||||||
"pgadmin_default_user": "{{cookiecutter.first_superuser}}",
|
|
||||||
"pgadmin_default_user_password": "{{cookiecutter.first_superuser_password}}",
|
|
||||||
|
|
||||||
"traefik_constraint_tag": "{{cookiecutter.domain_main}}",
|
|
||||||
"traefik_constraint_tag_staging": "{{cookiecutter.domain_staging}}",
|
|
||||||
"traefik_public_network": "traefik-public",
|
|
||||||
"traefik_public_constraint_tag": "traefik-public",
|
|
||||||
|
|
||||||
"flower_auth": "admin:{{cookiecutter.first_superuser_password}}",
|
|
||||||
|
|
||||||
"sentry_dsn": "",
|
|
||||||
|
|
||||||
"docker_image_prefix": "",
|
|
||||||
|
|
||||||
"docker_image_backend": "{{cookiecutter.docker_image_prefix}}backend",
|
|
||||||
"docker_image_celeryworker": "{{cookiecutter.docker_image_prefix}}celeryworker",
|
|
||||||
"docker_image_frontend": "{{cookiecutter.docker_image_prefix}}frontend",
|
|
||||||
|
|
||||||
"_copy_without_render": [
|
|
||||||
"frontend/src/**/*.html",
|
|
||||||
"frontend/src/**/*.vue",
|
|
||||||
"frontend/node_modules/*",
|
|
||||||
"backend/app/app/email-templates/**"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
project_name:
|
||||||
|
type: str
|
||||||
|
help: The name of the project, shown to API users (in .env)
|
||||||
|
default: FastAPI Project
|
||||||
|
|
||||||
|
stack_name:
|
||||||
|
type: str
|
||||||
|
help: The name of the stack used for Docker Compose labels (no spaces) (in .env)
|
||||||
|
default: fastapi-project
|
||||||
|
|
||||||
|
secret_key:
|
||||||
|
type: str
|
||||||
|
help: |
|
||||||
|
'The secret key for the project, used for security,
|
||||||
|
stored in .env, you can generate one with:
|
||||||
|
python -c "import secrets; print(secrets.token_urlsafe(32))"'
|
||||||
|
default: changethis
|
||||||
|
|
||||||
|
first_superuser:
|
||||||
|
type: str
|
||||||
|
help: The email of the first superuser (in .env)
|
||||||
|
default: admin@example.com
|
||||||
|
|
||||||
|
first_superuser_password:
|
||||||
|
type: str
|
||||||
|
help: The password of the first superuser (in .env)
|
||||||
|
default: changethis
|
||||||
|
|
||||||
|
smtp_host:
|
||||||
|
type: str
|
||||||
|
help: The SMTP server host to send emails, you can set it later in .env
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
smtp_user:
|
||||||
|
type: str
|
||||||
|
help: The SMTP server user to send emails, you can set it later in .env
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
smtp_password:
|
||||||
|
type: str
|
||||||
|
help: The SMTP server password to send emails, you can set it later in .env
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
emails_from_email:
|
||||||
|
type: str
|
||||||
|
help: The email account to send emails from, you can set it later in .env
|
||||||
|
default: info@example.com
|
||||||
|
|
||||||
|
postgres_password:
|
||||||
|
type: str
|
||||||
|
help: |
|
||||||
|
'The password for the PostgreSQL database, stored in .env,
|
||||||
|
you can generate one with:
|
||||||
|
python -c "import secrets; print(secrets.token_urlsafe(32))"'
|
||||||
|
default: changethis
|
||||||
|
|
||||||
|
sentry_dsn:
|
||||||
|
type: str
|
||||||
|
help: The DSN for Sentry, if you are using it, you can set it later in .env
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
_exclude:
|
||||||
|
# Global
|
||||||
|
- .vscode
|
||||||
|
- .mypy_cache
|
||||||
|
- poetry.lock
|
||||||
|
# Python
|
||||||
|
- __pycache__
|
||||||
|
- app.egg-info
|
||||||
|
- "*.pyc"
|
||||||
|
- .mypy_cache
|
||||||
|
- .coverage
|
||||||
|
- htmlcov
|
||||||
|
- poetry.lock
|
||||||
|
- .cache
|
||||||
|
- .venv
|
||||||
|
# Frontend
|
||||||
|
# Logs
|
||||||
|
- logs
|
||||||
|
- "*.log"
|
||||||
|
- npm-debug.log*
|
||||||
|
- yarn-debug.log*
|
||||||
|
- yarn-error.log*
|
||||||
|
- pnpm-debug.log*
|
||||||
|
- lerna-debug.log*
|
||||||
|
- node_modules
|
||||||
|
- dist
|
||||||
|
- dist-ssr
|
||||||
|
- "*.local"
|
||||||
|
# Editor directories and files
|
||||||
|
- .idea
|
||||||
|
- .DS_Store
|
||||||
|
- "*.suo"
|
||||||
|
- "*.ntvs*"
|
||||||
|
- "*.njsproj"
|
||||||
|
- "*.sln"
|
||||||
|
- "*.sw?"
|
||||||
|
|
||||||
|
_answers_file: .copier/.copier-answers.yml
|
||||||
|
|
||||||
|
_tasks:
|
||||||
|
- "python .copier/update_dotenv.py"
|
||||||
+291
@@ -0,0 +1,291 @@
|
|||||||
|
# FastAPI Project - Deployment
|
||||||
|
|
||||||
|
You can deploy the project using Docker Compose to a remote server.
|
||||||
|
|
||||||
|
This project expects you to have a Traefik proxy handling communication to the outside world and HTTPS certificates.
|
||||||
|
|
||||||
|
You can use CI/CD (continuous integration and continuous deployment) systems to deploy automatically, there are already configurations to do it with GitHub Actions.
|
||||||
|
|
||||||
|
But you have to configure a couple things first. 🤓
|
||||||
|
|
||||||
|
## Preparation
|
||||||
|
|
||||||
|
* Have a remote server ready and available.
|
||||||
|
* Configure the DNS records of your domain to point to the IP of the server you just created.
|
||||||
|
* Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `staging.fastapi-project.example.com`, `staging.adminer.fastapi-project.example.com`, etc.
|
||||||
|
* Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop).
|
||||||
|
|
||||||
|
## Public Traefik
|
||||||
|
|
||||||
|
We need a Traefik proxy to handle incoming connections and HTTPS certificates.
|
||||||
|
|
||||||
|
You need to do these next steps only once.
|
||||||
|
|
||||||
|
### Traefik Docker Compose
|
||||||
|
|
||||||
|
* Create a remote directory to store your Traefik Docker Compose file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p /root/code/traefik-public/
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy the Traefik Docker Compose file to your server. You could do it by running the command `rsync` in your local terminal:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rsync -a docker-compose.traefik.yml root@your-server.example.com:/root/code/traefik-public/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Traefik Public Network
|
||||||
|
|
||||||
|
This Traefik will expect a Docker "public network" named `traefik-public` to communicate with your stack(s).
|
||||||
|
|
||||||
|
This way, there will be a single public Traefik proxy that handles the communication (HTTP and HTTPS) with the outside world, and then behind that, you could have one or more stacks with different domains, even if they are on the same single server.
|
||||||
|
|
||||||
|
To create a Docker "public network" named `traefik-public` run the following command in your remote server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network create traefik-public
|
||||||
|
```
|
||||||
|
|
||||||
|
### Traefik Environment Variables
|
||||||
|
|
||||||
|
The Traefik Docker Compose file expects some environment variables to be set in your terminal before starting it. You can do it by running the following commands in your remote server.
|
||||||
|
|
||||||
|
* Create the username for HTTP Basic Auth, e.g.:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export USERNAME=admin
|
||||||
|
```
|
||||||
|
|
||||||
|
* Create an environment variable with the password for HTTP Basic Auth, e.g.:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export PASSWORD=changethis
|
||||||
|
```
|
||||||
|
|
||||||
|
* Use openssl to generate the "hashed" version of the password for HTTP Basic Auth and store it in an environment variable:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export HASHED_PASSWORD=$(openssl passwd -apr1 $PASSWORD)
|
||||||
|
```
|
||||||
|
|
||||||
|
To verify that the hashed password is correct, you can print it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
echo $HASHED_PASSWORD
|
||||||
|
```
|
||||||
|
|
||||||
|
* Create an environment variable with the domain name for your server, e.g.:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export DOMAIN=fastapi-project.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
* Create an environment variable with the email for Let's Encrypt, e.g.:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export EMAIL=admin@example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: you need to set a different email, an email `@example.com` won't work.
|
||||||
|
|
||||||
|
### Start the Traefik Docker Compose
|
||||||
|
|
||||||
|
Go to the directory where you copied the Traefik Docker Compose file in your remote server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/code/traefik-public/
|
||||||
|
```
|
||||||
|
|
||||||
|
Now with the environment variables set and the `docker-compose.traefik.yml` in place, you can start the Traefik Docker Compose running the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.traefik.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy the FastAPI Project
|
||||||
|
|
||||||
|
Now that you have Traefik in place you can deploy your FastAPI project with Docker Compose.
|
||||||
|
|
||||||
|
**Note**: You might want to jump ahead to the section about Continuous Deployment with GitHub Actions.
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
You need to set some environment variables first.
|
||||||
|
|
||||||
|
Set the `ENVIRONMENT`, by default `local` (for development), but when deploying to a server you would put something like `staging` or `production`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export ENVIRONMENT=production
|
||||||
|
```
|
||||||
|
|
||||||
|
Set the `DOMAIN`, by default `localhost` (for development), but when deploying you would use your own domain, for example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export DOMAIN=fastapi-project.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
You can set several variables, like:
|
||||||
|
|
||||||
|
* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
|
||||||
|
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
|
||||||
|
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
|
||||||
|
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
|
||||||
|
* `USERS_OPEN_REGISTRATION`: Whether to allow open registration of new users.
|
||||||
|
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
|
||||||
|
* `SMTP_USER`: The SMTP server user to send emails.
|
||||||
|
* `SMTP_PASSWORD`: The SMTP server password to send emails.
|
||||||
|
* `EMAILS_FROM_EMAIL`: The email account to send emails from.
|
||||||
|
* `POSTGRES_SERVER`: The hostname of the PostgreSQL server. You can leave the default of `db`, provided by the same Docker Compose. You normally wouldn't need to change this unless you are using a third-party provider.
|
||||||
|
* `POSTGRES_PORT`: The port of the PostgreSQL server. You can leave the default. You normally wouldn't need to change this unless you are using a third-party provider.
|
||||||
|
* `POSTGRES_PASSWORD`: The Postgres password.
|
||||||
|
* `POSTGRES_USER`: The Postgres user, you can leave the default.
|
||||||
|
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
|
||||||
|
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
|
||||||
|
|
||||||
|
### Generate secret keys
|
||||||
|
|
||||||
|
Some environment variables in the `.env` file have a default value of `changethis`.
|
||||||
|
|
||||||
|
You have to change them with a secret key, to generate secret keys you can run the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -c "import secrets; print(secrets.token_urlsafe(32))"
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy the content and use that as password / secret key. And run that again to generate another secure key.
|
||||||
|
|
||||||
|
### Deploy with Docker Compose
|
||||||
|
|
||||||
|
With the environment variables in place, you can deploy with Docker Compose:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
For production you wouldn't want to have the overrides in `docker-compose.override.yml`, that's why we explicitly specify `docker-compose.yml` as the file to use.
|
||||||
|
|
||||||
|
## Continuous Deployment (CD)
|
||||||
|
|
||||||
|
You can use GitHub Actions to deploy your project automatically. 😎
|
||||||
|
|
||||||
|
You can have multiple environment deployments.
|
||||||
|
|
||||||
|
There are already two environments configured, `staging` and `production`. 🚀
|
||||||
|
|
||||||
|
### Install GitHub Actions Runner
|
||||||
|
|
||||||
|
* On your remote server, if you are running as the `root` user, create a user for your GitHub Actions:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
adduser github
|
||||||
|
```
|
||||||
|
|
||||||
|
* Add Docker permissions to the `github` user:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
usermod -aG docker github
|
||||||
|
```
|
||||||
|
|
||||||
|
* Temporarily switch to the `github` user:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
su - github
|
||||||
|
```
|
||||||
|
|
||||||
|
* Go to the `github` user's home directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd
|
||||||
|
```
|
||||||
|
|
||||||
|
* [Install a GitHub Action self-hosted runner following the official guide](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners#adding-a-self-hosted-runner-to-a-repository).
|
||||||
|
|
||||||
|
* When asked about labels, add a label for the environment, e.g. `production`. You can also add labels later.
|
||||||
|
|
||||||
|
After installing, the guide would tell you to run a command to start the runner. Nevertheless, it would stop once you terminate that process or if your local connection to your server is lost.
|
||||||
|
|
||||||
|
To make sure it runs on startup and continues running, you can install it as a service. To do that, exit the `github` user and go back to the `root` user:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
exit
|
||||||
|
```
|
||||||
|
|
||||||
|
After you do it, you would be on the `root` user again. And you will be on the previous directory, belonging to the `root` user.
|
||||||
|
|
||||||
|
* Go to the `actions-runner` directory inside of the `github` user's home directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/github/actions-runner
|
||||||
|
```
|
||||||
|
|
||||||
|
* Install the self-hosted runner as a service with the user `github`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./svc.sh install github
|
||||||
|
```
|
||||||
|
|
||||||
|
* Start the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./svc.sh start
|
||||||
|
```
|
||||||
|
|
||||||
|
* Check the status of the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./svc.sh status
|
||||||
|
```
|
||||||
|
|
||||||
|
You can read more about it in the official guide: [Configuring the self-hosted runner application as a service](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service).
|
||||||
|
|
||||||
|
### Set Secrets
|
||||||
|
|
||||||
|
On your repository, configure secrets for the environment variables you need, the same ones described above, including `SECRET_KEY`, etc. Follow the [official GitHub guide for setting repository secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository).
|
||||||
|
|
||||||
|
The current Github Actions workflows expect these secrets:
|
||||||
|
|
||||||
|
* `DOMAIN_PRODUCTION`
|
||||||
|
* `DOMAIN_STAGING`
|
||||||
|
* `EMAILS_FROM_EMAIL`
|
||||||
|
* `FIRST_SUPERUSER`
|
||||||
|
* `FIRST_SUPERUSER_PASSWORD`
|
||||||
|
* `POSTGRES_PASSWORD`
|
||||||
|
* `SECRET_KEY`
|
||||||
|
|
||||||
|
## GitHub Action Deployment Workflows
|
||||||
|
|
||||||
|
There are GitHub Action workflows in the `.github/workflows` directory already configured for deploying to the environments (GitHub Actions runners with the labels):
|
||||||
|
|
||||||
|
* `staging`: after pushing (or merging) to the branch `master`.
|
||||||
|
* `production`: after publishing a release.
|
||||||
|
|
||||||
|
If you need to add extra environments you could use those as a starting point.
|
||||||
|
|
||||||
|
## URLs
|
||||||
|
|
||||||
|
Replace `fastapi-project.example.com` with your domain.
|
||||||
|
|
||||||
|
### Main Traefik Dashboard
|
||||||
|
|
||||||
|
Traefik UI: `https://traefik.fastapi-project.example.com`
|
||||||
|
|
||||||
|
### Production
|
||||||
|
|
||||||
|
Frontend: `https://fastapi-project.example.com`
|
||||||
|
|
||||||
|
Backend API docs: `https://fastapi-project.example.com/docs`
|
||||||
|
|
||||||
|
Backend API base URL: `https://fastapi-project.example.com/api/`
|
||||||
|
|
||||||
|
Adminer: `https://adminer.fastapi-project.example.com`
|
||||||
|
|
||||||
|
### Staging
|
||||||
|
|
||||||
|
Frontend: `https://staging.fastapi-project.example.com`
|
||||||
|
|
||||||
|
Backend API docs: `https://staging.fastapi-project.example.com/docs`
|
||||||
|
|
||||||
|
Backend API base URL: `https://staging.fastapi-project.example.com/api/`
|
||||||
|
|
||||||
|
Adminer: `https://staging.adminer.fastapi-project.example.com`
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
#! /usr/bin/env bash
|
|
||||||
|
|
||||||
# Run this script from outside the project, to integrate a dev-fsfp project with changes and review modifications
|
|
||||||
|
|
||||||
# Exit in case of error
|
|
||||||
set -e
|
|
||||||
|
|
||||||
if [ $(uname -s) = "Linux" ]; then
|
|
||||||
echo "Remove __pycache__ files"
|
|
||||||
sudo find ./dev-fsfp/ -type d -name __pycache__ -exec rm -r {} \+
|
|
||||||
fi
|
|
||||||
|
|
||||||
rm -rf ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/*
|
|
||||||
|
|
||||||
rsync -a --exclude=node_modules ./dev-fsfp/* ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/
|
|
||||||
|
|
||||||
rsync -a ./dev-fsfp/{.env,.gitignore,.gitlab-ci.yml} ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
default_context:
|
|
||||||
"project_name": "Dev FSFP"
|
|
||||||
-10
@@ -1,10 +0,0 @@
|
|||||||
#! /usr/bin/env bash
|
|
||||||
|
|
||||||
# Run this script from outside the project, to generate a dev-fsfp project
|
|
||||||
|
|
||||||
# Exit in case of error
|
|
||||||
set -e
|
|
||||||
|
|
||||||
rm -rf ./dev-fsfp
|
|
||||||
|
|
||||||
cookiecutter --config-file ./full-stack-fastapi-postgresql/dev-fsfp-config.yml --no-input -f ./full-stack-fastapi-postgresql
|
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
# FastAPI Project - Development
|
||||||
|
|
||||||
|
## Development in `localhost` with a custom domain
|
||||||
|
|
||||||
|
You might want to use something different than `localhost` as the domain. For example, if you are having problems with cookies that need a subdomain, and Chrome is not allowing you to use `localhost`.
|
||||||
|
|
||||||
|
In that case, you have two options: you could use the instructions to modify your system `hosts` file with the instructions below in **Development with a custom IP** or you can just use `localhost.tiangolo.com`, it is set up to point to `localhost` (to the IP `127.0.0.1`) and all its subdomains too. And as it is an actual domain, the browsers will store the cookies you set during development, etc.
|
||||||
|
|
||||||
|
If you used the default CORS enabled domains while generating the project, `localhost.tiangolo.com` was configured to be allowed. If you didn't, you will need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
|
||||||
|
|
||||||
|
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `localhost.tiangolo.com`.
|
||||||
|
|
||||||
|
After performing those steps you should be able to open: http://localhost.tiangolo.com and it will be served by your stack in `localhost`.
|
||||||
|
|
||||||
|
Check all the corresponding available URLs in the section at the end.
|
||||||
|
|
||||||
|
## Development with a custom IP
|
||||||
|
|
||||||
|
If you are running Docker in an IP address different than `127.0.0.1` (`localhost`), you will need to perform some additional steps. That will be the case if you are running a custom Virtual Machine or your Docker is located in a different machine in your network.
|
||||||
|
|
||||||
|
In that case, you will need to use a fake local domain (`dev.example.com`) and make your computer think that the domain is served by the custom IP (e.g. `192.168.99.150`).
|
||||||
|
|
||||||
|
If you have a custom domain like that, you need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
|
||||||
|
|
||||||
|
* Open your `hosts` file with administrative privileges using a text editor:
|
||||||
|
* **Note for Windows**: If you are in Windows, open the main Windows menu, search for "notepad", right click on it, and select the option "open as Administrator" or similar. Then click the "File" menu, "Open file", go to the directory `c:\Windows\System32\Drivers\etc\`, select the option to show "All files" instead of only "Text (.txt) files", and open the `hosts` file.
|
||||||
|
* **Note for Mac and Linux**: Your `hosts` file is probably located at `/etc/hosts`, you can edit it in a terminal running `sudo nano /etc/hosts`.
|
||||||
|
|
||||||
|
* Additional to the contents it might have, add a new line with the custom IP (e.g. `192.168.99.150`) a space character, and your fake local domain: `dev.example.com`.
|
||||||
|
|
||||||
|
The new line might look like:
|
||||||
|
|
||||||
|
```
|
||||||
|
192.168.99.150 dev.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
* Save the file.
|
||||||
|
* **Note for Windows**: Make sure you save the file as "All files", without an extension of `.txt`. By default, Windows tries to add the extension. Make sure the file is saved as is, without extension.
|
||||||
|
|
||||||
|
...that will make your computer think that the fake local domain is served by that custom IP, and when you open that URL in your browser, it will talk directly to your locally running server when it is asked to go to `dev.example.com` and think that it is a remote server while it is actually running in your computer.
|
||||||
|
|
||||||
|
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `dev.example.com`.
|
||||||
|
|
||||||
|
After performing those steps you should be able to open: http://dev.example.com and it will be server by your stack in `192.168.99.150`.
|
||||||
|
|
||||||
|
Check all the corresponding available URLs in the section at the end.
|
||||||
|
|
||||||
|
## Change the development "domain"
|
||||||
|
|
||||||
|
If you need to use your local stack with a different domain than `localhost`, you need to make sure the domain you use points to the IP where your stack is set up.
|
||||||
|
|
||||||
|
To simplify your Docker Compose setup, for example, so that the API docs (Swagger UI) knows where is your API, you should let it know you are using that domain for development.
|
||||||
|
|
||||||
|
* Open the file located at `./.env`. It would have a line like:
|
||||||
|
|
||||||
|
```
|
||||||
|
DOMAIN=localhost
|
||||||
|
```
|
||||||
|
|
||||||
|
* Change it to the domain you are going to use, e.g.:
|
||||||
|
|
||||||
|
```
|
||||||
|
DOMAIN=localhost.tiangolo.com
|
||||||
|
```
|
||||||
|
|
||||||
|
That variable will be used by the Docker Compose files.
|
||||||
|
|
||||||
|
After that, you can restart your stack with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
and check all the corresponding available URLs in the section at the end.
|
||||||
|
|
||||||
|
## Docker Compose files and env vars
|
||||||
|
|
||||||
|
There is a main `docker-compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`.
|
||||||
|
|
||||||
|
And there's also a `docker-compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `docker-compose.yml`.
|
||||||
|
|
||||||
|
These Docker Compose files use the `.env` file containing configurations to be injected as environment variables in the containers.
|
||||||
|
|
||||||
|
They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command.
|
||||||
|
|
||||||
|
## The .env file
|
||||||
|
|
||||||
|
The `.env` file is the one that contains all your configurations, generated keys and passwords, etc.
|
||||||
|
|
||||||
|
Depending on your workflow, you could want to exclude it from Git, for example if your project is public. In that case, you would have to make sure to set up a way for your CI tools to obtain it while building or deploying your project.
|
||||||
|
|
||||||
|
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
|
||||||
|
|
||||||
|
## URLs
|
||||||
|
|
||||||
|
The production or staging URLs would use these same paths, but with your own domain.
|
||||||
|
|
||||||
|
### Development URLs
|
||||||
|
|
||||||
|
Development URLs, for local development.
|
||||||
|
|
||||||
|
Frontend: http://localhost
|
||||||
|
|
||||||
|
Backend: http://localhost/api/
|
||||||
|
|
||||||
|
Automatic Interactive Docs (Swagger UI): https://localhost/docs
|
||||||
|
|
||||||
|
Automatic Alternative Docs (ReDoc): https://localhost/redoc
|
||||||
|
|
||||||
|
Adminer: http://localhost:8080
|
||||||
|
|
||||||
|
Traefik UI: http://localhost:8090
|
||||||
|
|
||||||
|
### Development in localhost with a custom domain URLs
|
||||||
|
|
||||||
|
Development URLs, for local development.
|
||||||
|
|
||||||
|
Frontend: http://localhost.tiangolo.com
|
||||||
|
|
||||||
|
Backend: http://localhost.tiangolo.com/api/
|
||||||
|
|
||||||
|
Automatic Interactive Docs (Swagger UI): https://localhost.tiangolo.com/docs
|
||||||
|
|
||||||
|
Automatic Alternative Docs (ReDoc): https://localhost.tiangolo.com/redoc
|
||||||
|
|
||||||
|
Adminer: http://localhost.tiangolo.com:8080
|
||||||
|
|
||||||
|
Traefik UI: http://localhost.tiangolo.com:8090
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
version: "3.3"
|
||||||
|
services:
|
||||||
|
|
||||||
|
proxy:
|
||||||
|
image: traefik:v2.3
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "8090:8080"
|
||||||
|
# Duplicate the command from docker-compose.yml to add --api.insecure=true
|
||||||
|
command:
|
||||||
|
# Enable Docker in Traefik, so that it reads labels from Docker services
|
||||||
|
- --providers.docker
|
||||||
|
# Add a constraint to only use services with the label for this stack
|
||||||
|
- --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`)
|
||||||
|
# Do not expose all Docker services, only the ones explicitly exposed
|
||||||
|
- --providers.docker.exposedbydefault=false
|
||||||
|
# Create an entrypoint "http" listening on port 80
|
||||||
|
- --entrypoints.http.address=:80
|
||||||
|
# Create an entrypoint "https" listening on port 443
|
||||||
|
- --entrypoints.https.address=:443
|
||||||
|
# Enable the access log, with HTTP requests
|
||||||
|
- --accesslog
|
||||||
|
# Enable the Traefik log, for configurations and errors
|
||||||
|
- --log
|
||||||
|
# Enable debug logging for local development
|
||||||
|
- --log.level=DEBUG
|
||||||
|
# Enable the Dashboard and API
|
||||||
|
- --api
|
||||||
|
# Enable the Dashboard and API in insecure mode for local development
|
||||||
|
- --api.insecure=true
|
||||||
|
labels:
|
||||||
|
# Enable Traefik for this service, to make it available in the public network
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.constraint-label=traefik-public
|
||||||
|
# Dummy https-redirect middleware that doesn't really redirect, only to
|
||||||
|
# allow running it locally
|
||||||
|
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false
|
||||||
|
|
||||||
|
db:
|
||||||
|
restart: "no"
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
|
||||||
|
adminer:
|
||||||
|
restart: "no"
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
|
||||||
|
backend:
|
||||||
|
restart: "no"
|
||||||
|
ports:
|
||||||
|
- "8888:8888"
|
||||||
|
volumes:
|
||||||
|
- ./backend/:/app
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
args:
|
||||||
|
INSTALL_DEV: ${INSTALL_DEV-true}
|
||||||
|
# command: sleep infinity # Infinite loop to keep container alive doing nothing
|
||||||
|
command: /start-reload.sh
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
restart: "no"
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
- VITE_API_URL=http://${DOMAIN?Variable not set}
|
||||||
|
- NODE_ENV=development
|
||||||
|
|
||||||
|
networks:
|
||||||
|
traefik-public:
|
||||||
|
# For local dev, don't expect an external Traefik network
|
||||||
|
external: false
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
services:
|
||||||
|
traefik:
|
||||||
|
image: traefik:v2.3
|
||||||
|
ports:
|
||||||
|
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS
|
||||||
|
- 80:80
|
||||||
|
# Listen on port 443, default for HTTPS
|
||||||
|
- 443:443
|
||||||
|
restart: always
|
||||||
|
labels:
|
||||||
|
# Enable Traefik for this service, to make it available in the public network
|
||||||
|
- traefik.enable=true
|
||||||
|
# Use the traefik-public network (declared below)
|
||||||
|
- traefik.docker.network=traefik-public
|
||||||
|
# Define the port inside of the Docker service to use
|
||||||
|
- traefik.http.services.traefik-dashboard.loadbalancer.server.port=8080
|
||||||
|
# Make Traefik use this domain (from an environment variable) in HTTP
|
||||||
|
- traefik.http.routers.traefik-dashboard-http.entrypoints=http
|
||||||
|
- traefik.http.routers.traefik-dashboard-http.rule=Host(`traefik.${DOMAIN?Variable not set}`)
|
||||||
|
# traefik-https the actual router using HTTPS
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.entrypoints=https
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.rule=Host(`traefik.${DOMAIN?Variable not set}`)
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.tls=true
|
||||||
|
# Use the "le" (Let's Encrypt) resolver created below
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.tls.certresolver=le
|
||||||
|
# Use the special Traefik service api@internal with the web UI/Dashboard
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.service=api@internal
|
||||||
|
# https-redirect middleware to redirect HTTP to HTTPS
|
||||||
|
- traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
|
||||||
|
- traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
|
||||||
|
# traefik-http set up only to use the middleware to redirect to https
|
||||||
|
- traefik.http.routers.traefik-dashboard-http.middlewares=https-redirect
|
||||||
|
# admin-auth middleware with HTTP Basic auth
|
||||||
|
# Using the environment variables USERNAME and HASHED_PASSWORD
|
||||||
|
- traefik.http.middlewares.admin-auth.basicauth.users=${USERNAME?Variable not set}:${HASHED_PASSWORD?Variable not set}
|
||||||
|
# Enable HTTP Basic auth, using the middleware created above
|
||||||
|
- traefik.http.routers.traefik-dashboard-https.middlewares=admin-auth
|
||||||
|
volumes:
|
||||||
|
# Add Docker as a mounted volume, so that Traefik can read the labels of other services
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
# Mount the volume to store the certificates
|
||||||
|
- traefik-public-certificates:/certificates
|
||||||
|
command:
|
||||||
|
# Enable Docker in Traefik, so that it reads labels from Docker services
|
||||||
|
- --providers.docker
|
||||||
|
# Do not expose all Docker services, only the ones explicitly exposed
|
||||||
|
- --providers.docker.exposedbydefault=false
|
||||||
|
# Create an entrypoint "http" listening on port 80
|
||||||
|
- --entrypoints.http.address=:80
|
||||||
|
# Create an entrypoint "https" listening on port 443
|
||||||
|
- --entrypoints.https.address=:443
|
||||||
|
# Create the certificate resolver "le" for Let's Encrypt, uses the environment variable EMAIL
|
||||||
|
- --certificatesresolvers.le.acme.email=${EMAIL?Variable not set}
|
||||||
|
# Store the Let's Encrypt certificates in the mounted volume
|
||||||
|
- --certificatesresolvers.le.acme.storage=/certificates/acme.json
|
||||||
|
# Use the TLS Challenge for Let's Encrypt
|
||||||
|
- --certificatesresolvers.le.acme.tlschallenge=true
|
||||||
|
# Enable the access log, with HTTP requests
|
||||||
|
- --accesslog
|
||||||
|
# Enable the Traefik log, for configurations and errors
|
||||||
|
- --log
|
||||||
|
# Enable the Dashboard and API
|
||||||
|
- --api
|
||||||
|
networks:
|
||||||
|
# Use the public network created to be shared between Traefik and
|
||||||
|
# any other service that needs to be publicly available with HTTPS
|
||||||
|
- traefik-public
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
# Create a volume to store the certificates, even if the container is recreated
|
||||||
|
traefik-public-certificates:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
# Use the previously created public network "traefik-public", shared with other
|
||||||
|
# services that need to be publicly available via this Traefik
|
||||||
|
traefik-public:
|
||||||
|
external: true
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
version: "3.3"
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:12
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- app-db-data:/var/lib/postgresql/data/pgdata
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
environment:
|
||||||
|
- PGDATA=/var/lib/postgresql/data/pgdata
|
||||||
|
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
|
||||||
|
- POSTGRES_USER=${POSTGRES_USER?Variable not set}
|
||||||
|
- POSTGRES_DB=${POSTGRES_DB?Variable not set}
|
||||||
|
|
||||||
|
adminer:
|
||||||
|
image: adminer
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- traefik-public
|
||||||
|
- default
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
|
environment:
|
||||||
|
- ADMINER_DESIGN=pepa-linha-dark
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=traefik-public
|
||||||
|
- traefik.constraint-label=traefik-public
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.rule=Host(`adminer.${DOMAIN?Variable not set}`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.entrypoints=http
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.middlewares=https-redirect
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.rule=Host(`adminer.${DOMAIN?Variable not set}`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.entrypoints=https
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls=true
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le
|
||||||
|
- traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080
|
||||||
|
|
||||||
|
backend:
|
||||||
|
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- traefik-public
|
||||||
|
- default
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
environment:
|
||||||
|
- DOMAIN=${DOMAIN}
|
||||||
|
- ENVIRONMENT=${ENVIRONMENT}
|
||||||
|
- BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS}
|
||||||
|
- SECRET_KEY=${SECRET_KEY?Variable not set}
|
||||||
|
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
|
||||||
|
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
|
||||||
|
- USERS_OPEN_REGISTRATION=${USERS_OPEN_REGISTRATION}
|
||||||
|
- SMTP_HOST=${SMTP_HOST}
|
||||||
|
- SMTP_USER=${SMTP_USER}
|
||||||
|
- SMTP_PASSWORD=${SMTP_PASSWORD}
|
||||||
|
- EMAILS_FROM_EMAIL=${EMAILS_FROM_EMAIL}
|
||||||
|
- POSTGRES_SERVER=db
|
||||||
|
- POSTGRES_PORT=${POSTGRES_PORT}
|
||||||
|
- POSTGRES_DB=${POSTGRES_DB}
|
||||||
|
- POSTGRES_USER=${POSTGRES_USER?Variable not set}
|
||||||
|
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
|
||||||
|
- SENTRY_DSN=${SENTRY_DSN}
|
||||||
|
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
args:
|
||||||
|
INSTALL_DEV: ${INSTALL_DEV-false}
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=traefik-public
|
||||||
|
- traefik.constraint-label=traefik-public
|
||||||
|
|
||||||
|
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
|
||||||
|
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http
|
||||||
|
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
|
||||||
|
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}'
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- traefik-public
|
||||||
|
- default
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
- VITE_API_URL=https://${DOMAIN?Variable not set}
|
||||||
|
- NODE_ENV=production
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=traefik-public
|
||||||
|
- traefik.constraint-label=traefik-public
|
||||||
|
|
||||||
|
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
|
||||||
|
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http
|
||||||
|
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
|
||||||
|
|
||||||
|
# Handle domain with and without "www" to redirect to only one
|
||||||
|
# To disable www redirection remove the next line
|
||||||
|
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.regex=^http(s)?://www.(${DOMAIN?Variable not set})/(.*)
|
||||||
|
# Redirect a domain with www to non-www
|
||||||
|
# To disable it remove the next line
|
||||||
|
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
|
||||||
|
# Middleware to redirect www, to disable it remove the next line
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
||||||
|
# Middleware to redirect www, and redirect HTTP to HTTPS
|
||||||
|
# to disable www redirection remove the section: ${STACK_NAME?Variable not set}-www-redirect,
|
||||||
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
||||||
|
volumes:
|
||||||
|
app-db-data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
traefik-public:
|
||||||
|
# Allow setting it to false for testing
|
||||||
|
external: true
|
||||||
Executable → Regular
+1
@@ -1 +1,2 @@
|
|||||||
node_modules
|
node_modules
|
||||||
|
dist
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_API_URL=http://localhost
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
module.exports = {
|
||||||
|
root: true,
|
||||||
|
env: { browser: true, es2020: true },
|
||||||
|
extends: [
|
||||||
|
'eslint:recommended',
|
||||||
|
'plugin:@typescript-eslint/recommended',
|
||||||
|
'plugin:react-hooks/recommended',
|
||||||
|
],
|
||||||
|
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
plugins: ['react-refresh'],
|
||||||
|
rules: {
|
||||||
|
'react-refresh/only-export-components': [
|
||||||
|
'warn',
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -1,21 +1,25 @@
|
|||||||
.DS_Store
|
# Logs
|
||||||
node_modules
|
logs
|
||||||
/dist
|
*.log
|
||||||
|
|
||||||
# local env files
|
|
||||||
.env.local
|
|
||||||
.env.*.local
|
|
||||||
|
|
||||||
# Log files
|
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
openapi.json
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
.idea
|
.idea
|
||||||
.vscode
|
.DS_Store
|
||||||
*.suo
|
*.suo
|
||||||
*.ntvs*
|
*.ntvs*
|
||||||
*.njsproj
|
*.njsproj
|
||||||
*.sln
|
*.sln
|
||||||
*.sw*
|
*.sw?
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
18.x.x
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
src/client/
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
|
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
|
||||||
FROM tiangolo/node-frontend:10 as build-stage
|
FROM node:20 as build-stage
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -9,19 +9,15 @@ RUN npm install
|
|||||||
|
|
||||||
COPY ./ /app/
|
COPY ./ /app/
|
||||||
|
|
||||||
ARG FRONTEND_ENV=production
|
ARG VITE_API_URL=${VITE_API_URL}
|
||||||
|
|
||||||
ENV VUE_APP_ENV=${FRONTEND_ENV}
|
|
||||||
|
|
||||||
# Comment out the next line to disable tests
|
|
||||||
RUN npm run test:unit
|
|
||||||
|
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
|
|
||||||
# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
|
# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
|
||||||
FROM nginx:1.15
|
FROM nginx:1
|
||||||
|
|
||||||
COPY --from=build-stage /app/dist/ /usr/share/nginx/html
|
COPY --from=build-stage /app/dist/ /usr/share/nginx/html
|
||||||
|
|
||||||
COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.conf
|
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY ./nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# FastAPI Project - Frontend
|
||||||
|
|
||||||
|
The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), [TanStack Query](https://tanstack.com/query), [TanStack Router](https://tanstack.com/router) and [Chakra UI](https://chakra-ui.com/).
|
||||||
|
|
||||||
|
## Frontend development
|
||||||
|
|
||||||
|
Before you begin, ensure that you have either the Node Version Manager (nvm) or Fast Node Manager (fnm) installed on your system.
|
||||||
|
|
||||||
|
* To install fnm follow the [official fnm guide](https://github.com/Schniz/fnm#installation). If you prefer nvm, you can install it using the [official nvm guide](https://github.com/nvm-sh/nvm#installing-and-updating).
|
||||||
|
|
||||||
|
* After installing either nvm or fnm, proceed to the `frontend` directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
```
|
||||||
|
* If the Node.js version specified in the `.nvmrc` file isn't installed on your system, you can install it using the appropriate command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# If using fnm
|
||||||
|
fnm install
|
||||||
|
|
||||||
|
# If using nvm
|
||||||
|
nvm install
|
||||||
|
```
|
||||||
|
|
||||||
|
* Once the installation is complete, switch to the installed version:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# If using fnm
|
||||||
|
fnm use
|
||||||
|
|
||||||
|
# If using nvm
|
||||||
|
nvm use
|
||||||
|
```
|
||||||
|
|
||||||
|
* Within the `frontend` directory, install the necessary NPM packages:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
* And start the live server with the following `npm` script:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
* Then open your browser at http://localhost:5173/.
|
||||||
|
|
||||||
|
Notice that this live server is not running inside Docker, it's for local development, and that is the recommended workflow. Once you are happy with your frontend, you can build the frontend Docker image and start it, to test it in a production-like environment. But building the image at every change will not be as productive as running the local development server with live reload.
|
||||||
|
|
||||||
|
Check the file `package.json` to see other available options.
|
||||||
|
|
||||||
|
### Removing the frontend
|
||||||
|
|
||||||
|
If you are developing an API-only app and want to remove the frontend, you can do it easily:
|
||||||
|
|
||||||
|
* Remove the `./frontend` directory.
|
||||||
|
|
||||||
|
* In the `docker-compose.yml` file, remove the whole service / section `frontend`.
|
||||||
|
|
||||||
|
* In the `docker-compose.override.yml` file, remove the whole service / section `frontend`.
|
||||||
|
|
||||||
|
Done, you have a frontend-less (api-only) app. 🤓
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
If you want, you can also remove the `FRONTEND` environment variables from:
|
||||||
|
|
||||||
|
* `.env`
|
||||||
|
* `./scripts/*.sh`
|
||||||
|
|
||||||
|
But it would be only to clean them up, leaving them won't really have any effect either way.
|
||||||
|
|
||||||
|
## Generate Client
|
||||||
|
|
||||||
|
* Start the Docker Compose stack.
|
||||||
|
|
||||||
|
* Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory.
|
||||||
|
|
||||||
|
* To simplify the names in the generated frontend client code, modify the `openapi.json` file by running the following script:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node modify-openapi-operationids.js
|
||||||
|
```
|
||||||
|
|
||||||
|
* To generate the frontend client, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run generate-client
|
||||||
|
```
|
||||||
|
|
||||||
|
* Commit the changes.
|
||||||
|
|
||||||
|
Notice that everytime the backend changes (changing the OpenAPI schema), you should follow these steps again to update the frontend client.
|
||||||
|
|
||||||
|
## Using a Remote API
|
||||||
|
|
||||||
|
If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file:
|
||||||
|
|
||||||
|
```env
|
||||||
|
VITE_API_URL=https://my-remote-api.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, when you run the frontend, it will use that URL as the base URL for the API.
|
||||||
|
|
||||||
|
## Code Structure
|
||||||
|
|
||||||
|
The frontend code is structured as follows:
|
||||||
|
|
||||||
|
* `frontend/src` - The main frontend code.
|
||||||
|
* `frontend/src/assets` - Static assets.
|
||||||
|
* `frontend/src/client` - The generated OpenAPI client.
|
||||||
|
* `frontend/src/components` - The different components of the frontend.
|
||||||
|
* `frontend/src/hooks` - Custom hooks.
|
||||||
|
* `frontend/src/routes` - The different routes of the frontend which include the pages.
|
||||||
|
* `theme.tsx` - The Chakra UI custom theme.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Full Stack FastAPI Project</title>
|
||||||
|
<link rel="icon" type="image/x-icon" href="./src/assets/images/favicon.png" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="./src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import * as fs from "fs";
|
||||||
|
|
||||||
|
const filePath = "./openapi.json";
|
||||||
|
|
||||||
|
fs.readFile(filePath, (err, data) => {
|
||||||
|
const openapiContent = JSON.parse(data);
|
||||||
|
if (err) throw err;
|
||||||
|
|
||||||
|
const paths = openapiContent.paths;
|
||||||
|
|
||||||
|
Object.keys(paths).forEach((pathKey) => {
|
||||||
|
const pathData = paths[pathKey];
|
||||||
|
Object.keys(pathData).forEach((method) => {
|
||||||
|
const operation = pathData[method];
|
||||||
|
if (operation.tags && operation.tags.length > 0) {
|
||||||
|
const tag = operation.tags[0];
|
||||||
|
const operationId = operation.operationId;
|
||||||
|
const toRemove = `${tag}-`;
|
||||||
|
if (operationId.startsWith(toRemove)) {
|
||||||
|
const newOperationId = operationId.substring(toRemove.length);
|
||||||
|
operation.operationId = newOperationId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
|
||||||
|
if (err) throw err;
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user