-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 13bfea5
Showing
62 changed files
with
24,781 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2022 TestDriven.io | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# Developing a Single Page App with FastAPI and Vue.js | ||
|
||
### Want to learn how to build this? | ||
|
||
Check out the [post](https://testdriven.io/blog/developing-a-single-page-app-with-fastapi-and-vuejs). | ||
|
||
## Want to use this project? | ||
|
||
Build the images and spin up the containers: | ||
|
||
```sh | ||
$ docker-compose up -d --build | ||
``` | ||
|
||
Apply the migrations: | ||
|
||
```sh | ||
$ docker-compose exec backend aerich upgrade | ||
``` | ||
|
||
Ensure [http://localhost:5000](http://localhost:5000), [http://localhost:5000/docs](http://localhost:5000/docs), and [http://localhost:8080](http://localhost:8080) work as expected. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
version: '3.8' | ||
|
||
services: | ||
|
||
backend: | ||
build: ./services/backend | ||
ports: | ||
- 5000:5000 | ||
environment: | ||
- DATABASE_URL=postgres://hello_fastapi:hello_fastapi@db:5432/hello_fastapi_dev | ||
- SECRET_KEY=09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 | ||
volumes: | ||
- ./services/backend:/app | ||
command: uvicorn src.main:app --reload --host 0.0.0.0 --port 5000 | ||
depends_on: | ||
- db | ||
|
||
frontend: | ||
build: ./services/frontend | ||
volumes: | ||
- './services/frontend:/app' | ||
- '/app/node_modules' | ||
ports: | ||
- 8080:8080 | ||
|
||
db: | ||
image: postgres:15.1 | ||
expose: | ||
- 5432 | ||
environment: | ||
- POSTGRES_USER=hello_fastapi | ||
- POSTGRES_PASSWORD=hello_fastapi | ||
- POSTGRES_DB=hello_fastapi_dev | ||
volumes: | ||
- postgres_data:/var/lib/postgresql/data/ | ||
|
||
volumes: | ||
postgres_data: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
FROM python:3.11-buster | ||
|
||
RUN mkdir app | ||
WORKDIR /app | ||
|
||
ENV PATH="${PATH}:/root/.local/bin" | ||
ENV PYTHONPATH=. | ||
|
||
COPY requirements.txt . | ||
RUN pip install --upgrade pip | ||
RUN pip install -r requirements.txt | ||
|
||
# for migrations | ||
COPY migrations . | ||
COPY pyproject.toml . | ||
|
||
COPY src/ . |
32 changes: 32 additions & 0 deletions
32
services/backend/migrations/models/0_20221212182213_init.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
from tortoise import BaseDBAsyncClient | ||
|
||
|
||
async def upgrade(db: BaseDBAsyncClient) -> str: | ||
return """ | ||
CREATE TABLE IF NOT EXISTS "users" ( | ||
"id" SERIAL NOT NULL PRIMARY KEY, | ||
"username" VARCHAR(20) NOT NULL UNIQUE, | ||
"full_name" VARCHAR(50), | ||
"password" VARCHAR(128), | ||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
"modified_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP | ||
); | ||
CREATE TABLE IF NOT EXISTS "notes" ( | ||
"id" SERIAL NOT NULL PRIMARY KEY, | ||
"title" VARCHAR(225) NOT NULL, | ||
"content" TEXT NOT NULL, | ||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
"modified_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
"author_id" INT NOT NULL REFERENCES "users" ("id") ON DELETE CASCADE | ||
); | ||
CREATE TABLE IF NOT EXISTS "aerich" ( | ||
"id" SERIAL NOT NULL PRIMARY KEY, | ||
"version" VARCHAR(255) NOT NULL, | ||
"app" VARCHAR(100) NOT NULL, | ||
"content" JSONB NOT NULL | ||
);""" | ||
|
||
|
||
async def downgrade(db: BaseDBAsyncClient) -> str: | ||
return """ | ||
""" |
Binary file added
BIN
+1.39 KB
services/backend/migrations/models/__pycache__/0_20221212182213_init.cpython-311.pyc
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
[tool.aerich] | ||
tortoise_orm = "src.database.config.TORTOISE_ORM" | ||
location = "./migrations" | ||
src_folder = "./." |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
aerich==0.7.1 | ||
asyncpg==0.27.0 | ||
bcrypt==4.0.1 | ||
passlib==1.7.4 | ||
fastapi==0.88.0 | ||
python-jose==3.3.0 | ||
python-multipart==0.0.5 | ||
tortoise-orm==0.19.2 | ||
uvicorn==0.20.0 |
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
import os | ||
from datetime import datetime, timedelta | ||
from typing import Optional | ||
|
||
from fastapi import Depends, HTTPException, Request | ||
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel | ||
from fastapi.security import OAuth2 | ||
from fastapi.security.utils import get_authorization_scheme_param | ||
from jose import JWTError, jwt | ||
from tortoise.exceptions import DoesNotExist | ||
|
||
from src.schemas.token import TokenData | ||
from src.schemas.users import UserOutSchema | ||
from src.database.models import Users | ||
|
||
|
||
SECRET_KEY = os.environ.get("SECRET_KEY") | ||
ALGORITHM = "HS256" | ||
ACCESS_TOKEN_EXPIRE_MINUTES = 30 | ||
|
||
|
||
class OAuth2PasswordBearerCookie(OAuth2): | ||
def __init__( | ||
self, | ||
token_url: str, | ||
scheme_name: str = None, | ||
scopes: dict = None, | ||
auto_error: bool = True, | ||
): | ||
if not scopes: | ||
scopes = {} | ||
flows = OAuthFlowsModel(password={"tokenUrl": token_url, "scopes": scopes}) | ||
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error) | ||
|
||
async def __call__(self, request: Request) -> Optional[str]: | ||
authorization: str = request.cookies.get("Authorization") | ||
scheme, param = get_authorization_scheme_param(authorization) | ||
|
||
if not authorization or scheme.lower() != "bearer": | ||
if self.auto_error: | ||
raise HTTPException( | ||
status_code=401, | ||
detail="Not authenticated", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
else: | ||
return None | ||
|
||
return param | ||
|
||
|
||
security = OAuth2PasswordBearerCookie(token_url="/login") | ||
|
||
|
||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): | ||
to_encode = data.copy() | ||
|
||
if expires_delta: | ||
expire = datetime.utcnow() + expires_delta | ||
else: | ||
expire = datetime.utcnow() + timedelta(minutes=15) | ||
|
||
to_encode.update({"exp": expire}) | ||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | ||
|
||
return encoded_jwt | ||
|
||
|
||
async def get_current_user(token: str = Depends(security)): | ||
credentials_exception = HTTPException( | ||
status_code=401, | ||
detail="Could not validate credentials", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
|
||
try: | ||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | ||
username: str = payload.get("sub") | ||
if username is None: | ||
raise credentials_exception | ||
token_data = TokenData(username=username) | ||
except JWTError: | ||
raise credentials_exception | ||
|
||
try: | ||
user = await UserOutSchema.from_queryset_single( | ||
Users.get(username=token_data.username) | ||
) | ||
except DoesNotExist: | ||
raise credentials_exception | ||
|
||
return user |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
from fastapi import HTTPException, Depends, status | ||
from fastapi.security import OAuth2PasswordRequestForm | ||
from passlib.context import CryptContext | ||
from tortoise.exceptions import DoesNotExist | ||
|
||
from src.database.models import Users | ||
from src.schemas.users import UserDatabaseSchema | ||
|
||
|
||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | ||
|
||
|
||
def verify_password(plain_password, hashed_password): | ||
return pwd_context.verify(plain_password, hashed_password) | ||
|
||
|
||
def get_password_hash(password): | ||
return pwd_context.hash(password) | ||
|
||
|
||
async def get_user(username: str): | ||
return await UserDatabaseSchema.from_queryset_single(Users.get(username=username)) | ||
|
||
|
||
async def validate_user(user: OAuth2PasswordRequestForm = Depends()): | ||
try: | ||
db_user = await get_user(user.username) | ||
except DoesNotExist: | ||
raise HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, | ||
detail="Incorrect username or password", | ||
) | ||
|
||
if not verify_password(user.password, db_user.password): | ||
raise HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, | ||
detail="Incorrect username or password", | ||
) | ||
|
||
return db_user |
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from fastapi import HTTPException | ||
from tortoise.exceptions import DoesNotExist | ||
|
||
from src.database.models import Notes | ||
from src.schemas.notes import NoteOutSchema | ||
from src.schemas.token import Status | ||
|
||
|
||
async def get_notes(): | ||
return await NoteOutSchema.from_queryset(Notes.all()) | ||
|
||
|
||
async def get_note(note_id) -> NoteOutSchema: | ||
return await NoteOutSchema.from_queryset_single(Notes.get(id=note_id)) | ||
|
||
|
||
async def create_note(note, current_user) -> NoteOutSchema: | ||
note_dict = note.dict(exclude_unset=True) | ||
note_dict["author_id"] = current_user.id | ||
note_obj = await Notes.create(**note_dict) | ||
return await NoteOutSchema.from_tortoise_orm(note_obj) | ||
|
||
|
||
async def update_note(note_id, note, current_user) -> NoteOutSchema: | ||
try: | ||
db_note = await NoteOutSchema.from_queryset_single(Notes.get(id=note_id)) | ||
except DoesNotExist: | ||
raise HTTPException(status_code=404, detail=f"Note {note_id} not found") | ||
|
||
if db_note.author.id == current_user.id: | ||
await Notes.filter(id=note_id).update(**note.dict(exclude_unset=True)) | ||
return await NoteOutSchema.from_queryset_single(Notes.get(id=note_id)) | ||
|
||
raise HTTPException(status_code=403, detail=f"Not authorized to update") | ||
|
||
|
||
async def delete_note(note_id, current_user) -> Status: | ||
try: | ||
db_note = await NoteOutSchema.from_queryset_single(Notes.get(id=note_id)) | ||
except DoesNotExist: | ||
raise HTTPException(status_code=404, detail=f"Note {note_id} not found") | ||
|
||
if db_note.author.id == current_user.id: | ||
deleted_count = await Notes.filter(id=note_id).delete() | ||
if not deleted_count: | ||
raise HTTPException(status_code=404, detail=f"Note {note_id} not found") | ||
return Status(message=f"Deleted note {note_id}") | ||
|
||
raise HTTPException(status_code=403, detail=f"Not authorized to delete") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from fastapi import HTTPException | ||
from passlib.context import CryptContext | ||
from tortoise.exceptions import DoesNotExist, IntegrityError | ||
|
||
from src.database.models import Users | ||
from src.schemas.token import Status | ||
from src.schemas.users import UserOutSchema | ||
|
||
|
||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | ||
|
||
|
||
async def create_user(user) -> UserOutSchema: | ||
user.password = pwd_context.encrypt(user.password) | ||
|
||
try: | ||
user_obj = await Users.create(**user.dict(exclude_unset=True)) | ||
except IntegrityError: | ||
raise HTTPException(status_code=401, detail=f"Sorry, that username already exists.") | ||
|
||
return await UserOutSchema.from_tortoise_orm(user_obj) | ||
|
||
|
||
async def delete_user(user_id, current_user) -> Status: | ||
try: | ||
db_user = await UserOutSchema.from_queryset_single(Users.get(id=user_id)) | ||
except DoesNotExist: | ||
raise HTTPException(status_code=404, detail=f"User {user_id} not found") | ||
|
||
if db_user.id == current_user.id: | ||
deleted_count = await Users.filter(id=user_id).delete() | ||
if not deleted_count: | ||
raise HTTPException(status_code=404, detail=f"User {user_id} not found") | ||
return Status(message=f"Deleted user {user_id}") | ||
|
||
raise HTTPException(status_code=403, detail=f"Not authorized to delete") |
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import os | ||
|
||
|
||
TORTOISE_ORM = { | ||
"connections": {"default": os.environ.get("DATABASE_URL")}, | ||
"apps": { | ||
"models": { | ||
"models": [ | ||
"src.database.models", "aerich.models" | ||
], | ||
"default_connection": "default" | ||
} | ||
} | ||
} |
Oops, something went wrong.