Initial commit
This commit is contained in:
9
src/__init__.py
Normal file
9
src/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
from src.users.router import users_router
|
||||
from src.maps.router import maps_router
|
||||
|
||||
app.include_router(users_router, prefix="/users")
|
||||
app.include_router(maps_router, prefix="/maps")
|
||||
1
src/alembic/README
Normal file
1
src/alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
85
src/alembic/env.py
Normal file
85
src/alembic/env.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
from sqlmodel import SQLModel
|
||||
import sqlmodel
|
||||
|
||||
from src.db import Base
|
||||
from src.utils.config import get
|
||||
|
||||
# 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', get('db', 'connection_string'))
|
||||
|
||||
# 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
|
||||
target_metadata = SQLModel.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()
|
||||
29
src/alembic/script.py.mako
Normal file
29
src/alembic/script.py.mako
Normal file
@@ -0,0 +1,29 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
48
src/alembic/versions/2607b8f9586f_.py
Normal file
48
src/alembic/versions/2607b8f9586f_.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 2607b8f9586f
|
||||
Revises:
|
||||
Create Date: 2025-10-04 15:15:16.698698
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlmodel
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '2607b8f9586f'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('user',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('password', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_user_name'), 'user', ['name'], unique=True)
|
||||
op.create_table('waypoint',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('x', sa.Float(), nullable=False),
|
||||
sa.Column('y', sa.Float(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('waypoint')
|
||||
op.drop_index(op.f('ix_user_name'), table_name='user')
|
||||
op.drop_table('user')
|
||||
# ### end Alembic commands ###
|
||||
16
src/db/__init__.py
Normal file
16
src/db/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
from src.utils.config import get
|
||||
|
||||
engine = create_engine(get('db', 'connection_string'), echo=True)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
0
src/maps/__init__.py
Normal file
0
src/maps/__init__.py
Normal file
10
src/maps/models.py
Normal file
10
src/maps/models.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from typing import Optional
|
||||
from sqlmodel import SQLModel, Field
|
||||
|
||||
class WaypointBase(SQLModel):
|
||||
name: str
|
||||
x: float
|
||||
y: float
|
||||
|
||||
class Waypoint(WaypointBase, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True, sa_column_kwargs={"autoincrement": True})
|
||||
37
src/maps/router.py
Normal file
37
src/maps/router.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
from sqlmodel import select
|
||||
|
||||
from src.db import get_db
|
||||
from src.maps.models import Waypoint
|
||||
from src.maps.schemas import WaypointCreate, WaypointResponse
|
||||
from src.utils.decorators import auth_required
|
||||
|
||||
maps_router = APIRouter()
|
||||
|
||||
@auth_required()
|
||||
@maps_router.post("/waypoints", response_model=WaypointResponse)
|
||||
def create_waypoint(waypoint: WaypointCreate, db: Session = Depends(get_db)):
|
||||
db_wp = Waypoint.model_validate(waypoint)
|
||||
db.add(db_wp)
|
||||
db.commit()
|
||||
db.refresh(db_wp)
|
||||
return db_wp
|
||||
|
||||
|
||||
@auth_required()
|
||||
@maps_router.get("/waypoints", response_model=List[WaypointResponse])
|
||||
def get_waypoints(db: Session = Depends(get_db)):
|
||||
waypoints = db.execute(select(Waypoint)).scalars().all()
|
||||
return waypoints
|
||||
|
||||
|
||||
@auth_required()
|
||||
@maps_router.get("/waypoints/{waypoint_id}", response_model=WaypointResponse)
|
||||
def get_waypoint(waypoint_id: int, db: Session = Depends(get_db)):
|
||||
wp = db.get(Waypoint, waypoint_id)
|
||||
if not wp:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Waypoint not found")
|
||||
return wp
|
||||
12
src/maps/schemas.py
Normal file
12
src/maps/schemas.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class WaypointCreate(BaseModel):
|
||||
name: str
|
||||
x: float
|
||||
y: float
|
||||
|
||||
class WaypointResponse(WaypointCreate):
|
||||
id: int
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
85
src/maps/tests.py
Normal file
85
src/maps/tests.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import StaticPool
|
||||
from sqlmodel import SQLModel, create_engine, Session
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from src import app, maps_router
|
||||
from src.maps.models import Waypoint
|
||||
from src.db import get_db
|
||||
|
||||
# --- Setup in-memory SQLite ---
|
||||
TEST_DATABASE_URL = "sqlite:///:memory:"
|
||||
engine = create_engine(
|
||||
TEST_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool # <-- crucial for in-memory DB
|
||||
)
|
||||
TestingSessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
# --- Override dependency ---
|
||||
def override_get_db():
|
||||
db = TestingSessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
# Include router (no need to check prefix)
|
||||
app.include_router(maps_router, prefix="/maps")
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
# --- Fixture to create tables ---
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def setup_db():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
yield
|
||||
SQLModel.metadata.drop_all(engine)
|
||||
|
||||
# --- Bypass auth decorator for tests ---
|
||||
def fake_auth_dependency():
|
||||
return lambda: True
|
||||
|
||||
# Monkeypatch your auth_required to do nothing in tests
|
||||
from src.utils.decorators import auth_required
|
||||
auth_required = lambda *args, **kwargs: (lambda x: x)
|
||||
|
||||
# --- Tests ---
|
||||
def test_create_waypoint():
|
||||
payload = {"name": "TestPoint", "x": 10.5, "y": 20.5}
|
||||
response = client.post("/maps/waypoints", json=payload)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["name"] == payload["name"]
|
||||
assert data["x"] == payload["x"]
|
||||
assert data["y"] == payload["y"]
|
||||
assert "id" in data
|
||||
|
||||
def test_get_waypoints():
|
||||
response = client.get("/maps/waypoints")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) >= 1
|
||||
|
||||
def test_get_waypoint_by_id():
|
||||
# Create waypoint first
|
||||
payload = {"name": "Point1", "x": 1.0, "y": 2.0}
|
||||
create_resp = client.post("/maps/waypoints", json=payload)
|
||||
wp_id = create_resp.json()["id"]
|
||||
|
||||
# Fetch by ID
|
||||
response = client.get(f"/maps/waypoints/{wp_id}")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["id"] == wp_id
|
||||
assert data["name"] == payload["name"]
|
||||
|
||||
def test_get_waypoint_not_found():
|
||||
response = client.get("/maps/waypoints/9999")
|
||||
assert response.status_code == 404
|
||||
data = response.json()
|
||||
assert data["detail"] == "Waypoint not found"
|
||||
0
src/users/__init__.py
Normal file
0
src/users/__init__.py
Normal file
31
src/users/models.py
Normal file
31
src/users/models.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from sqlmodel import SQLModel, Field, Session
|
||||
from passlib.context import CryptContext
|
||||
from typing import Optional
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
class User(SQLModel, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
name: str = Field(index=True, unique=True)
|
||||
password: str
|
||||
|
||||
@staticmethod
|
||||
def make_password(plain_password: str) -> str:
|
||||
return pwd_context.hash(plain_password)
|
||||
|
||||
def verify_password(self, plain_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, self.password)
|
||||
|
||||
@classmethod
|
||||
def add_user(cls, session: Session, name: str, password: str):
|
||||
try:
|
||||
user = cls(name=name, password=cls.make_password(password))
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
print(f"User '{name}' added successfully.")
|
||||
return user
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f"Error: Could not add user '{name}': {e}")
|
||||
31
src/users/router.py
Normal file
31
src/users/router.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from fastapi import Request
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from src.db import get_db
|
||||
from src.users.models import User
|
||||
from src.users.schemas import LoginRequest
|
||||
from src.utils.decorators import auth_required
|
||||
from src.utils.jwt import create_access_token
|
||||
|
||||
|
||||
users_router = APIRouter()
|
||||
|
||||
|
||||
@users_router.post("/login")
|
||||
def login(request: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.name == request.name).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
|
||||
if not user.verify_password(request.password):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
|
||||
access_token = create_access_token(data={"sub": user.id})
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
@users_router.get("/info")
|
||||
@auth_required()
|
||||
async def get_info(request: Request):
|
||||
user_name = request.state.user.name
|
||||
return {"message": f"Hello, {user_name}!"}
|
||||
6
src/users/schemas.py
Normal file
6
src/users/schemas.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
name: str
|
||||
password: str
|
||||
0
src/utils/__init__.py
Normal file
0
src/utils/__init__.py
Normal file
35
src/utils/config.py
Normal file
35
src/utils/config.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import json
|
||||
import os
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class Environment(Enum):
|
||||
PRODUCTION = 'production'
|
||||
DEVELOPMENT = 'development'
|
||||
|
||||
|
||||
def get_config_file() -> dict:
|
||||
with open('config.json', 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def get(*keys: str) -> Any:
|
||||
env_var = '__'.join(keys).upper()
|
||||
if env_var in os.environ:
|
||||
return os.environ[env_var]
|
||||
|
||||
config = get_config_file()
|
||||
for key in keys:
|
||||
if not isinstance(config, dict) or key not in config:
|
||||
raise KeyError(f"Key path {' -> '.join(keys)} not found in config.")
|
||||
config = config[key]
|
||||
|
||||
return config
|
||||
|
||||
def get_environment() -> Environment:
|
||||
value = get('environment')
|
||||
try:
|
||||
return Environment(value)
|
||||
except ValueError:
|
||||
raise ValueError(f"Invalid environment value '{value}' in config. Must be one of {[e.value for e in Environment]}")
|
||||
88
src/utils/decorators.py
Normal file
88
src/utils/decorators.py
Normal file
@@ -0,0 +1,88 @@
|
||||
from functools import wraps
|
||||
from fastapi import Request, HTTPException, status
|
||||
import jwt
|
||||
|
||||
from src.utils.config import get
|
||||
from src.users.models import User
|
||||
from src.db import get_db
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
SECRET_KEY = get('jwt_secret')
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
def auth_required():
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request: Request | None = kwargs.get("request")
|
||||
|
||||
# Try to locate Request in args if not found in kwargs
|
||||
if not request:
|
||||
for arg in args:
|
||||
if isinstance(arg, Request):
|
||||
request = arg
|
||||
break
|
||||
|
||||
if not request:
|
||||
raise Exception(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Request object not found"
|
||||
)
|
||||
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header or not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authorization header missing or invalid",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token payload invalid",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has expired",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
|
||||
# Optional: Fetch the user from the DB and pass it to the route
|
||||
try:
|
||||
db: Session = kwargs.get("db") or next(get_db())
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Database error"
|
||||
)
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
|
||||
# Inject user into request.state
|
||||
request.state.user = user
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
21
src/utils/jwt.py
Normal file
21
src/utils/jwt.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from datetime import datetime, timedelta
|
||||
import jwt
|
||||
|
||||
from src.utils.config import get
|
||||
|
||||
SECRET_KEY = get('jwt_secret')
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 6000
|
||||
|
||||
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
|
||||
if "sub" in to_encode:
|
||||
to_encode["sub"] = str(to_encode["sub"])
|
||||
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode.update({"exp": expire})
|
||||
|
||||
token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
return token
|
||||
|
||||
Reference in New Issue
Block a user