refactor: improve code structure and optimize key functions

This commit is contained in:
Cheng Zhou
2025-12-16 15:55:08 +08:00
commit 223d445a94
1290 changed files with 1361 additions and 0 deletions
View File
View File
View File
+32
View File
@@ -0,0 +1,32 @@
from datetime import timedelta
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
from app.core.config import settings
from app.core.security import create_access_token
from app.schemas.user import Token
class LoginRequest(BaseModel):
username: str = Field(min_length=1)
password: str = Field(min_length=1)
router = APIRouter()
@router.post("/login", response_model=Token)
async def login_for_access_token(payload: LoginRequest) -> Token:
if not (payload.username == "admin" and payload.password == "admin"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
)
access_token = create_access_token(
subject="00000000-0000-0000-0000-000000000001",
role="PM",
expires_delta=timedelta(minutes=settings.JWT_EXPIRE_MINUTES),
)
return Token(access_token=access_token, token_type="bearer")
+6
View File
@@ -0,0 +1,6 @@
from fastapi import APIRouter
from app.api.v1 import auth
api_router = APIRouter()
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
View File
+22
View File
@@ -0,0 +1,22 @@
from functools import lru_cache
from typing import Literal
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
DATABASE_URL: str = Field(default="postgresql+asyncpg://postgres:postgres@db:5432/ctms")
ENV: Literal["development", "production", "test"] = "development"
JWT_SECRET_KEY: str = "dev-secret"
JWT_EXPIRE_MINUTES: int = 60
@lru_cache
def get_settings() -> Settings:
return Settings()
settings = get_settings()
+26
View File
@@ -0,0 +1,26 @@
from typing import Annotated, AsyncGenerator
from fastapi import Depends, HTTPException, status
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.security import decode_access_token, oauth2_scheme
from app.db.session import SessionLocal
from app.schemas.user import TokenPayload
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield session
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> TokenPayload:
payload = decode_access_token(token)
try:
return TokenPayload(**payload)
except ValidationError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
) from exc
+30
View File
@@ -0,0 +1,30 @@
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional
from fastapi import HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from app.core.config import settings
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", scheme_name="Bearer")
def create_access_token(*, subject: str, role: str, expires_delta: Optional[timedelta] = None) -> str:
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=settings.JWT_EXPIRE_MINUTES))
to_encode: Dict[str, Any] = {"sub": subject, "role": role, "exp": expire}
return jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> Dict[str, Any]:
try:
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM])
except JWTError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
) from exc
return payload
View File
+30
View File
@@ -0,0 +1,30 @@
from typing import Sequence
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.user import User
from app.schemas.user import UserCreate
async def get_by_username(db: AsyncSession, username: str) -> User | None:
result = await db.execute(select(User).where(User.username == username))
return result.scalar_one_or_none()
async def create(db: AsyncSession, user_in: UserCreate, hashed_password: str) -> User:
user = User(
username=user_in.username,
hashed_password=hashed_password,
role=user_in.role,
is_active=user_in.is_active,
)
db.add(user)
await db.commit()
await db.refresh(user)
return user
async def list_users(db: AsyncSession, limit: int = 100) -> Sequence[User]:
result = await db.execute(select(User).limit(limit))
return result.scalars().all()
View File
+5
View File
@@ -0,0 +1,5 @@
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
+6
View File
@@ -0,0 +1,6 @@
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.config import settings
engine = create_async_engine(settings.DATABASE_URL, future=True, echo=False)
SessionLocal = async_sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
+31
View File
@@ -0,0 +1,31 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.router import api_router
from app.core.config import settings
def create_app() -> FastAPI:
app = FastAPI(
title="CTMS API",
version="0.1.0",
debug=settings.ENV == "development",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health", tags=["health"])
async def health() -> dict[str, str]:
return {"status": "ok"}
app.include_router(api_router, prefix="/api/v1")
return app
app = create_app()
View File
+19
View File
@@ -0,0 +1,19 @@
import uuid
from datetime import datetime
from sqlalchemy import Boolean, DateTime, String, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base
class User(Base):
__tablename__ = "users"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
username: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
role: Mapped[str] = mapped_column(String(20), nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default="true")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
View File
+41
View File
@@ -0,0 +1,41 @@
import uuid
from datetime import datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
class UserBase(BaseModel):
username: str = Field(min_length=1)
role: Literal["PM", "CRA", "PV", "IMP"]
is_active: bool = True
class UserCreate(UserBase):
password: str = Field(min_length=1)
class UserRead(UserBase):
id: uuid.UUID
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class UserInDB(UserBase):
id: uuid.UUID
hashed_password: str
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class Token(BaseModel):
access_token: str
token_type: str = "bearer"
class TokenPayload(BaseModel):
sub: uuid.UUID
role: str
exp: Optional[int] = None