[add] Initial commit

Boilerplate + sops encrypted envs
This commit is contained in:
Pablo Aramburo 2022-08-22 14:17:56 -06:00
commit b639ed5157
164 changed files with 5952 additions and 0 deletions

46
.enc.env Normal file
View File

@ -0,0 +1,46 @@
DOMAIN=ENC[AES256_GCM,data:3mpvpvYc6avb,iv:0A6rLBdgEylA4tlnXG85RL5Jvw/KHWYqpW2D1wN1BwI=,tag:JMVK4NzD6GWJ3nGhz97j0w==,type:str]
#ENC[AES256_GCM,data:xwtz7hlrY6NOLstvstQQUpkDslR2wkzXBZiRk3jTKPcsIrKZfb/CsA==,iv:X/8+38kWjFxBjpGIghPTvY1METE3swWeo/offBzzads=,tag:TGh41mBcRYqDIvXkzBafYA==,type:comment]
#ENC[AES256_GCM,data:UOPMvgZ/6cO47wTG2FsMrHlLKRVuomWUAkjPsFfT,iv:M7jWfXHvBWrB+RXcEq7D+ses+cMb45Ug6tlBSn4NsyI=,tag:xf6nkK8irn1cUwQP/a3elA==,type:comment]
#ENC[AES256_GCM,data:gHB07TeDXOvKUui/ubV9PvJbeiV1upPupaiAzEOyNVy9ID4z3J0J7DxW+Fc=,iv:FIqDDpyJ0mj6Ahx6b6eklBfEFbymVykhHuI5nmc64aM=,tag:T78X3wpUEgetHCHphEapzA==,type:comment]
STACK_NAME=ENC[AES256_GCM,data:cVk0/UM8B2taS5SncYmtzRP9cCY5JhFH4OTXJ5p7kPo=,iv:lld9fhPfYQCsyBoBsOnbOEt6OclmgqFXbr06bQyIKiY=,tag:dwZORXr1QS/gttK8QZAOWA==,type:str]
TRAEFIK_PUBLIC_NETWORK=ENC[AES256_GCM,data:hhjNRPlC5Byqu5HbKeo=,iv:8f0E6qmx1DoZ44tJD+RzmSCu2SU+XKpRSpcIkSpDi14=,tag:PwOzFkGIXdIZ06QdyvjDjQ==,type:str]
TRAEFIK_TAG=ENC[AES256_GCM,data:HGIRXh/OVPMReanVah2dqiwqKR9paWJ2Cm8PLDnLpkA=,iv:THjLe9mGwJyiy4z5WjudYBLOfYTz1b0fWwI0YKXDl2Q=,tag:Qjw1Nsc17BD5Ss+qMd0Gwg==,type:str]
TRAEFIK_PUBLIC_TAG=ENC[AES256_GCM,data:tJVBv+A0g3wKn92Qp1o=,iv:LKe3mCPaawFQNblNcF1RAKjrkl/JZu6lgnWL2K/zrc4=,tag:yb5Gr4fYdT90nvgSNgOHrA==,type:str]
DOCKER_IMAGE_BACKEND=ENC[AES256_GCM,data:31xWo/t8Um6ySdrYlq25Ow==,iv:uK66ZCJl/rZ8z/091Mv0JT94neVb9d9movgTTn58E4s=,tag:J2wwm6DXDyJYGV7DN/Vw1g==,type:str]
DOCKER_IMAGE_CELERYWORKER=ENC[AES256_GCM,data:VROlrMnynC5GTwSK9udx9y3S/A9yDncpVQ==,iv:e3hBam/vrzsli1zLMrhcE0SqYfx1mL4BgvO9V1Ks6CA=,tag:GhvkI9qC8uqnFnjVxkQvgw==,type:str]
DOCKER_IMAGE_FRONTEND=ENC[AES256_GCM,data:er5x5wF2moicdsDLmbZv+0LPodGi,iv:ZPmcDjL0qBYtJnNF17DxZ0kWsiLhUNyJoI4Vbz34MZM=,tag:4FsSgUEyRXY+DnOD1UdKMQ==,type:str]
#ENC[AES256_GCM,data:7dxzvCzPSf4=,iv:s67UDSd2qSjwzryTGJn7vJ+l+hvK+nT0pqvGqRlb0Nk=,tag:RxOQ3nAmDPMDrOWu2nv5qQ==,type:comment]
BACKEND_CORS_ORIGINS=ENC[AES256_GCM,data:EKq2Y94WHkw9Rt4m3jMfNBOkpCKwN7VDclvS527Cuhza+SbqVoNOxz4si7jN2mDzMt+/ZSxI+yPULoyBR1t3jVUF0BXcPxj9TW56pIgSbA8hoeX0ndY+EkytvTI9VDg74i0HIdEa4Ag1LAWde6XFkL6hCd3BJgL8BgHiZKOnCELoFEx3+G8i+mkyltGKpKzO2E3RHHq3vmk+qFnZZ5JAz6YgswkFR4u02mu5y/+LNq47DjRiTuTfsgy9r0uIZ5kIcn8IfkFlvW7iBTJnoMSRHivexm0l9dv/pKr/KeiL0leJyG5b0qh+c+5QKinaU2uwjC7/6Zvci5aNPxNRMnvWuZh7cm7PbThr756ZFpn2yPibm6lwFlKn5BNKmHQ4A+Nw4/1HvAAklgb4b27kvxJi3zcjVOoTUpKyIcIcmfAAnqWCEOE/q7WBwNIGZanwn5x4/WF5sEos1Va3RH7G7b+0CYNkwQsnYtzvHiWHiBoQ/tEOz0WL/0GCHRTRnFbB2Sw9njTtUCePDDaUrsutZ7ADK1yAjfHa7ZB8DN4=,iv:Bc6t8ZNptGwD1WiAbTy7w8Sh5xL1SKwYHjcAMW1C6PY=,tag:H0GFXIVSX/BYYqPIVDywdA==,type:str]
PROJECT_NAME=ENC[AES256_GCM,data:6M9Lc9McrDeo6FfA,iv:EYxq3Qeuai+HOM9Ede6aIG7aqsyo/g5bGw3VBNnStbE=,tag:Az2At+aPxe91zpjqWQ4ZWw==,type:str]
SECRET_KEY=ENC[AES256_GCM,data:001UJh/qD9I/P5fdjm0uFbfvLH8kuqa3uUfUne78RyMhjwpemrp45R/JEGC5289UC9wNitWn+EJvoUi+v9ME0w==,iv:Y1r4K8b0fYVXdvaYzTHiIISd60t3iMOQglXTqJLPGmA=,tag:0MMBCLDrvwq2PZT+mq+4xQ==,type:str]
FIRST_SUPERUSER=ENC[AES256_GCM,data:wnslqvbHLklM9AuxKdpYNzbfi1lPFLKtz73gW5HQsZ9uckoSG0g=,iv:FRoXYxFzu3zM1+rczcu0yeVpMyxqDLXC9FAo0a2DvFs=,tag:alSbSERax4dzypoy+lGFbQ==,type:str]
FIRST_SUPERUSER_PASSWORD=ENC[AES256_GCM,data:QqdzFxT2wq+T4KNr1TAfbNtgZtBu06sr3yAY+pWbju8V5JFbsKosJ/beE+4P/vg5OQuF5m8es/kP93hx9AAR+Q==,iv:nO0oUCs4yWVH3RQMH5+Ueec5bC7yLuf3sbvBHcPGP+g=,tag:bK3d3U9uc+c6WuEcfWo99g==,type:str]
SMTP_TLS=ENC[AES256_GCM,data:vGJdOg==,iv:6wuaQypoye5Rorqsdr2lj59KcUgNV2BMWANVR8npESo=,tag:EAariuZYoIFUR8QtGJ2fKQ==,type:str]
SMTP_PORT=ENC[AES256_GCM,data:bg+T,iv:MhZCnLQOz/GSAU6V1cMfPDPxBaTsp7zJ7NSQvQPusFs=,tag:tgKY3VN7m5K7oZDLrobmPg==,type:str]
SMTP_HOST=
SMTP_USER=
SMTP_PASSWORD=
EMAILS_FROM_EMAIL=ENC[AES256_GCM,data:X9xyaxD6bea9Xt6AdI/hZd460a0rjh3AKlwYHG1WAeDbHLvqJg==,iv:vR959t3iC63yFszx+0wPm9Ji5rIUKvQUOFZA9xYmwsA=,tag:UxN8nVmjTPDtKqPSCto2SA==,type:str]
USERS_OPEN_REGISTRATION=ENC[AES256_GCM,data:jQG/GPc=,iv:WMoazQO0q+eBeyeS1jQqh67OoMGQN794BUp/06t2OdA=,tag:9gVrjVmDCgUSg/Sv1FOPGw==,type:str]
SENTRY_DSN=
#ENC[AES256_GCM,data:8lwQ6mWwVg==,iv:NxtGiJNNRUep3x6kwlosnTcJcmgszxPKAqWn3R3vVlY=,tag:Lby5/MEvv3VXHIPWQYtthw==,type:comment]
FLOWER_BASIC_AUTH=ENC[AES256_GCM,data:8DuGSVlA30tVUfd8nnozoqqQB7lU3BcKnLQEG6H+2RTCRmi1674xg4kHFvVpiLU77cKOrv2hMEye3McDNrD7Jl5vdgZZSQ==,iv:G+aiWLNYFfGLO7eBl7g6eZuls6Dtz5eP6t4o5vN45dQ=,tag:GV6FWT38RD9ZG3JnlQx4Qg==,type:str]
#ENC[AES256_GCM,data:g6DRo/OiKPWc,iv:K9qGpC4uRdLBzmVz66Q9sfsKmfsvsQPjZslB7InMcS8=,tag:S/gE3fn/OBqr03bM3QEhBw==,type:comment]
POSTGRES_SERVER=ENC[AES256_GCM,data:d54=,iv:pLkhRkAkJ4+0JljkLM0z1VeQjvzwNWZhIlE1mcqG3n4=,tag:SmGwlAKQJsMsMpEgDynKkA==,type:str]
POSTGRES_USER=ENC[AES256_GCM,data:HjaMyw2vDWk=,iv:64ey41EzO7Hr/B7sIKHy/HlwZcncmFheNDLr889APyU=,tag:jW7fKUaTPFlKyO9fvw2vxw==,type:str]
POSTGRES_PASSWORD=ENC[AES256_GCM,data:FJoqiWQo5TN16kYb1HJAasPvQV6cWJ9Qxsy/e34JFtraTWAdI6QTZDVkXgpO7iEFxcEvhEsGSqOIebVg44H3UA==,iv:Y5krU1fYxl4JB1dmRiBzJ/hHqRVgYvnrkxyWn/QQGRc=,tag:dWVEyeAVyUNxOLNaxToRYQ==,type:str]
POSTGRES_DB=ENC[AES256_GCM,data:hZgf,iv:3cesD5m9gwpDeDCvk2d6sSMQ+fBsUGTMrMzmnCTQWBc=,tag:CUDR8L+/MlqG8LhqbMYWvQ==,type:str]
#ENC[AES256_GCM,data:zrslweD0YcE=,iv:esZZrxXlFB4ttT2RHlyRBoCNkkl/hFPtjz+IAYdSvW8=,tag:yzvgNS+NzPWvJMbOBl0bQA==,type:comment]
PGADMIN_LISTEN_PORT=ENC[AES256_GCM,data:HyI4OQ==,iv:N1wejs0ScM+2ZFr1JbhD6oPhaAWA5bi87oANPkjbcCc=,tag:QeVLfo5MNNn5Dv0ah6+aVQ==,type:str]
PGADMIN_DEFAULT_EMAIL=ENC[AES256_GCM,data:5JQthkIotdvcTKzB/kk51IEs0rNz4G8+yOPM2L+dRUy3/F2VWEE=,iv:wBGCvZ7We44jn778sVZVALFmTQNW1m9XWW2hwyScruw=,tag:6C4iT+yJqUoVCTxLykJBnQ==,type:str]
PGADMIN_DEFAULT_PASSWORD=ENC[AES256_GCM,data:5honTKtV9O7emQU+2r2mSKwNmIOQCofRiLLBDbDonWS4UQI31hmQgaJgMrbmkWkvPnOoBN+pE3Dx5ba9xt/50Q==,iv:EvdFsYKTIfpZdjYgF4v1aO9Q+GCzuC3Fh8Z5CBMBsMQ=,tag:Ft4HrEl7Cqx2oBZPY7Nb2Q==,type:str]
sops_pgp__list_0__map_fp=F667DDCB4C2C786B0EF6FF7704425FAD6BC1A0F4
sops_version=3.7.3
sops_pgp__list_1__map_fp=1E637A80960A78247805630D12B64D3462D4F90B
sops_pgp__list_0__map_created_at=2022-08-22T20:15:32Z
sops_unencrypted_suffix=_unencrypted
sops_pgp__list_1__map_created_at=2022-08-22T20:15:32Z
sops_pgp__list_0__map_enc=-----BEGIN PGP MESSAGE-----\n\nhQIMAwKAhE25DcB9AQ//ZC/xL7/NbGuI2Murevz1Aip7KHp1yvAZwU7r3TJCU1nC\neYr2A45saCEyoWrl9QFfTNKsqk3tIYW+LNED3IWJi0HyAFyhOew5QyYfvv6tbt8s\nnfA+1GvcenelNVg4Ph69Sv5NThrUCAIymNuL5dWrMRyOQ+NsdnTyFFycZD53U4KZ\nAR6JFMEZhxoY3cWjsTOIbdpT29p4LGFBJv5m6g/IXkRDJdBjcfJzKgeXtYoMQ2i6\n6JbBAZkixPynZeh3yON3TfrneDzUxPs0EmKggBEhgXNFQQTrZ4OfEItaWUyhrTMj\nOQ51A+sR0DxJcLOVWQth/dgbprggAAbZkZgWj0BzM+BCG6wKyYVI2TB11RfMBp/e\nJQEb0GwAoauAfgmEY9G7MgnbpazUpHd25YFOqp7B2meyQOq0mphyy39Ds/lmG5Uw\nZ+085BoVV1KedxF05SmPHsZnB7sDYT/xbnygN/xFGLYg1X2fom4bJxRYmCPWnrAj\nxilWHf85D50+jD1rSoq43w1hSW/37dQ7m7Rnc+YWMOb2VDXgmeTIwRfIHi6SsR8V\n3vKPMsoeH5D8Ualb93QtWkvSNJbt4wT6d4v52b1hfuiD0yNhYPLxvnUmqxNCkuxT\nw1HHzduY/VcJ/Ww4gK0vX9RCaVeEmn31TUymAno2fBrDNwhNghXAZBFr3Ze8IMjS\nXgHxSjtDD4z4dtPwUKlyE7AjixFTZ8BRQYBlE0eoFSj+BfhyObFaGnJQj8y5vg5J\nJ0pBE6hF5VokfIbyEPG7szDQN905mCNy6aOUbBXjQWyCzJ7kMBfmt5H6Gnyh+hg=\n=KE77\n-----END PGP MESSAGE-----\n
sops_lastmodified=2022-08-22T20:15:34Z
sops_pgp__list_1__map_enc=-----BEGIN PGP MESSAGE-----\n\nhQIMAwD3nc+ACRcnAQ//RVl0lQpGPz50/pCgtgN6k/EF/tMk7vGn0f8762TW+eqL\n3SQmhKSMN9lmdTiUEEPyhMBq/FriyHmYiqqJV5FurtKbYpNeJ/n1iByIjsNeLswv\nmVBi7wVKai1sDRMIgQRkUdVjihj/RMCmqAQfKNdrWtdf3M66fa1wAnadH8FAzswB\nkBxnFLhkChCV6jmcKUPOVcybpz0KlC0y91WOfrf70SQdYKHVQU+0Oq2JBAGgFREW\ndsM2yRujKxAdBOtd1qicAJ2/L+Xe2/3f7RBSWYgDCzgQeAhK5/Tyuk46l6ryLuki\n/bB0PAb/1B/ESig3EGmV7QEnoj4eDUUX3nvS/4xWwvpXFb/xW2fjNVj2vIUszSI4\numWnUVEoETtkbhMBb+oiHxt6xixADnZfN74FOzZDrtEkkE/WYNaV3/ILXIZrWuOF\ngwss+igOuxjQ2U1vm5jo4BHnYCV6ypuSHhcMm0BxIwmPU0jX1bdnnu1vqeaiV4GK\nJOW29G1gnauDXyrat2boxNkir5/W+AQGjlycVo1YDOA0l14AGS1vJ6sr9O5V7kQL\ny1UUQlCgGzIR1iaR+xgKJ7VPAFV3MSrG5PpDfkN62mnr3DMOYOCw7IiMjem1ryyW\nfUcHuU4i3Rc+PawKtLM6g2JF8bkjUWCcb0/n7iXLv4ZCxKymXTjcVmeeB0JNYzrS\nXgHbUpAI9PxEP9qLv3SZEv8Y5Yw5OpZ5RR0gZ8oRR1feD0YeLuwC+mgcc6/Duhmo\nA43bupsR4Zx69yzAZx13RWUNxJCWYd6fkOUGG0IR6CkgkMsys4ihH/X72HuBut8=\n=InWH\n-----END PGP MESSAGE-----\n
sops_mac=ENC[AES256_GCM,data:aPWlRuNafOvDyyQbkZtBSM6ZX2ml1Do9PMvpoz2iPPk1mz0pMKTM5uVLQ9iZLToqPbfecE0sXeaA6flgFqaqdiScauTRnSBKSrlXo6mTATmMdggNqxlsv/DwIV5WyrxIPQ1e/xuo8ERHRVXWA+zJrSxhCWJZZDed0ZtsZlH+MQo=,iv:gNlCwQh4tCh+cToM5MVyBIf6CwzwvgwBdq3lhyEFNrw=,tag:z6Ov5yH4wrT2AH7cajLnvA==,type:str]

5
.gitignore vendored Executable file
View File

@ -0,0 +1,5 @@
.vscode
.mypy_cache
docker-stack.yml
.idea
.env

74
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,74 @@
image: tiangolo/docker-with-compose
before_script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
- pip install docker-auto-labels
stages:
- test
- build
- deploy
tests:
stage: test
script:
- sh ./scripts/test.sh
tags:
- build
- test
build-stag:
stage: build
script:
- TAG=stag FRONTEND_ENV=staging sh ./scripts/build-push.sh
only:
- master
tags:
- build
- test
build-prod:
stage: build
script:
- TAG=prod FRONTEND_ENV=production sh ./scripts/build-push.sh
only:
- production
tags:
- build
- test
deploy-stag:
stage: deploy
script:
- >
DOMAIN=stag.sms-receiver.idle.laziness.rocks
TRAEFIK_TAG=stag.sms-receiver.idle.laziness.rocks
STACK_NAME=stag-sms-receiver-idle-laziness-rocks
TAG=stag
sh ./scripts/deploy.sh
environment:
name: staging
url: https://stag.sms-receiver.idle.laziness.rocks
only:
- master
tags:
- swarm
- stag
deploy-prod:
stage: deploy
script:
- >
DOMAIN=sms-receiver.idle.laziness.rocks
TRAEFIK_TAG=sms-receiver.idle.laziness.rocks
STACK_NAME=sms-receiver-idle-laziness-rocks
TAG=prod
sh ./scripts/deploy.sh
environment:
name: production
url: https://sms-receiver.idle.laziness.rocks
only:
- production
tags:
- swarm
- prod

4
.sops.yaml Normal file
View File

@ -0,0 +1,4 @@
creation_rules:
- pgp: >-
F667DDCB4C2C786B0EF6FF7704425FAD6BC1A0F4,
1E637A80960A78247805630D12B64D3462D4F90B

833
README.md Normal file
View File

@ -0,0 +1,833 @@
# sms-receiver
## Backend Requirements
* [Docker](https://www.docker.com/).
* [Docker Compose](https://docs.docker.com/compose/install/).
* [Poetry](https://python-poetry.org/) for Python package and environment management.
## Frontend Requirements
* Node.js (with `npm`).
## Backend 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
Alternative automatic documentation with ReDoc (from the OpenAPI backend): http://localhost/redoc
PGAdmin, PostgreSQL web administration: http://localhost:5050
Flower, administration of Celery tasks: http://localhost:5555
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) check the sections below on **Development with Docker Toolbox** and **Development with a custom IP**.
## 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/app/` 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
```
Next, open your editor at `./backend/app/` (instead of the project root: `./`), so that you see an `./app/` directory with your code inside. That way, your editor will be able to find all the imports, etc. Make sure your editor uses the environment you just created with Poetry.
Modify or add SQLAlchemy models in `./backend/app/app/models/`, Pydantic schemas in `./backend/app/app/schemas/`, API endpoints in `./backend/app/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/app/crud/`. The easiest might be to copy the ones for Items (models, endpoints, and CRUD utils) and update them to your needs.
Add and modify tasks to the Celery worker in `./backend/app/app/worker.py`.
If you need to install any additional package to the worker, add it to the file `./backend/app/celeryworker.dockerfile`.
### 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, or start a Jupyter Notebook session.
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.
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
$ DOMAIN=backend sh ./scripts/test.sh
```
The file `./scripts/test.sh` has the commands to generate a testing `docker-stack.yml` file, start the stack and test it.
The tests run with Pytest, modify and add tests to `./backend/app/app/tests/`.
If you use GitLab CI the tests will run automatically.
#### Local tests
Start the stack with this command:
```Bash
DOMAIN=backend sh ./scripts/test-local.sh
```
The `./backend/app` directory is mounted as a "host volume" inside the docker container (set in the file `docker-compose.dev.volumes.yml`).
You can rerun the test on live code:
```Bash
docker-compose exec backend /app/tests-start.sh
```
#### 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 /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
Because the test scripts forward arguments to `pytest`, you can enable test coverage HTML report generation by passing `--cov-report=html`.
To run the local tests with coverage HTML reports:
```Bash
DOMAIN=backend sh ./scripts/test-local.sh --cov-report=html
```
To run the tests in a running stack with coverage HTML reports:
```bash
docker-compose exec backend bash /app/tests-start.sh --cov-report=html
```
### Live development with Python Jupyter Notebooks
If you know about Python [Jupyter Notebooks](http://jupyter.org/), you can take advantage of them during local development.
The `docker-compose.override.yml` file sends a variable `env` with a value `dev` to the build process of the Docker image (during local development) and the `Dockerfile` has steps to then install and configure Jupyter inside your Docker container.
So, you can enter into the running Docker container:
```bash
docker-compose exec backend bash
```
And use the environment variable `$JUPYTER` to run a Jupyter Notebook with everything configured to listen on the public port (so that you can use it from your browser).
It will output something like:
```console
root@73e0ec1f1ae6:/app# $JUPYTER
[I 12:02:09.975 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[I 12:02:10.317 NotebookApp] Serving notebooks from local directory: /app
[I 12:02:10.317 NotebookApp] The Jupyter Notebook is running at:
[I 12:02:10.317 NotebookApp] http://(73e0ec1f1ae6 or 127.0.0.1):8888/?token=f20939a41524d021fbfc62b31be8ea4dd9232913476f4397
[I 12:02:10.317 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 12:02:10.317 NotebookApp] No web browser found: could not locate runnable browser.
[C 12:02:10.317 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://(73e0ec1f1ae6 or 127.0.0.1):8888/?token=f20939a41524d021fbfc62b31be8ea4dd9232913476f4397
```
you can copy that URL and modify the "host" to be `localhost` or the domain you are using for development (e.g. `local.dockertoolbox.tiangolo.com`), in the case above, it would be, e.g.:
```
http://localhost:8888/token=f20939a41524d021fbfc62b31be8ea4dd9232913476f4397
```
and then open it in your browser.
You will have a full Jupyter Notebook running inside your container that has direct access to your database by the container name (`db`), etc. So, you can just run sections of your backend code directly, for example with [VS Code Python Jupyter Interactive Window](https://code.visualstudio.com/docs/python/jupyter-support-py) or [Hydrogen](https://github.com/nteract/hydrogen).
### 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
```
* If you created a new model in `./backend/app/app/models/`, make sure to import it in `./backend/app/app/db/base.py`, that Python module (`base.py`) that imports all the models will be used by Alembic.
* 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 line in the file at `./backend/app/app/db/init_db.py` with:
```python
Base.metadata.create_all(bind=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.
### Development with Docker Toolbox
If you are using **Docker Toolbox** in Windows or macOS instead of **Docker for Windows** or **Docker for Mac**, Docker will be running in a VirtualBox Virtual Machine, and it will have a local IP different than `127.0.0.1`, which is the IP address for `localhost` in your machine.
The address of your Docker Toolbox virtual machine would probably be `192.168.99.100` (that is the default).
As this is a common case, the domain `local.dockertoolbox.tiangolo.com` points to that (private) IP, just to help with development (actually `dockertoolbox.tiangolo.com` and all its subdomains point to that IP). That way, you can start the stack in Docker Toolbox, and use that domain for development. You will be able to open that URL in Chrome and it will communicate with your local Docker Toolbox directly as if it was a cloud server, including CORS (Cross Origin Resource Sharing).
If you used the default CORS enabled domains while generating the project, `local.dockertoolbox.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 `local.dockertoolbox.tiangolo.com`.
After performing those steps you should be able to open: http://local.dockertoolbox.tiangolo.com and it will be server by your stack in your Docker Toolbox virtual machine.
Check all the corresponding available URLs in the section at the end.
### 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 server 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`) and `192.168.99.100` (the default of Docker Toolbox), you will need to perform some additional steps. That will be the case if you are running a custom Virtual Machine, a secondary Docker Toolbox 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.sms-receiver.idle.laziness.rocks`) and make your computer think that the domain is is served by the custom IP (e.g. `192.168.99.150`).
If you used the default CORS enabled domains, `dev.sms-receiver.idle.laziness.rocks` was configured to be allowed. If you want a custom one, 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.sms-receiver.idle.laziness.rocks`.
The new line might look like:
```
192.168.99.100 dev.sms-receiver.idle.laziness.rocks
```
* 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.sms-receiver.idle.laziness.rocks` 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.sms-receiver.idle.laziness.rocks`.
After performing those steps you should be able to open: http://dev.sms-receiver.idle.laziness.rocks and it will be server by your stack in `localhost`.
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. See the different ways to achieve that in the sections above (i.e. using Docker Toolbox with `local.dockertoolbox.tiangolo.com`, using `localhost.tiangolo.com` or using `dev.sms-receiver.idle.laziness.rocks`).
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. You will need to edit 1 line in 2 files.
* 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.
* Now open the file located at `./frontend/.env`. It would have a line like:
```
VUE_APP_DOMAIN_DEV=localhost
```
* Change that line to the domain you are going to use, e.g.:
```
VUE_APP_DOMAIN_DEV=localhost.tiangolo.com
```
That variable will make your frontend communicate with that domain when interacting with your backend API, when the other variable `VUE_APP_ENV` is set to `development`.
After changing the two lines, you can re-start your stack with:
```bash
docker-compose up -d
```
and check all the corresponding available URLs in the section at the end.
## Frontend development
* Enter the `frontend` directory, install the NPM packages and start the live server using the `npm` scripts:
```bash
cd frontend
npm install
npm run serve
```
Then open your browser at http://localhost:8080
Notice that this live server is not running inside Docker, it is 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 compiling 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.
If you have Vue CLI installed, you can also run `vue ui` to control, configure, serve, and analyze your application using a nice local web user interface.
If you are only developing the frontend (e.g. other team members are developing the backend) and there is a staging environment already deployed, you can make your local development code use that staging API instead of a full local Docker Compose stack.
To do that, modify the file `./frontend/.env`, there's a section with:
```
VUE_APP_ENV=development
# VUE_APP_ENV=staging
```
* Switch the comment, to:
```
# VUE_APP_ENV=development
VUE_APP_ENV=staging
```
### 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`
* `.gitlab-ci.yml`
* `./scripts/*.sh`
But it would be only to clean them up, leaving them won't really have any effect either way.
## Deployment
You can deploy the stack to a Docker Swarm mode cluster with a main Traefik proxy, set up using the ideas from <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a>, to get automatic HTTPS certificates, etc.
And you can use CI (continuous integration) systems to do it automatically.
But you have to configure a couple things first.
### Traefik network
This stack expects the public Traefik network to be named `traefik-public`, just as in the tutorials in <a href="https://dockerswarm.rocks" class="external-link" target="_blank">DockerSwarm.rocks</a>.
If you need to use a different Traefik public network name, update it in the `docker-compose.yml` files, in the section:
```YAML
networks:
traefik-public:
external: true
```
Change `traefik-public` to the name of the used Traefik network. And then update it in the file `.env`:
```bash
TRAEFIK_PUBLIC_NETWORK=traefik-public
```
### Persisting Docker named volumes
You need to make sure that each service (Docker container) that uses a volume is always deployed to the same Docker "node" in the cluster, that way it will preserve the data. Otherwise, it could be deployed to a different node each time, and each time the volume would be created in that new node before starting the service. As a result, it would look like your service was starting from scratch every time, losing all the previous data.
That's specially important for a service running a database. But the same problem would apply if you were saving files in your main backend service (for example, if those files were uploaded by your users, or if they were created by your system).
To solve that, you can put constraints in the services that use one or more data volumes (like databases) to make them be deployed to a Docker node with a specific label. And of course, you need to have that label assigned to one (only one) of your nodes.
#### Adding services with volumes
For each service that uses a volume (databases, services with uploaded files, etc) you should have a label constraint in your `docker-compose.yml` file.
To make sure that your labels are unique per volume per stack (for example, that they are not the same for `prod` and `stag`) you should prefix them with the name of your stack and then use the same name of the volume.
Then you need to have those constraints in your `docker-compose.yml` file for the services that need to be fixed with each volume.
To be able to use different environments, like `prod` and `stag`, you should pass the name of the stack as an environment variable. Like:
```bash
STACK_NAME=stag-sms-receiver-idle-laziness-rocks sh ./scripts/deploy.sh
```
To use and expand that environment variable inside the `docker-compose.yml` files you can add the constraints to the services like:
```yaml
version: '3'
services:
db:
volumes:
- 'app-db-data:/var/lib/postgresql/data/pgdata'
deploy:
placement:
constraints:
- node.labels.${STACK_NAME?Variable not set}.app-db-data == true
```
note the `${STACK_NAME?Variable not set}`. In the script `./scripts/deploy.sh`, the `docker-compose.yml` would be converted, and saved to a file `docker-stack.yml` containing:
```yaml
version: '3'
services:
db:
volumes:
- 'app-db-data:/var/lib/postgresql/data/pgdata'
deploy:
placement:
constraints:
- node.labels.sms-receiver-idle-laziness-rocks.app-db-data == true
```
**Note**: The `${STACK_NAME?Variable not set}` means "use the environment variable `STACK_NAME`, but if it is not set, show an error `Variable not set`".
If you add more volumes to your stack, you need to make sure you add the corresponding constraints to the services that use that named volume.
Then you have to create those labels in some nodes in your Docker Swarm mode cluster. You can use `docker-auto-labels` to do it automatically.
#### `docker-auto-labels`
You can use [`docker-auto-labels`](https://github.com/tiangolo/docker-auto-labels) to automatically read the placement constraint labels in your Docker stack (Docker Compose file) and assign them to a random Docker node in your Swarm mode cluster if those labels don't exist yet.
To do that, you can install `docker-auto-labels`:
```bash
pip install docker-auto-labels
```
And then run it passing your `docker-stack.yml` file as a parameter:
```bash
docker-auto-labels docker-stack.yml
```
You can run that command every time you deploy, right before deploying, as it doesn't modify anything if the required labels already exist.
#### (Optionally) adding labels manually
If you don't want to use `docker-auto-labels` or for any reason you want to manually assign the constraint labels to specific nodes in your Docker Swarm mode cluster, you can do the following:
* First, connect via SSH to your Docker Swarm mode cluster.
* Then check the available nodes with:
```console
$ docker node ls
// you would see an output like:
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
nfa3d4df2df34as2fd34230rm * dog.example.com Ready Active Reachable
2c2sd2342asdfasd42342304e cat.example.com Ready Active Leader
c4sdf2342asdfasd4234234ii snake.example.com Ready Active Reachable
```
then chose a node from the list. For example, `dog.example.com`.
* Add the label to that node. Use as label the name of the stack you are deploying followed by a dot (`.`) followed by the named volume, and as value, just `true`, e.g.:
```bash
docker node update --label-add sms-receiver-idle-laziness-rocks.app-db-data=true dog.example.com
```
* Then you need to do the same for each stack version you have. For example, for staging you could do:
```bash
docker node update --label-add stag-sms-receiver-idle-laziness-rocks.app-db-data=true cat.example.com
```
### Deploy to a Docker Swarm mode cluster
There are 3 steps:
1. **Build** your app images
2. Optionally, **push** your custom images to a Docker Registry
3. **Deploy** your stack
---
Here are the steps in detail:
1. **Build your app images**
* Set these environment variables, right before the next command:
* `TAG=prod`
* `FRONTEND_ENV=production`
* Use the provided `scripts/build.sh` file with those environment variables:
```bash
TAG=prod FRONTEND_ENV=production bash ./scripts/build.sh
```
2. **Optionally, push your images to a Docker Registry**
**Note**: if the deployment Docker Swarm mode "cluster" has more than one server, you will have to push the images to a registry or build the images in each server, so that when each of the servers in your cluster tries to start the containers it can get the Docker images for them, pulling them from a Docker Registry or because it has them already built locally.
If you are using a registry and pushing your images, you can omit running the previous script and instead using this one, in a single shot.
* Set these environment variables:
* `TAG=prod`
* `FRONTEND_ENV=production`
* Use the provided `scripts/build-push.sh` file with those environment variables:
```bash
TAG=prod FRONTEND_ENV=production bash ./scripts/build-push.sh
```
3. **Deploy your stack**
* Set these environment variables:
* `DOMAIN=sms-receiver.idle.laziness.rocks`
* `TRAEFIK_TAG=sms-receiver.idle.laziness.rocks`
* `STACK_NAME=sms-receiver-idle-laziness-rocks`
* `TAG=prod`
* Use the provided `scripts/deploy.sh` file with those environment variables:
```bash
DOMAIN=sms-receiver.idle.laziness.rocks \
TRAEFIK_TAG=sms-receiver.idle.laziness.rocks \
STACK_NAME=sms-receiver-idle-laziness-rocks \
TAG=prod \
bash ./scripts/deploy.sh
```
---
If you change your mind and, for example, want to deploy everything to a different domain, you only have to change the `DOMAIN` environment variable in the previous commands. If you wanted to add a different version / environment of your stack, like "`preproduction`", you would only have to set `TAG=preproduction` in your command and update these other environment variables accordingly. And it would all work, that way you could have different environments and deployments of the same app in the same cluster.
#### Deployment Technical Details
Building and pushing is done with the `docker-compose.yml` file, using the `docker-compose` command. The file `docker-compose.yml` uses the file `.env` with default environment variables. And the scripts set some additional environment variables as well.
The deployment requires using `docker stack` instead of `docker-swarm`, and it can't read environment variables or `.env` files. Because of that, the `deploy.sh` script generates a file `docker-stack.yml` with the configurations from `docker-compose.yml` and injecting the environment variables in it. And then uses it to deploy the stack.
You can do the process by hand based on those same scripts if you wanted. The general structure is like this:
```bash
# Use the environment variables passed to this script, as TAG and FRONTEND_ENV
# And re-create those variables as environment variables for the next command
TAG=${TAG?Variable not set} \
# Set the environment variable FRONTEND_ENV to the same value passed to this script with
# a default value of "production" if nothing else was passed
FRONTEND_ENV=${FRONTEND_ENV-production?Variable not set} \
# The actual comand that does the work: docker-compose
docker-compose \
# Pass the file that should be used, setting explicitly docker-compose.yml avoids the
# default of also using docker-compose.override.yml
-f docker-compose.yml \
# Use the docker-compose sub command named "config", it just uses the docker-compose.yml
# file passed to it and prints their combined contents
# Put those contents in a file "docker-stack.yml", with ">"
config > docker-stack.yml
# The previous only generated a docker-stack.yml file,
# but didn't do anything with it yet
# docker-auto-labels makes sure the labels used for constraints exist in the cluster
docker-auto-labels docker-stack.yml
# Now this command uses that same file to deploy it
docker stack deploy -c docker-stack.yml --with-registry-auth "${STACK_NAME?Variable not set}"
```
### Continuous Integration / Continuous Delivery
If you use GitLab CI, the included `.gitlab-ci.yml` can automatically deploy it. You may need to update it according to your GitLab configurations.
If you use any other CI / CD provider, you can base your deployment from that `.gitlab-ci.yml` file, as all the actual script steps are performed in `bash` scripts that you can easily re-use.
GitLab CI is configured assuming 2 environments following GitLab flow:
* `prod` (production) from the `production` branch.
* `stag` (staging) from the `master` branch.
If you need to add more environments, for example, you could imagine using a client-approved `preprod` branch, you can just copy the configurations in `.gitlab-ci.yml` for `stag` and rename the corresponding variables. The Docker Compose file and environment variables are configured to support as many environments as you need, so that you only need to modify `.gitlab-ci.yml` (or whichever CI system configuration you are using).
## 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.
It is all designed to support several "stages", like development, building, testing, and deployment. Also, allowing the deployment to different environments like staging and production (and you can add more environments very easily).
They are designed to have the minimum repetition of code and configurations, so that if you need to change something, you have to change it in the minimum amount of places. That's why files use environment variables that get auto-expanded. That way, if for example, you want to use a different domain, you can call the `docker-compose` command with a different `DOMAIN` environment variable instead of having to change the domain in several places inside the Docker Compose files.
Also, if you want to have another deployment environment, say `preprod`, you just have to change environment variables, but you can keep using the same Docker Compose files.
### 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
These are the URLs that will be used and generated by the project.
### Production URLs
Production URLs, from the branch `production`.
Frontend: https://sms-receiver.idle.laziness.rocks
Backend: https://sms-receiver.idle.laziness.rocks/api/
Automatic Interactive Docs (Swagger UI): https://sms-receiver.idle.laziness.rocks/docs
Automatic Alternative Docs (ReDoc): https://sms-receiver.idle.laziness.rocks/redoc
PGAdmin: https://pgadmin.sms-receiver.idle.laziness.rocks
Flower: https://flower.sms-receiver.idle.laziness.rocks
### Staging URLs
Staging URLs, from the branch `master`.
Frontend: https://stag.sms-receiver.idle.laziness.rocks
Backend: https://stag.sms-receiver.idle.laziness.rocks/api/
Automatic Interactive Docs (Swagger UI): https://stag.sms-receiver.idle.laziness.rocks/docs
Automatic Alternative Docs (ReDoc): https://stag.sms-receiver.idle.laziness.rocks/redoc
PGAdmin: https://pgadmin.stag.sms-receiver.idle.laziness.rocks
Flower: https://flower.stag.sms-receiver.idle.laziness.rocks
### 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
PGAdmin: http://localhost:5050
Flower: http://localhost:5555
Traefik UI: http://localhost:8090
### Development with Docker Toolbox URLs
Development URLs, for local development.
Frontend: http://local.dockertoolbox.tiangolo.com
Backend: http://local.dockertoolbox.tiangolo.com/api/
Automatic Interactive Docs (Swagger UI): https://local.dockertoolbox.tiangolo.com/docs
Automatic Alternative Docs (ReDoc): https://local.dockertoolbox.tiangolo.com/redoc
PGAdmin: http://local.dockertoolbox.tiangolo.com:5050
Flower: http://local.dockertoolbox.tiangolo.com:5555
Traefik UI: http://local.dockertoolbox.tiangolo.com:8090
### Development with a custom IP URLs
Development URLs, for local development.
Frontend: http://dev.sms-receiver.idle.laziness.rocks
Backend: http://dev.sms-receiver.idle.laziness.rocks/api/
Automatic Interactive Docs (Swagger UI): https://dev.sms-receiver.idle.laziness.rocks/docs
Automatic Alternative Docs (ReDoc): https://dev.sms-receiver.idle.laziness.rocks/redoc
PGAdmin: http://dev.sms-receiver.idle.laziness.rocks:5050
Flower: http://dev.sms-receiver.idle.laziness.rocks:5555
Traefik UI: http://dev.sms-receiver.idle.laziness.rocks: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
PGAdmin: http://localhost.tiangolo.com:5050
Flower: http://localhost.tiangolo.com:5555
Traefik UI: http://localhost.tiangolo.com:8090
## Project generation and updating, or re-generating
This project was generated using https://github.com/tiangolo/full-stack-fastapi-postgresql with:
```bash
pip install cookiecutter
cookiecutter https://github.com/tiangolo/full-stack-fastapi-postgresql
```
You can check the variables used during generation in the file `cookiecutter-config-file.yml`.
You can generate the project again with the same configurations used the first time.
That would be useful if, for example, the project generator (`tiangolo/full-stack-fastapi-postgresql`) was updated and you wanted to integrate or review the changes.
You could generate a new project with the same configurations as this one in a parallel directory. And compare the differences between the two, without having to overwrite your current code but being able to use the same variables used for your current project.
To achieve that, the generated project includes the file `cookiecutter-config-file.yml` with the current variables used.
You can use that file while generating a new project to reuse all those variables.
For example, run:
```console
$ cookiecutter --config-file ./cookiecutter-config-file.yml --output-dir ../project-copy https://github.com/tiangolo/full-stack-fastapi-postgresql
```
That will use the file `cookiecutter-config-file.yml` in the current directory (in this project) to generate a new project inside a sibling directory `project-copy`.

2
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
__pycache__
app.egg-info

3
backend/app/.flake8 Normal file
View File

@ -0,0 +1,3 @@
[flake8]
max-line-length = 88
exclude = .git,__pycache__,__init__.py,.mypy_cache,.pytest_cache

3
backend/app/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.mypy_cache
.coverage
htmlcov

71
backend/app/alembic.ini Executable file
View File

@ -0,0 +1,71 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
#truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

1
backend/app/alembic/README Executable file
View File

@ -0,0 +1 @@
Generic single-database configuration.

87
backend/app/alembic/env.py Executable file
View File

@ -0,0 +1,87 @@
from __future__ import with_statement
import os
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
# target_metadata = None
from app.db.base import Base # noqa
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_url():
user = os.getenv("POSTGRES_USER", "postgres")
password = os.getenv("POSTGRES_PASSWORD", "")
server = os.getenv("POSTGRES_SERVER", "db")
db = os.getenv("POSTGRES_DB", "app")
return f"postgresql://{user}:{password}@{server}/{db}"
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = get_url()
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata, compare_type=True
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

View File

@ -0,0 +1,59 @@
"""First revision
Revision ID: d4867f3a4c0a
Revises:
Create Date: 2019-04-17 13:53:32.978401
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "d4867f3a4c0a"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"user",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("full_name", sa.String(), nullable=True),
sa.Column("email", sa.String(), nullable=True),
sa.Column("hashed_password", sa.String(), nullable=True),
sa.Column("is_active", sa.Boolean(), nullable=True),
sa.Column("is_superuser", sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_user_email"), "user", ["email"], unique=True)
op.create_index(op.f("ix_user_full_name"), "user", ["full_name"], unique=False)
op.create_index(op.f("ix_user_id"), "user", ["id"], unique=False)
op.create_table(
"item",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("title", sa.String(), nullable=True),
sa.Column("description", sa.String(), nullable=True),
sa.Column("owner_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(["owner_id"], ["user.id"],),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_item_description"), "item", ["description"], unique=False)
op.create_index(op.f("ix_item_id"), "item", ["id"], unique=False)
op.create_index(op.f("ix_item_title"), "item", ["title"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_item_title"), table_name="item")
op.drop_index(op.f("ix_item_id"), table_name="item")
op.drop_index(op.f("ix_item_description"), table_name="item")
op.drop_table("item")
op.drop_index(op.f("ix_user_id"), table_name="user")
op.drop_index(op.f("ix_user_full_name"), table_name="user")
op.drop_index(op.f("ix_user_email"), table_name="user")
op.drop_table("user")
# ### end Alembic commands ###

View File

View File

View File

View File

@ -0,0 +1,9 @@
from fastapi import APIRouter
from app.api.api_v1.endpoints 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"])

View File

@ -0,0 +1,99 @@
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Retrieve items.
"""
if crud.user.is_superuser(current_user):
items = crud.item.get_multi(db, skip=skip, limit=limit)
else:
items = crud.item.get_multi_by_owner(
db=db, owner_id=current_user.id, skip=skip, limit=limit
)
return items
@router.post("/", response_model=schemas.Item)
def create_item(
*,
db: Session = Depends(deps.get_db),
item_in: schemas.ItemCreate,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Create new item.
"""
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=current_user.id)
return item
@router.put("/{id}", response_model=schemas.Item)
def update_item(
*,
db: Session = Depends(deps.get_db),
id: int,
item_in: schemas.ItemUpdate,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Update an item.
"""
item = crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
return item
@router.get("/{id}", response_model=schemas.Item)
def read_item(
*,
db: Session = Depends(deps.get_db),
id: int,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get item by ID.
"""
item = crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
return item
@router.delete("/{id}", response_model=schemas.Item)
def delete_item(
*,
db: Session = Depends(deps.get_db),
id: int,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Delete an item.
"""
item = crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
item = crud.item.remove(db=db, id=id)
return item

View File

@ -0,0 +1,96 @@
from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.utils import (
generate_password_reset_token,
send_reset_password_email,
verify_password_reset_token,
)
router = APIRouter()
@router.post("/login/access-token", response_model=schemas.Token)
def login_access_token(
db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(
db, email=form_data.username, password=form_data.password
)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
elif not crud.user.is_active(user):
raise HTTPException(status_code=400, detail="Inactive user")
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": security.create_access_token(
user.id, expires_delta=access_token_expires
),
"token_type": "bearer",
}
@router.post("/login/test-token", response_model=schemas.User)
def test_token(current_user: models.User = Depends(deps.get_current_user)) -> Any:
"""
Test access token
"""
return current_user
@router.post("/password-recovery/{email}", response_model=schemas.Msg)
def recover_password(email: str, db: Session = Depends(deps.get_db)) -> Any:
"""
Password Recovery
"""
user = crud.user.get_by_email(db, 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)
send_reset_password_email(
email_to=user.email, email=email, token=password_reset_token
)
return {"msg": "Password recovery email sent"}
@router.post("/reset-password/", response_model=schemas.Msg)
def reset_password(
token: str = Body(...),
new_password: str = Body(...),
db: Session = Depends(deps.get_db),
) -> Any:
"""
Reset password
"""
email = verify_password_reset_token(token)
if not email:
raise HTTPException(status_code=400, detail="Invalid token")
user = crud.user.get_by_email(db, email=email)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this username does not exist in the system.",
)
elif not crud.user.is_active(user):
raise HTTPException(status_code=400, detail="Inactive user")
hashed_password = get_password_hash(new_password)
user.hashed_password = hashed_password
db.add(user)
db.commit()
return {"msg": "Password updated successfully"}

View File

@ -0,0 +1,153 @@
from typing import Any, List
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic.networks import EmailStr
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
from app.core.config import settings
from app.utils import send_new_account_email
router = APIRouter()
@router.get("/", response_model=List[schemas.User])
def read_users(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Retrieve users.
"""
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users
@router.post("/", response_model=schemas.User)
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schemas.UserCreate,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Create new user.
"""
user = crud.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=400,
detail="The user with this username already exists in the system.",
)
user = crud.user.create(db, obj_in=user_in)
if settings.EMAILS_ENABLED and user_in.email:
send_new_account_email(
email_to=user_in.email, username=user_in.email, password=user_in.password
)
return user
@router.put("/me", response_model=schemas.User)
def update_user_me(
*,
db: Session = Depends(deps.get_db),
password: str = Body(None),
full_name: str = Body(None),
email: EmailStr = Body(None),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Update own user.
"""
current_user_data = jsonable_encoder(current_user)
user_in = schemas.UserUpdate(**current_user_data)
if password is not None:
user_in.password = password
if full_name is not None:
user_in.full_name = full_name
if email is not None:
user_in.email = email
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
return user
@router.get("/me", response_model=schemas.User)
def read_user_me(
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get current user.
"""
return current_user
@router.post("/open", response_model=schemas.User)
def create_user_open(
*,
db: Session = Depends(deps.get_db),
password: str = Body(...),
email: EmailStr = Body(...),
full_name: str = Body(None),
) -> 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.user.get_by_email(db, email=email)
if user:
raise HTTPException(
status_code=400,
detail="The user with this username already exists in the system",
)
user_in = schemas.UserCreate(password=password, email=email, full_name=full_name)
user = crud.user.create(db, obj_in=user_in)
return user
@router.get("/{user_id}", response_model=schemas.User)
def read_user_by_id(
user_id: int,
current_user: models.User = Depends(deps.get_current_active_user),
db: Session = Depends(deps.get_db),
) -> Any:
"""
Get a specific user by id.
"""
user = crud.user.get(db, id=user_id)
if user == current_user:
return user
if not crud.user.is_superuser(current_user):
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return user
@router.put("/{user_id}", response_model=schemas.User)
def update_user(
*,
db: Session = Depends(deps.get_db),
user_id: int,
user_in: schemas.UserUpdate,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Update a user.
"""
user = crud.user.get(db, id=user_id)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this username does not exist in the system",
)
user = crud.user.update(db, db_obj=user, obj_in=user_in)
return user

View File

@ -0,0 +1,35 @@
from typing import Any
from fastapi import APIRouter, Depends
from pydantic.networks import EmailStr
from app import models, schemas
from app.api import deps
from app.core.celery_app import celery_app
from app.utils import send_test_email
router = APIRouter()
@router.post("/test-celery/", response_model=schemas.Msg, status_code=201)
def test_celery(
msg: schemas.Msg,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Test Celery worker.
"""
celery_app.send_task("app.worker.test_celery", args=[msg.msg])
return {"msg": "Word received"}
@router.post("/test-email/", response_model=schemas.Msg, status_code=201)
def test_email(
email_to: EmailStr,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Test emails.
"""
send_test_email(email_to=email_to)
return {"msg": "Test email sent"}

View File

@ -0,0 +1,61 @@
from typing import Generator
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.core import security
from app.core.config import settings
from app.db.session import SessionLocal
reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)
def get_db() -> Generator:
try:
db = SessionLocal()
yield db
finally:
db.close()
def get_current_user(
db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
token_data = schemas.TokenPayload(**payload)
except (jwt.JWTError, ValidationError):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
user = crud.user.get(db, id=token_data.sub)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
def get_current_active_user(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not crud.user.is_active(current_user):
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
def get_current_active_superuser(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not crud.user.is_superuser(current_user):
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return current_user

View File

@ -0,0 +1,37 @@
import logging
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import SessionLocal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
max_tries = 60 * 5 # 5 minutes
wait_seconds = 1
@retry(
stop=stop_after_attempt(max_tries),
wait=wait_fixed(wait_seconds),
before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN),
)
def init() -> None:
try:
db = SessionLocal()
# Try to create session to check if DB is awake
db.execute("SELECT 1")
except Exception as e:
logger.error(e)
raise e
def main() -> None:
logger.info("Initializing service")
init()
logger.info("Service finished initializing")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,37 @@
import logging
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import SessionLocal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
max_tries = 60 * 5 # 5 minutes
wait_seconds = 1
@retry(
stop=stop_after_attempt(max_tries),
wait=wait_fixed(wait_seconds),
before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN),
)
def init() -> None:
try:
# Try to create session to check if DB is awake
db = SessionLocal()
db.execute("SELECT 1")
except Exception as e:
logger.error(e)
raise e
def main() -> None:
logger.info("Initializing service")
init()
logger.info("Service finished initializing")
if __name__ == "__main__":
main()

View File

View File

@ -0,0 +1,5 @@
from celery import Celery
celery_app = Celery("worker", broker="amqp://guest@queue//")
celery_app.conf.task_routes = {"app.worker.test_celery": "main-queue"}

View File

@ -0,0 +1,89 @@
import secrets
from typing import Any, Dict, List, Optional, Union
from pydantic import AnyHttpUrl, BaseSettings, EmailStr, HttpUrl, PostgresDsn, validator
class Settings(BaseSettings):
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
SERVER_NAME: str
SERVER_HOST: AnyHttpUrl
# BACKEND_CORS_ORIGINS is a JSON-formatted list of origins
# e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \
# "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]'
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[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)
PROJECT_NAME: str
SENTRY_DSN: Optional[HttpUrl] = None
@validator("SENTRY_DSN", pre=True)
def sentry_dsn_can_be_blank(cls, v: str) -> Optional[str]:
if len(v) == 0:
return None
return v
POSTGRES_SERVER: str
POSTGRES_USER: str
POSTGRES_PASSWORD: str
POSTGRES_DB: str
SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None
@validator("SQLALCHEMY_DATABASE_URI", pre=True)
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
if isinstance(v, str):
return v
return PostgresDsn.build(
scheme="postgresql",
user=values.get("POSTGRES_USER"),
password=values.get("POSTGRES_PASSWORD"),
host=values.get("POSTGRES_SERVER"),
path=f"/{values.get('POSTGRES_DB') or ''}",
)
SMTP_TLS: bool = True
SMTP_PORT: Optional[int] = None
SMTP_HOST: Optional[str] = None
SMTP_USER: Optional[str] = None
SMTP_PASSWORD: Optional[str] = None
EMAILS_FROM_EMAIL: Optional[EmailStr] = None
EMAILS_FROM_NAME: Optional[str] = None
@validator("EMAILS_FROM_NAME")
def get_project_name(cls, v: Optional[str], values: Dict[str, Any]) -> str:
if not v:
return values["PROJECT_NAME"]
return v
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
EMAIL_TEMPLATES_DIR: str = "/app/app/email-templates/build"
EMAILS_ENABLED: bool = False
@validator("EMAILS_ENABLED", pre=True)
def get_emails_enabled(cls, v: bool, values: Dict[str, Any]) -> bool:
return bool(
values.get("SMTP_HOST")
and values.get("SMTP_PORT")
and values.get("EMAILS_FROM_EMAIL")
)
EMAIL_TEST_USER: EmailStr = "test@example.com" # type: ignore
FIRST_SUPERUSER: EmailStr
FIRST_SUPERUSER_PASSWORD: str
USERS_OPEN_REGISTRATION: bool = False
class Config:
case_sensitive = True
settings = Settings()

View File

@ -0,0 +1,34 @@
from datetime import datetime, timedelta
from typing import Any, Union
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: Union[str, Any], expires_delta: timedelta = None
) -> str:
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
)
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)

View File

@ -0,0 +1,10 @@
from .crud_item import item
from .crud_user import user
# For a new basic set of CRUD operations you could just do
# from .base import CRUDBase
# from app.models.item import Item
# from app.schemas.item import ItemCreate, ItemUpdate
# item = CRUDBase[Item, ItemCreate, ItemUpdate](Item)

View File

@ -0,0 +1,66 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.base_class import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType]):
"""
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
* `schema`: A Pydantic model (schema) class
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

View File

@ -0,0 +1,34 @@
from typing import List
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
def create_with_owner(
self, db: Session, *, obj_in: ItemCreate, owner_id: int
) -> Item:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data, owner_id=owner_id)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def get_multi_by_owner(
self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100
) -> List[Item]:
return (
db.query(self.model)
.filter(Item.owner_id == owner_id)
.offset(skip)
.limit(limit)
.all()
)
item = CRUDItem(Item)

View File

@ -0,0 +1,55 @@
from typing import Any, Dict, Optional, Union
from sqlalchemy.orm import Session
from app.core.security import get_password_hash, verify_password
from app.crud.base import CRUDBase
from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
return db.query(User).filter(User.email == email).first()
def create(self, db: Session, *, obj_in: UserCreate) -> User:
db_obj = User(
email=obj_in.email,
hashed_password=get_password_hash(obj_in.password),
full_name=obj_in.full_name,
is_superuser=obj_in.is_superuser,
)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
) -> User:
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
if update_data["password"]:
hashed_password = get_password_hash(update_data["password"])
del update_data["password"]
update_data["hashed_password"] = hashed_password
return super().update(db, db_obj=db_obj, obj_in=update_data)
def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
user = self.get_by_email(db, email=email)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
def is_active(self, user: User) -> bool:
return user.is_active
def is_superuser(self, user: User) -> bool:
return user.is_superuser
user = CRUDUser(User)

View File

View File

@ -0,0 +1,5 @@
# Import all the models, so that Base has them before being
# imported by Alembic
from app.db.base_class import Base # noqa
from app.models.item import Item # noqa
from app.models.user import User # noqa

View File

@ -0,0 +1,13 @@
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

View File

@ -0,0 +1,25 @@
from sqlalchemy.orm import Session
from app import crud, schemas
from app.core.config import settings
from app.db import base # noqa: F401
# make sure all SQL Alchemy models are imported (app.db.base) before initializing DB
# otherwise, SQL Alchemy might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28
def init_db(db: 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 line
# Base.metadata.create_all(bind=engine)
user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER)
if not user:
user_in = schemas.UserCreate(
email=settings.FIRST_SUPERUSER,
password=settings.FIRST_SUPERUSER_PASSWORD,
is_superuser=True,
)
user = crud.user.create(db, obj_in=user_in) # noqa: F841

View File

@ -0,0 +1,7 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

View File

@ -0,0 +1,26 @@
<!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:#ffffff;"><div style="background-color:#ffffff;"><!--[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="Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:top;width:600px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 4px #555555;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 4px #555555;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#555555;">{{ project_name }} - New Account</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">You have a new account:</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">Username: {{ username }}</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">Password: {{ password }}</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:50px 0px;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="#414141" role="presentation" style="border:none;border-radius:3px;cursor:auto;padding:10px 25px;background:#414141;" valign="middle"><a href="{{ link }}" style="background:#414141;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;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 #555555;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 #555555;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</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>

View File

@ -0,0 +1,26 @@
<!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:#ffffff;"><div style="background-color:#ffffff;"><!--[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="Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:top;width:600px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 4px #555555;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 4px #555555;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#555555;">{{ project_name }} - Password Recovery</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">We received a request to recover the password for user {{ username }} with email {{ email }}</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">Reset your password by clicking the button below:</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:50px 0px;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="#414141" role="presentation" style="border:none;border-radius:3px;cursor:auto;padding:10px 25px;background:#414141;" valign="middle"><a href="{{ link }}" style="background:#414141;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;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="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">Or open the following link:</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;"><a href="{{ link }}">{{ link }}</a></div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #555555;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 #555555;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:14px;line-height:1;text-align:left;color:#555555;">The reset password link / button will expire in {{ valid_hours }} hours.</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:14px;line-height:1;text-align:left;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>

View File

@ -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:#ffffff;"><div style="background-color:#ffffff;"><!--[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="Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:top;width:600px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 4px #555555;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 4px #555555;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#555555;">{{ project_name }}</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#555555;">Test email for: {{ 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>

View File

@ -0,0 +1,15 @@
<mjml>
<mj-body background-color="#fff">
<mj-section>
<mj-column>
<mj-divider border-color="#555"></mj-divider>
<mj-text font-size="20px" color="#555" font-family="helvetica">{{ project_name }} - New Account</mj-text>
<mj-text font-size="16px" color="#555">You have a new account:</mj-text>
<mj-text font-size="16px" color="#555">Username: {{ username }}</mj-text>
<mj-text font-size="16px" color="#555">Password: {{ password }}</mj-text>
<mj-button padding="50px 0px" href="{{ link }}">Go to Dashboard</mj-button>
<mj-divider border-color="#555" border-width="2px" />
</mj-column>
</mj-section>
</mj-body>
</mjml>

View File

@ -0,0 +1,19 @@
<mjml>
<mj-body background-color="#fff">
<mj-section>
<mj-column>
<mj-divider border-color="#555"></mj-divider>
<mj-text font-size="20px" color="#555" font-family="helvetica">{{ project_name }} - Password Recovery</mj-text>
<mj-text font-size="16px" color="#555">We received a request to recover the password for user {{ username }}
with email {{ email }}</mj-text>
<mj-text font-size="16px" color="#555">Reset your password by clicking the button below:</mj-text>
<mj-button padding="50px 0px" href="{{ link }}">Reset Password</mj-button>
<mj-text font-size="16px" color="#555">Or open the following link:</mj-text>
<mj-text font-size="16px" color="#555"><a href="{{ link }}">{{ link }}</a></mj-text>
<mj-divider border-color="#555" border-width="2px" />
<mj-text font-size="14px" color="#555">The reset password link / button will expire in {{ valid_hours }} hours.</mj-text>
<mj-text font-size="14px" color="#555">If you didn't request a password recovery you can disregard this email.</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>

View File

@ -0,0 +1,11 @@
<mjml>
<mj-body background-color="#fff">
<mj-section>
<mj-column>
<mj-divider border-color="#555"></mj-divider>
<mj-text font-size="20px" color="#555" font-family="helvetica">{{ project_name }}</mj-text>
<mj-text font-size="16px" color="#555">Test email for: {{ email }}</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>

View File

@ -0,0 +1,22 @@
import logging
from app.db.init_db import init_db
from app.db.session import SessionLocal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def init() -> None:
db = SessionLocal()
init_db(db)
def main() -> None:
logger.info("Creating initial data")
init()
logger.info("Initial data created")
if __name__ == "__main__":
main()

21
backend/app/app/main.py Normal file
View File

@ -0,0 +1,21 @@
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.api_v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)

View File

@ -0,0 +1,2 @@
from .item import Item
from .user import User

17
backend/app/app/models/item.py Executable file
View File

@ -0,0 +1,17 @@
from typing import TYPE_CHECKING
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from .user import User # noqa: F401
class Item(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("user.id"))
owner = relationship("User", back_populates="items")

19
backend/app/app/models/user.py Executable file
View File

@ -0,0 +1,19 @@
from typing import TYPE_CHECKING
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from .item import Item # noqa: F401
class User(Base):
id = Column(Integer, primary_key=True, index=True)
full_name = Column(String, index=True)
email = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
is_active = Column(Boolean(), default=True)
is_superuser = Column(Boolean(), default=False)
items = relationship("Item", back_populates="owner")

View File

@ -0,0 +1,4 @@
from .item import Item, ItemCreate, ItemInDB, ItemUpdate
from .msg import Msg
from .token import Token, TokenPayload
from .user import User, UserCreate, UserInDB, UserUpdate

View File

@ -0,0 +1,39 @@
from typing import Optional
from pydantic import BaseModel
# Shared properties
class ItemBase(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
# Properties to receive on item creation
class ItemCreate(ItemBase):
title: str
# Properties to receive on item update
class ItemUpdate(ItemBase):
pass
# Properties shared by models stored in DB
class ItemInDBBase(ItemBase):
id: int
title: str
owner_id: int
class Config:
orm_mode = True
# Properties to return to client
class Item(ItemInDBBase):
pass
# Properties properties stored in DB
class ItemInDB(ItemInDBBase):
pass

View File

@ -0,0 +1,5 @@
from pydantic import BaseModel
class Msg(BaseModel):
msg: str

View File

@ -0,0 +1,12 @@
from typing import Optional
from pydantic import BaseModel
class Token(BaseModel):
access_token: str
token_type: str
class TokenPayload(BaseModel):
sub: Optional[int] = None

View File

@ -0,0 +1,39 @@
from typing import Optional
from pydantic import BaseModel, EmailStr
# Shared properties
class UserBase(BaseModel):
email: Optional[EmailStr] = None
is_active: Optional[bool] = True
is_superuser: bool = False
full_name: Optional[str] = None
# Properties to receive via API on creation
class UserCreate(UserBase):
email: EmailStr
password: str
# Properties to receive via API on update
class UserUpdate(UserBase):
password: Optional[str] = None
class UserInDBBase(UserBase):
id: Optional[int] = None
class Config:
orm_mode = True
# Additional properties to return via API
class User(UserInDBBase):
pass
# Additional properties stored in DB
class UserInDB(UserInDBBase):
hashed_password: str

1
backend/app/app/tests/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
.cache

View File

View File

View File

@ -0,0 +1,18 @@
from typing import Dict
from fastapi.testclient import TestClient
from app.core.config import settings
def test_celery_worker_test(
client: TestClient, superuser_token_headers: Dict[str, str]
) -> None:
data = {"msg": "test"}
r = client.post(
f"{settings.API_V1_STR}/utils/test-celery/",
json=data,
headers=superuser_token_headers,
)
response = r.json()
assert response["msg"] == "Word received"

View File

@ -0,0 +1,35 @@
from fastapi.testclient import TestClient
from sqlalchemy.orm 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, 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, 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

View File

@ -0,0 +1,28 @@
from typing import Dict
from fastapi.testclient import TestClient
from app.core.config import settings
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_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

View File

@ -0,0 +1,115 @@
from typing import Dict
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app import crud
from app.core.config import settings
from app.schemas.user 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, db: Session
) -> None:
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.user.get_by_email(db, email=username)
assert user
assert user.email == created_user["email"]
def test_get_existing_user(
client: TestClient, superuser_token_headers: dict, db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.user.create(db, obj_in=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.user.get_by_email(db, email=username)
assert existing_user
assert existing_user.email == api_user["email"]
def test_create_user_existing_username(
client: TestClient, superuser_token_headers: dict, db: Session
) -> None:
username = random_email()
# username = email
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
crud.user.create(db, obj_in=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, db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
crud.user.create(db, obj_in=user_in)
username2 = random_email()
password2 = random_lower_string()
user_in2 = UserCreate(email=username2, password=password2)
crud.user.create(db, obj_in=user_in2)
r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers)
all_users = r.json()
assert len(all_users) > 1
for item in all_users:
assert "email" in item

View File

@ -0,0 +1,34 @@
from typing import Dict, Generator
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.session import SessionLocal
from app.main import app
from app.tests.utils.user import authentication_token_from_email
from app.tests.utils.utils import get_superuser_token_headers
@pytest.fixture(scope="session")
def db() -> Generator:
yield SessionLocal()
@pytest.fixture(scope="module")
def client() -> Generator:
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
)

View File

View File

@ -0,0 +1,61 @@
from sqlalchemy.orm import Session
from app import crud
from app.schemas.item import ItemCreate, ItemUpdate
from app.tests.utils.user import create_random_user
from app.tests.utils.utils import random_lower_string
def test_create_item(db: Session) -> None:
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description)
user = create_random_user(db)
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=user.id)
assert item.title == title
assert item.description == description
assert item.owner_id == user.id
def test_get_item(db: Session) -> None:
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description)
user = create_random_user(db)
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=user.id)
stored_item = crud.item.get(db=db, id=item.id)
assert stored_item
assert item.id == stored_item.id
assert item.title == stored_item.title
assert item.description == stored_item.description
assert item.owner_id == stored_item.owner_id
def test_update_item(db: Session) -> None:
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description)
user = create_random_user(db)
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=user.id)
description2 = random_lower_string()
item_update = ItemUpdate(description=description2)
item2 = crud.item.update(db=db, db_obj=item, obj_in=item_update)
assert item.id == item2.id
assert item.title == item2.title
assert item2.description == description2
assert item.owner_id == item2.owner_id
def test_delete_item(db: Session) -> None:
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description)
user = create_random_user(db)
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=user.id)
item2 = crud.item.remove(db=db, id=item.id)
item3 = crud.item.get(db=db, id=item.id)
assert item3 is None
assert item2.id == item.id
assert item2.title == title
assert item2.description == description
assert item2.owner_id == user.id

View File

@ -0,0 +1,94 @@
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app import crud
from app.core.security import verify_password
from app.schemas.user import 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.user.create(db, obj_in=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.user.create(db, obj_in=user_in)
authenticated_user = crud.user.authenticate(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.user.authenticate(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.user.create(db, obj_in=user_in)
is_active = crud.user.is_active(user)
assert 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.user.create(db, obj_in=user_in)
is_active = crud.user.is_active(user)
assert 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.user.create(db, obj_in=user_in)
is_superuser = crud.user.is_superuser(user)
assert 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.user.create(db, obj_in=user_in)
is_superuser = crud.user.is_superuser(user)
assert 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.user.create(db, obj_in=user_in)
user_2 = crud.user.get(db, id=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.user.create(db, obj_in=user_in)
new_password = random_lower_string()
user_in_update = UserUpdate(password=new_password, is_superuser=True)
crud.user.update(db, db_obj=user, obj_in=user_in_update)
user_2 = crud.user.get(db, id=user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)

View File

View File

@ -0,0 +1,18 @@
from typing import Optional
from sqlalchemy.orm import Session
from app import crud, models
from app.schemas.item import 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, *, owner_id: Optional[int] = None) -> models.Item:
if owner_id is None:
user = create_random_user(db)
owner_id = user.id
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description, id=id)
return crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=owner_id)

View File

@ -0,0 +1,50 @@
from typing import Dict
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app import crud
from app.core.config import settings
from app.models.user import User
from app.schemas.user import 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(username=email, email=email, password=password)
user = crud.user.create(db=db, obj_in=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.user.get_by_email(db, email=email)
if not user:
user_in_create = UserCreate(username=email, email=email, password=password)
user = crud.user.create(db, obj_in=user_in_create)
else:
user_in_update = UserUpdate(password=password)
user = crud.user.update(db, db_obj=user, obj_in=user_in_update)
return user_authentication_headers(client=client, email=email, password=password)

View File

@ -0,0 +1,27 @@
import random
import string
from typing import Dict
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

View File

@ -0,0 +1,37 @@
import logging
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import SessionLocal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
max_tries = 60 * 5 # 5 minutes
wait_seconds = 1
@retry(
stop=stop_after_attempt(max_tries),
wait=wait_fixed(wait_seconds),
before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN),
)
def init() -> None:
try:
# Try to create session to check if DB is awake
db = SessionLocal()
db.execute("SELECT 1")
except Exception as e:
logger.error(e)
raise e
def main() -> None:
logger.info("Initializing service")
init()
logger.info("Service finished initializing")
if __name__ == "__main__":
main()

106
backend/app/app/utils.py Normal file
View File

@ -0,0 +1,106 @@
import logging
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, Optional
import emails
from emails.template import JinjaTemplate
from jose import jwt
from app.core.config import settings
def send_email(
email_to: str,
subject_template: str = "",
html_template: str = "",
environment: Dict[str, Any] = {},
) -> None:
assert settings.EMAILS_ENABLED, "no provided configuration for email variables"
message = emails.Message(
subject=JinjaTemplate(subject_template),
html=JinjaTemplate(html_template),
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
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, render=environment, smtp=smtp_options)
logging.info(f"send email result: {response}")
def send_test_email(email_to: str) -> None:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - Test email"
with open(Path(settings.EMAIL_TEMPLATES_DIR) / "test_email.html") as f:
template_str = f.read()
send_email(
email_to=email_to,
subject_template=subject,
html_template=template_str,
environment={"project_name": settings.PROJECT_NAME, "email": email_to},
)
def send_reset_password_email(email_to: str, email: str, token: str) -> None:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {email}"
with open(Path(settings.EMAIL_TEMPLATES_DIR) / "reset_password.html") as f:
template_str = f.read()
server_host = settings.SERVER_HOST
link = f"{server_host}/reset-password?token={token}"
send_email(
email_to=email_to,
subject_template=subject,
html_template=template_str,
environment={
"project_name": settings.PROJECT_NAME,
"username": email,
"email": email_to,
"valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS,
"link": link,
},
)
def send_new_account_email(email_to: str, username: str, password: str) -> None:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - New account for user {username}"
with open(Path(settings.EMAIL_TEMPLATES_DIR) / "new_account.html") as f:
template_str = f.read()
link = settings.SERVER_HOST
send_email(
email_to=email_to,
subject_template=subject,
html_template=template_str,
environment={
"project_name": settings.PROJECT_NAME,
"username": username,
"password": password,
"email": email_to,
"link": link,
},
)
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) -> Optional[str]:
try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return decoded_token["email"]
except jwt.JWTError:
return None

11
backend/app/app/worker.py Normal file
View File

@ -0,0 +1,11 @@
from raven import Client
from app.core.celery_app import celery_app
from app.core.config import settings
client_sentry = Client(settings.SENTRY_DSN)
@celery_app.task(acks_late=True)
def test_celery(word: str) -> str:
return f"test task return {word}"

4
backend/app/mypy.ini Normal file
View File

@ -0,0 +1,4 @@
[mypy]
plugins = pydantic.mypy, sqlmypy
ignore_missing_imports = True
disallow_untyped_defs = True

10
backend/app/prestart.sh Normal file
View File

@ -0,0 +1,10 @@
#! /usr/bin/env bash
# Let the DB start
python /app/app/backend_pre_start.py
# Run migrations
alembic upgrade head
# Create initial data in DB
python /app/app/initial_data.py

View File

@ -0,0 +1,46 @@
[tool.poetry]
name = "app"
version = "0.1.0"
description = ""
authors = ["Admin <admin@example.com>"]
[tool.poetry.dependencies]
python = "^3.7"
uvicorn = "^0.11.3"
fastapi = "^0.54.1"
python-multipart = "^0.0.5"
email-validator = "^1.0.5"
requests = "^2.23.0"
celery = "^4.4.2"
passlib = {extras = ["bcrypt"], version = "^1.7.2"}
tenacity = "^6.1.0"
pydantic = "^1.4"
emails = "^0.5.15"
raven = "^6.10.0"
gunicorn = "^20.0.4"
jinja2 = "^2.11.2"
psycopg2-binary = "^2.8.5"
alembic = "^1.4.2"
sqlalchemy = "^1.3.16"
pytest = "^5.4.1"
python-jose = {extras = ["cryptography"], version = "^3.1.0"}
[tool.poetry.dev-dependencies]
mypy = "^0.770"
black = "^19.10b0"
isort = "^4.3.21"
autoflake = "^1.3.1"
flake8 = "^3.7.9"
pytest = "^5.4.1"
sqlalchemy-stubs = "^0.3"
pytest-cov = "^2.8.1"
[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"

View File

@ -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

6
backend/app/scripts/format.sh Executable file
View File

@ -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

View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -x
mypy app
black app --check
isort --recursive --check-only app
flake8

View File

@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -e
set -x
bash scripts/test.sh --cov-report=html "${@}"

6
backend/app/scripts/test.sh Executable file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -e
set -x
pytest --cov=app --cov-report=term-missing app/tests "${@}"

View File

@ -0,0 +1,6 @@
#! /usr/bin/env bash
set -e
python /app/app/tests_pre_start.py
bash ./scripts/test.sh "$@"

View File

@ -0,0 +1,6 @@
#! /usr/bin/env bash
set -e
python /app/app/celeryworker_pre_start.py
celery worker -A app.worker -l info -Q main-queue -c 1

View File

@ -0,0 +1,25 @@
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
WORKDIR /app/
# Install Poetry
RUN curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | 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 ./app/pyproject.toml ./app/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 --no-dev ; fi"
# For development, Jupyter remote kernel, Hydrogen
# Using inside the container:
# jupyter lab --ip=0.0.0.0 --allow-root --NotebookApp.custom_display_url=http://127.0.0.1:8888
ARG INSTALL_JUPYTER=false
RUN bash -c "if [ $INSTALL_JUPYTER == 'true' ] ; then pip install jupyterlab ; fi"
COPY ./app /app
ENV PYTHONPATH=/app

View File

@ -0,0 +1,35 @@
FROM python:3.7
WORKDIR /app/
# Install Poetry
RUN curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | 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 ./app/pyproject.toml ./app/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 --no-dev ; fi"
# For development, Jupyter remote kernel, Hydrogen
# Using inside the container:
# jupyter lab --ip=0.0.0.0 --allow-root --NotebookApp.custom_display_url=http://127.0.0.1:8888
ARG INSTALL_JUPYTER=false
RUN bash -c "if [ $INSTALL_JUPYTER == 'true' ] ; then pip install jupyterlab ; fi"
ENV C_FORCE_ROOT=1
COPY ./app /app
WORKDIR /app
ENV PYTHONPATH=/app
COPY ./app/worker-start.sh /worker-start.sh
RUN chmod +x /worker-start.sh
CMD ["bash", "/worker-start.sh"]

View File

@ -0,0 +1,30 @@
default_context:
project_name: 'sms-receiver'
project_slug: 'sms-receiver'
domain_main: 'sms-receiver.idle.laziness.rocks'
domain_staging: 'stag.sms-receiver.idle.laziness.rocks'
docker_swarm_stack_name_main: 'sms-receiver-idle-laziness-rocks'
docker_swarm_stack_name_staging: 'stag-sms-receiver-idle-laziness-rocks'
secret_key: '30b20e4d0c1f206e13a424f2db7da3202b474fac5c8217414a5a09bab0d80ca2'
first_superuser: 'admin@sms-receiver.idle.laziness.rocks'
first_superuser_password: '45ff201c3f85b15377f53b719c2c80f888bffb65a6aea39ed64dfe85a294e02a'
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.sms-receiver.idle.laziness.rocks", "https://stag.sms-receiver.idle.laziness.rocks", "https://sms-receiver.idle.laziness.rocks", "http://local.dockertoolbox.tiangolo.com", "http://localhost.tiangolo.com"]'
smtp_port: '587'
smtp_host: ''
smtp_user: ''
smtp_password: ''
smtp_emails_from_email: 'info@sms-receiver.idle.laziness.rocks'
postgres_password: 'ba0e427833eefeaf9d738870d7d077170695d438f9c9b3e643e5924a88f6c40a'
pgadmin_default_user: 'admin@sms-receiver.idle.laziness.rocks'
pgadmin_default_user_password: '20848f4318f505e3440df6d3a882711d7621d7888d8937c07111945c484e6ba7'
traefik_constraint_tag: 'sms-receiver.idle.laziness.rocks'
traefik_constraint_tag_staging: 'stag.sms-receiver.idle.laziness.rocks'
traefik_public_constraint_tag: 'traefik-public'
flower_auth: 'admin:45ff201c3f85b15377f53b719c2c80f888bffb65a6aea39ed64dfe85a294e02a'
sentry_dsn: ''
docker_image_prefix: ''
docker_image_backend: 'sms-receiver-api'
docker_image_celeryworker: 'sms-receiver-celeryworker'
docker_image_frontend: 'sms-receiver-frontend'
_copy_without_render: [frontend/src/**/*.html, frontend/src/**/*.vue, frontend/node_modules/*, backend/app/app/email-templates/**]
_template: ./

View File

@ -0,0 +1,89 @@
version: "3.3"
services:
proxy:
ports:
- "80:80"
- "8090:8080"
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
# from the env var TRAEFIK_TAG
- --providers.docker.constraints=Label(`traefik.constraint-label-stack`, `${TRAEFIK_TAG?Variable not set}`)
# Do not expose all Docker services, only the ones explicitly exposed
- --providers.docker.exposedbydefault=false
# Disable Docker Swarm mode for local development
# - --providers.docker.swarmmode
# Enable the access log, with HTTP requests
- --accesslog
# Enable the Traefik log, for configurations and errors
- --log
# Enable the Dashboard and API
- --api
# Enable the Dashboard and API in insecure mode for local development
- --api.insecure=true
labels:
- traefik.enable=true
- traefik.http.routers.${STACK_NAME?Variable not set}-traefik-public-http.rule=Host(`${DOMAIN?Variable not set}`)
- traefik.http.services.${STACK_NAME?Variable not set}-traefik-public.loadbalancer.server.port=80
pgadmin:
ports:
- "5050:5050"
flower:
ports:
- "5555:5555"
backend:
ports:
- "8888:8888"
volumes:
- ./backend/app:/app
environment:
- JUPYTER=jupyter lab --ip=0.0.0.0 --allow-root --NotebookApp.custom_display_url=http://127.0.0.1:8888
- SERVER_HOST=http://${DOMAIN?Variable not set}
build:
context: ./backend
dockerfile: backend.dockerfile
args:
INSTALL_DEV: ${INSTALL_DEV-true}
INSTALL_JUPYTER: ${INSTALL_JUPYTER-true}
# command: bash -c "while true; do sleep 1; done" # Infinite loop to keep container live doing nothing
command: /start-reload.sh
labels:
- traefik.enable=true
- traefik.constraint-label-stack=${TRAEFIK_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`)
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
celeryworker:
volumes:
- ./backend/app:/app
environment:
- RUN=celery worker -A app.worker -l info -Q main-queue -c 1
- JUPYTER=jupyter lab --ip=0.0.0.0 --allow-root --NotebookApp.custom_display_url=http://127.0.0.1:8888
- SERVER_HOST=http://${DOMAIN?Variable not set}
build:
context: ./backend
dockerfile: celeryworker.dockerfile
args:
INSTALL_DEV: ${INSTALL_DEV-true}
INSTALL_JUPYTER: ${INSTALL_JUPYTER-true}
frontend:
build:
context: ./frontend
args:
FRONTEND_ENV: dev
labels:
- traefik.enable=true
- traefik.constraint-label-stack=${TRAEFIK_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=PathPrefix(`/`)
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
networks:
traefik-public:
# For local dev, don't expect an external Traefik network
external: false

200
docker-compose.yml Normal file
View File

@ -0,0 +1,200 @@
version: "3.3"
services:
proxy:
image: traefik:v2.2
networks:
- ${TRAEFIK_PUBLIC_NETWORK?Variable not set}
- default
volumes:
- /var/run/docker.sock:/var/run/docker.sock
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
# from the env var TRAEFIK_TAG
- --providers.docker.constraints=Label(`traefik.constraint-label-stack`, `${TRAEFIK_TAG?Variable not set}`)
# Do not expose all Docker services, only the ones explicitly exposed
- --providers.docker.exposedbydefault=false
# Enable Docker Swarm mode
- --providers.docker.swarmmode
# Enable the access log, with HTTP requests
- --accesslog
# Enable the Traefik log, for configurations and errors
- --log
# Enable the Dashboard and API
- --api
deploy:
placement:
constraints:
- node.role == manager
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_NETWORK?Variable not set}
# Use the custom label "traefik.constraint-label=traefik-public"
# This public Traefik will only use services with this label
- traefik.constraint-label=${TRAEFIK_PUBLIC_TAG?Variable not set}
# traefik-http set up only to use the middleware to redirect to https
- traefik.http.middlewares.${STACK_NAME?Variable not set}-https-redirect.redirectscheme.scheme=https
- traefik.http.middlewares.${STACK_NAME?Variable not set}-https-redirect.redirectscheme.permanent=true
# Handle host with and without "www" to redirect to only one of them
# Uses environment variable DOMAIN
# To disable www redirection remove the Host() you want to discard, here and
# below for HTTPS
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-http.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-http.entrypoints=http
# traefik-https the actual router using HTTPS
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-https.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-https.tls=true
# Use the "le" (Let's Encrypt) resolver created below
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-https.tls.certresolver=le
# Define the port inside of the Docker service to use
- traefik.http.services.${STACK_NAME?Variable not set}-proxy.loadbalancer.server.port=80
# 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=^https?://(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=https://${DOMAIN?Variable not set}/$${3}
# Redirect a domain without www to www
# To enable it remove the previous line and uncomment the next
# - traefik.http.middlewares.${STACK_NAME}-www-redirect.redirectregex.replacement=https://www.${DOMAIN}/$${3}
# Middleware to redirect www, to disable it remove the next line
- traefik.http.routers.${STACK_NAME?Variable not set}-proxy-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}-proxy-http.middlewares=${STACK_NAME?Variable not set}-www-redirect,${STACK_NAME?Variable not set}-https-redirect
db:
image: postgres:12
volumes:
- app-db-data:/var/lib/postgresql/data/pgdata
env_file:
- .env
environment:
- PGDATA=/var/lib/postgresql/data/pgdata
deploy:
placement:
constraints:
- node.labels.${STACK_NAME?Variable not set}.app-db-data == true
pgadmin:
image: dpage/pgadmin4
networks:
- ${TRAEFIK_PUBLIC_NETWORK?Variable not set}
- default
depends_on:
- db
env_file:
- .env
deploy:
labels:
- traefik.enable=true
- traefik.docker.network=${TRAEFIK_PUBLIC_NETWORK?Variable not set}
- traefik.constraint-label=${TRAEFIK_PUBLIC_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-http.rule=Host(`pgadmin.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-http.middlewares=${STACK_NAME?Variable not set}-https-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-https.rule=Host(`pgadmin.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-pgadmin-https.tls.certresolver=le
- traefik.http.services.${STACK_NAME?Variable not set}-pgadmin.loadbalancer.server.port=5050
queue:
image: rabbitmq:3
# Using the below image instead is required to enable the "Broker" tab in the flower UI:
# image: rabbitmq:3-management
#
# You also have to change the flower command
flower:
image: mher/flower
networks:
- ${TRAEFIK_PUBLIC_NETWORK?Variable not set}
- default
env_file:
- .env
command:
- "--broker=amqp://guest@queue:5672//"
# For the "Broker" tab to work in the flower UI, uncomment the following command argument,
# and change the queue service's image as well
# - "--broker_api=http://guest:guest@queue:15672/api//"
deploy:
labels:
- traefik.enable=true
- traefik.docker.network=${TRAEFIK_PUBLIC_NETWORK?Variable not set}
- traefik.constraint-label=${TRAEFIK_PUBLIC_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-http.rule=Host(`flower.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-http.middlewares=${STACK_NAME?Variable not set}-https-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-https.rule=Host(`flower.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-flower-https.tls.certresolver=le
- traefik.http.services.${STACK_NAME?Variable not set}-flower.loadbalancer.server.port=5555
backend:
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
depends_on:
- db
env_file:
- .env
environment:
- SERVER_NAME=${DOMAIN?Variable not set}
- SERVER_HOST=https://${DOMAIN?Variable not set}
# Allow explicit env var override for tests
- SMTP_HOST=${SMTP_HOST}
build:
context: ./backend
dockerfile: backend.dockerfile
args:
INSTALL_DEV: ${INSTALL_DEV-false}
deploy:
labels:
- traefik.enable=true
- traefik.constraint-label-stack=${TRAEFIK_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`)
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
celeryworker:
image: '${DOCKER_IMAGE_CELERYWORKER?Variable not set}:${TAG-latest}'
depends_on:
- db
- queue
env_file:
- .env
environment:
- SERVER_NAME=${DOMAIN?Variable not set}
- SERVER_HOST=https://${DOMAIN?Variable not set}
# Allow explicit env var override for tests
- SMTP_HOST=${SMTP_HOST?Variable not set}
build:
context: ./backend
dockerfile: celeryworker.dockerfile
args:
INSTALL_DEV: ${INSTALL_DEV-false}
frontend:
image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}'
build:
context: ./frontend
args:
FRONTEND_ENV: ${FRONTEND_ENV-production}
deploy:
labels:
- traefik.enable=true
- traefik.constraint-label-stack=${TRAEFIK_TAG?Variable not set}
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=PathPrefix(`/`)
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
volumes:
app-db-data:
networks:
traefik-public:
# Allow setting it to false for testing
external: ${TRAEFIK_PUBLIC_NETWORK_IS_EXTERNAL-true}

1
frontend/.dockerignore Executable file
View File

@ -0,0 +1 @@
node_modules

21
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

28
frontend/Dockerfile Normal file
View File

@ -0,0 +1,28 @@
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM tiangolo/node-frontend:10 as build-stage
WORKDIR /app
COPY package*.json /app/
RUN npm install
COPY ./ /app/
ARG FRONTEND_ENV=production
ENV VUE_APP_ENV=${FRONTEND_ENV}
# Comment out the next line to disable tests
RUN npm run test:unit
RUN npm run build
# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15
COPY --from=build-stage /app/dist/ /usr/share/nginx/html
COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.conf
COPY ./nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf

31
frontend/README.md Normal file
View File

@ -0,0 +1,31 @@
# frontend
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Run your tests
```
npm run test
```
### Lints and fixes files
```
npm run lint
```
### Run your unit tests
```
npm run test:unit
```

10
frontend/babel.config.js Normal file
View File

@ -0,0 +1,10 @@
module.exports = {
"presets": [
[
"@vue/cli-plugin-babel/preset",
{
"useBuiltIns": "entry"
}
]
]
}

View File

@ -0,0 +1,9 @@
location /api {
return 404;
}
location /docs {
return 404;
}
location /redoc {
return 404;
}

74
frontend/package.json Normal file
View File

@ -0,0 +1,74 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"lint": "vue-cli-service lint"
},
"dependencies": {
"@babel/polyfill": "^7.2.5",
"axios": "^0.18.0",
"core-js": "^3.4.3",
"register-service-worker": "^1.0.0",
"typesafe-vuex": "^3.1.1",
"vee-validate": "^2.1.7",
"vue": "^2.5.22",
"vue-class-component": "^6.0.0",
"vue-property-decorator": "^7.3.0",
"vue-router": "^3.0.2",
"vuetify": "^1.4.4",
"vuex": "^3.1.0"
},
"devDependencies": {
"@types/jest": "^23.3.13",
"@vue/cli-plugin-babel": "^4.1.1",
"@vue/cli-plugin-pwa": "^4.1.1",
"@vue/cli-plugin-typescript": "^4.1.1",
"@vue/cli-plugin-unit-jest": "^4.1.1",
"@vue/cli-service": "^4.1.1",
"@vue/test-utils": "^1.0.0-beta.28",
"babel-core": "7.0.0-bridge.0",
"ts-jest": "^23.10.5",
"typescript": "^3.2.4",
"vue-cli-plugin-vuetify": "^2.0.2",
"vue-template-compiler": "^2.5.22"
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 10"
],
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue",
"ts",
"tsx"
],
"transform": {
"^.+\\.vue$": "vue-jest",
".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
"^.+\\.tsx?$": "ts-jest"
},
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
},
"snapshotSerializers": [
"jest-serializer-vue"
],
"testMatch": [
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
],
"testURL": "http://localhost/"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Some files were not shown because too many files have changed in this diff Show More