From 52aa93d67c50a971a1d878ede648344307cf6a98 Mon Sep 17 00:00:00 2001 From: pptx704 Date: Sat, 14 Jun 2025 04:28:24 +0300 Subject: [PATCH] Initial commit --- .env.example | 7 +++ Dockerfile | 17 ++++++ README.md | 24 +++++++- alembic.ini | 110 +++++++++++++++++++++++++++++++++++ alembic/README | 1 + alembic/env.py | 82 ++++++++++++++++++++++++++ alembic/script.py.mako | 24 ++++++++ app/__init__.py | 0 app/const.py | 0 app/database.py | 21 +++++++ app/models.py | 7 +++ app/repositories/__init__.py | 0 app/repositories/auth.py | 6 ++ app/routers/__init__.py | 0 app/routers/auth.py | 14 +++++ app/schemas.py | 14 +++++ app/security.py | 52 +++++++++++++++++ app/settings.py | 13 +++++ app/utils.py | 0 docker-compose.yml | 24 ++++++++ main.py | 20 +++++++ requirements.txt | 8 +++ 22 files changed, 442 insertions(+), 2 deletions(-) create mode 100644 .env.example create mode 100644 Dockerfile create mode 100644 alembic.ini create mode 100644 alembic/README create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 app/__init__.py create mode 100644 app/const.py create mode 100644 app/database.py create mode 100644 app/models.py create mode 100644 app/repositories/__init__.py create mode 100644 app/repositories/auth.py create mode 100644 app/routers/__init__.py create mode 100644 app/routers/auth.py create mode 100644 app/schemas.py create mode 100644 app/security.py create mode 100644 app/settings.py create mode 100644 app/utils.py create mode 100644 docker-compose.yml create mode 100644 main.py create mode 100644 requirements.txt diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..708a869 --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +POSTGRES_USER= +POSTGRES_PASSWORD= +POSTGRES_DB= + +JWT_SECRET= +JWT_ALGORITHM= +JWT_EXPIRE_MINUTES= \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..14d209a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.14.0a3-slim + +# Turns off buffering for easier container logging +ENV PYTHONUNBUFFERED=1 + +COPY --from=ghcr.io/ufoscout/docker-compose-wait:latest /wait /wait + +# Install pip requirements +COPY requirements.txt . +RUN pip install --no-cache-dir --upgrade -r requirements.txt + +WORKDIR / +COPY . / + +EXPOSE 8000 + +CMD /wait; alembic upgrade head; uvicorn main:app --host 0.0.0.0 \ No newline at end of file diff --git a/README.md b/README.md index 9250cee..b2487eb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,23 @@ -# fastapi-template +# Omukk FastAPI Template -Template files for all fastapi projects \ No newline at end of file +Template repository for all FastAPI backend projects developed by Omukk. + +## Components +- Basic FastAPI dependencies +- Docker and Docker Compose for easier testing +- Alembic configuration for database migrations +- Initial codebase to start from + +## Using this template + +1. **Create a new repository from this template**: + - In Omukk Repos, navigate to [this repository](https://git.omukk.dev/pptx704/fastapi-template) + - Click the "Use this template" button at the top of the page + - Choose "Create a new repository" + - Fill in your new repository details and click "Create Repository" + +2. **Clone your new repository**: + ```bash + git clone git@git.omukk.dev//.git + cd + ``` diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..14d0c8e --- /dev/null +++ b/alembic.ini @@ -0,0 +1,110 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# 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. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# 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 diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..6ba805d --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,82 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +from app.const import SQLALCHEMY_DATABASE_URL + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +config.set_main_option("sqlalchemy.url", SQLALCHEMY_DATABASE_URL) +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +from app import models, database +target_metadata = database.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 run_migrations_offline() -> None: + """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 = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..55df286 --- /dev/null +++ b/alembic/script.py.mako @@ -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() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/const.py b/app/const.py new file mode 100644 index 0000000..e69de29 diff --git a/app/database.py b/app/database.py new file mode 100644 index 0000000..cdccadd --- /dev/null +++ b/app/database.py @@ -0,0 +1,21 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from .const import SQLALCHEMY_DATABASE_URL + + +engine = create_engine( + SQLALCHEMY_DATABASE_URL +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..8f1c795 --- /dev/null +++ b/app/models.py @@ -0,0 +1,7 @@ +from app.database import Base +from sqlalchemy.sql import func +import uuid +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, PrimaryKeyConstraint +from sqlalchemy.orm import relationship +from sqlalchemy.schema import Index diff --git a/app/repositories/__init__.py b/app/repositories/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/repositories/auth.py b/app/repositories/auth.py new file mode 100644 index 0000000..c608bb1 --- /dev/null +++ b/app/repositories/auth.py @@ -0,0 +1,6 @@ +from fastapi import HTTPException, status +from sqlalchemy.orm import Session + +from .. import schemas +from ..models import User +from ..security import get_password_hash, verify_password, create_jwt_token diff --git a/app/routers/__init__.py b/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routers/auth.py b/app/routers/auth.py new file mode 100644 index 0000000..6e5f9cf --- /dev/null +++ b/app/routers/auth.py @@ -0,0 +1,14 @@ +from app import database, schemas +from fastapi import APIRouter, Depends, status +from sqlalchemy.orm import Session + +from ..repositories import auth +from .. import schemas + +from ..security import get_user +from ..database import get_db + +router = APIRouter( + prefix = "", + tags = ['auth'] +) diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..1ab3528 --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,14 @@ +from typing import List, Optional +from pydantic import BaseModel, EmailStr +import uuid +import enum +import datetime + +class BaseResponse(BaseModel): + message: str + +class User(BaseModel): + id: uuid.UUID + + class Config: + orm_mode = True diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..98e1b34 --- /dev/null +++ b/app/security.py @@ -0,0 +1,52 @@ +import os +from passlib.context import CryptContext +import jwt +from datetime import datetime, timedelta, UTC + +from app.models import User + +from fastapi import Security, HTTPException +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from .database import get_db +from .models import User +from .settings import settings + +from . import schemas + +pwd_context = CryptContext(schemes=["bcrypt"]) + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + +def create_jwt_token(data: dict) -> str: + _ed = timedelta(minutes=settings.JWT_EXPIRE_MINUTES) + iat = datetime.now(UTC) + exp = datetime.now(UTC) + _ed + token_payload = data + token_payload.update({"iat": iat, "exp": exp}) + + token = jwt.encode(token_payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM) + + return token + +def get_user_from_token(token: str) -> schemas.User: + try: + payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM]) + except jwt.ExpiredSignatureError: + raise HTTPException(status_code=401, detail="Token has expired") + except jwt.JWTError: + raise HTTPException(status_code=401, detail="Invalid authentication credentials") + + user_id = payload.get("user_id") + + ... + +def get_user(authorization: HTTPAuthorizationCredentials = Security(HTTPBearer())) -> schemas.User: + if authorization.scheme.lower() != "bearer": + raise HTTPException(status_code=401, detail="Invalid authentication scheme") + + token = authorization.credentials + return get_user_from_token(token) diff --git a/app/settings.py b/app/settings.py new file mode 100644 index 0000000..f2433e5 --- /dev/null +++ b/app/settings.py @@ -0,0 +1,13 @@ +import os +from pydantic_settings import BaseSettings +from dotenv import load_dotenv + +load_dotenv() + +class Settings(BaseSettings): + JWT_SECRET: str + JWT_ALGORITHM: str + JWT_EXPIRE_MINUTES: int + SQLALCHEMY_DATABASE_URL: str + +settings = Settings() diff --git a/app/utils.py b/app/utils.py new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..6984f70 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,24 @@ +version: '3.1' + +services: + backend: + image: fastapi + build: + context: . + dockerfile: Dockerfile + ports: + - "8000:8000" + environment: + - JWT_SECRET=${JWT_SECRET} + - JWT_ALGORITHM=${JWT_ALGORITHM:-HS256} + - JWT_EXPIRE_MINUTES=${JWT_EXPIRE_MINUTES:-60} + - DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB} + - WAIT_HOSTS=db:5432 + depends_on: + - db + db: + image: postgres:15.3 + environment: + - POSTGRES_USER=${POSTGRES_USER} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_DB=${POSTGRES_DB} \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..5c9b213 --- /dev/null +++ b/main.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.routers import auth + +app = FastAPI() + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_methods=["*"], + allow_headers=["*"] +) + + +@app.get("/") +async def index() -> str: + return "Version 0.0.1" + +app.include_router(auth.router) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1f97bca --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +bcrypt==4.0.1 +fastapi[standard]~=0.115.12 +pydantic-settings~=2.9.1 +sqlalchemy~=2.0.41 +passlib~=1.7.4 +pyjwt~=2.10.1 +alembic~=1.16.1 +python-dotenv~=1.1.0 \ No newline at end of file