feat: add unified linting scripts and git hooks for code quality enforcement

- Introduced `lint` and `lint-fix` applications in `flake.nix` for unified linting of backend (Python) and frontend (TypeScript/Svelte) code.
- Added `scripts/lint.sh` for manual linting execution.
- Created `scripts/install-hooks.sh` to set up git hooks for automatic linting before commits and optional tests before pushes.
- Updated `README.md` with instructions for using the new linting features and git hooks.
This commit is contained in:
Danilo Reyes
2025-11-02 00:08:37 -06:00
parent 4c94793aba
commit b55ac51fe2
32 changed files with 470 additions and 171 deletions

View File

@@ -1,4 +1,3 @@
"""Reference Board Viewer - Backend API."""
__version__ = "1.0.0"

View File

@@ -1,4 +1,5 @@
"""Authentication endpoints."""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
@@ -16,37 +17,31 @@ router = APIRouter(prefix="/auth", tags=["auth"])
def register_user(user_data: UserCreate, db: Session = Depends(get_db)):
"""
Register a new user.
Args:
user_data: User registration data
db: Database session
Returns:
Created user information
Raises:
HTTPException: If email already exists or password is weak
"""
repo = UserRepository(db)
# Check if email already exists
if repo.email_exists(user_data.email):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Email already registered"
)
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
# Validate password strength
is_valid, error_message = validate_password_strength(user_data.password)
if not is_valid:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error_message
)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_message)
# Create user
user = repo.create_user(email=user_data.email, password=user_data.password)
return UserResponse.model_validate(user)
@@ -54,22 +49,22 @@ def register_user(user_data: UserCreate, db: Session = Depends(get_db)):
def login_user(login_data: UserLogin, db: Session = Depends(get_db)):
"""
Login user and return JWT token.
Args:
login_data: Login credentials
db: Database session
Returns:
JWT access token and user information
Raises:
HTTPException: If credentials are invalid
"""
repo = UserRepository(db)
# Get user by email
user = repo.get_user_by_email(login_data.email)
# Verify user exists and password is correct
if not user or not verify_password(login_data.password, user.password_hash):
raise HTTPException(
@@ -77,34 +72,26 @@ def login_user(login_data: UserLogin, db: Session = Depends(get_db)):
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Check if user is active
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="User account is deactivated"
)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User account is deactivated")
# Create access token
access_token = create_access_token(user_id=user.id, email=user.email)
return TokenResponse(
access_token=access_token,
token_type="bearer",
user=UserResponse.model_validate(user)
)
return TokenResponse(access_token=access_token, token_type="bearer", user=UserResponse.model_validate(user))
@router.get("/me", response_model=UserResponse)
def get_current_user_info(current_user: User = Depends(get_current_user)):
"""
Get current authenticated user information.
Args:
current_user: Current authenticated user (from JWT)
Returns:
Current user information
"""
return UserResponse.model_validate(current_user)

View File

@@ -1,2 +1 @@
"""Authentication module."""

View File

@@ -1,6 +1,6 @@
"""JWT token generation and validation."""
from datetime import datetime, timedelta
from typing import Optional
from uuid import UUID
from jose import JWTError, jwt
@@ -8,15 +8,15 @@ from jose import JWTError, jwt
from app.core.config import settings
def create_access_token(user_id: UUID, email: str, expires_delta: Optional[timedelta] = None) -> str:
def create_access_token(user_id: UUID, email: str, expires_delta: timedelta | None = None) -> str:
"""
Create a new JWT access token.
Args:
user_id: User's UUID
email: User's email address
expires_delta: Optional custom expiration time
Returns:
Encoded JWT token string
"""
@@ -24,26 +24,20 @@ def create_access_token(user_id: UUID, email: str, expires_delta: Optional[timed
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {
"sub": str(user_id),
"email": email,
"exp": expire,
"iat": datetime.utcnow(),
"type": "access"
}
to_encode = {"sub": str(user_id), "email": email, "exp": expire, "iat": datetime.utcnow(), "type": "access"}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def decode_access_token(token: str) -> Optional[dict]:
def decode_access_token(token: str) -> dict | None:
"""
Decode and validate a JWT access token.
Args:
token: JWT token string to decode
Returns:
Decoded token payload if valid, None otherwise
"""
@@ -52,4 +46,3 @@ def decode_access_token(token: str) -> Optional[dict]:
return payload
except JWTError:
return None

View File

@@ -1,9 +1,7 @@
"""User repository for database operations."""
from typing import Optional
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from app.auth.security import hash_password
@@ -16,7 +14,7 @@ class UserRepository:
def __init__(self, db: Session):
"""
Initialize repository.
Args:
db: Database session
"""
@@ -25,48 +23,45 @@ class UserRepository:
def create_user(self, email: str, password: str) -> User:
"""
Create a new user.
Args:
email: User email (will be lowercased)
password: Plain text password (will be hashed)
Returns:
Created user instance
"""
email = email.lower()
password_hash = hash_password(password)
user = User(
email=email,
password_hash=password_hash
)
user = User(email=email, password_hash=password_hash)
self.db.add(user)
self.db.commit()
self.db.refresh(user)
return user
def get_user_by_email(self, email: str) -> Optional[User]:
def get_user_by_email(self, email: str) -> User | None:
"""
Get user by email address.
Args:
email: User email to search for
Returns:
User if found, None otherwise
"""
email = email.lower()
return self.db.query(User).filter(User.email == email).first()
def get_user_by_id(self, user_id: UUID) -> Optional[User]:
def get_user_by_id(self, user_id: UUID) -> User | None:
"""
Get user by ID.
Args:
user_id: User UUID
Returns:
User if found, None otherwise
"""
@@ -75,13 +70,12 @@ class UserRepository:
def email_exists(self, email: str) -> bool:
"""
Check if email already exists.
Args:
email: Email to check
Returns:
True if email exists, False otherwise
"""
email = email.lower()
return self.db.query(User).filter(User.email == email).first() is not None

View File

@@ -1,6 +1,6 @@
"""Authentication schemas for request/response validation."""
from datetime import datetime
from typing import Optional
from uuid import UUID
from pydantic import BaseModel, EmailStr, Field
@@ -42,4 +42,3 @@ class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
user: UserResponse

View File

@@ -1,5 +1,7 @@
"""Password hashing utilities using passlib."""
import re
from passlib.context import CryptContext
# Create password context for hashing and verification
@@ -9,10 +11,10 @@ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
"""
Hash a password using bcrypt.
Args:
password: Plain text password
Returns:
Hashed password string
"""
@@ -22,11 +24,11 @@ def hash_password(password: str) -> str:
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify a plain password against a hashed password.
Args:
plain_password: Plain text password to verify
hashed_password: Hashed password from database
Returns:
True if password matches, False otherwise
"""
@@ -36,30 +38,29 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
def validate_password_strength(password: str) -> tuple[bool, str]:
"""
Validate password meets complexity requirements.
Requirements:
- At least 8 characters
- At least 1 uppercase letter
- At least 1 lowercase letter
- At least 1 number
Args:
password: Plain text password to validate
Returns:
Tuple of (is_valid, error_message)
"""
if len(password) < 8:
return False, "Password must be at least 8 characters long"
if not re.search(r"[A-Z]", password):
return False, "Password must contain at least one uppercase letter"
if not re.search(r"[a-z]", password):
return False, "Password must contain at least one lowercase letter"
if not re.search(r"\d", password):
return False, "Password must contain at least one number"
return True, ""
return True, ""

View File

@@ -1,2 +1 @@
"""Core application modules."""

View File

@@ -90,4 +90,3 @@ def get_settings() -> Settings:
# Export settings instance
settings = get_settings()

View File

@@ -1,6 +1,6 @@
"""Dependency injection utilities."""
from typing import Annotated, Generator
from typing import Annotated
from uuid import UUID
from fastapi import Depends, HTTPException, status
@@ -19,33 +19,32 @@ security = HTTPBearer()
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)
) -> User:
"""
Get current authenticated user from JWT token.
Args:
credentials: HTTP Authorization Bearer token
db: Database session
Returns:
Current authenticated user
Raises:
HTTPException: If token is invalid or user not found
"""
# Decode token
token = credentials.credentials
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Extract user ID from token
user_id_str: str = payload.get("sub")
if user_id_str is None:
@@ -54,7 +53,7 @@ def get_current_user(
detail="Invalid token payload",
headers={"WWW-Authenticate": "Bearer"},
)
try:
user_id = UUID(user_id_str)
except ValueError:
@@ -62,23 +61,19 @@ def get_current_user(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid user ID in token",
headers={"WWW-Authenticate": "Bearer"},
)
) from None
# Get user from database
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
headers={"WWW-Authenticate": "Bearer"},
)
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="User account is deactivated"
)
return user
if not user.is_active:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User account is deactivated")
return user

View File

@@ -65,4 +65,3 @@ class UnsupportedFileTypeError(WebRefException):
def __init__(self, file_type: str, allowed_types: list[str]):
message = f"File type '{file_type}' not supported. Allowed types: {', '.join(allowed_types)}"
super().__init__(message, status_code=415)

View File

@@ -8,27 +8,24 @@ from app.core.config import settings
def setup_logging() -> None:
"""Configure application logging."""
# Get log level from settings
log_level = getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO)
# Configure root logger
logging.basicConfig(
level=log_level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[
logging.StreamHandler(sys.stdout)
],
handlers=[logging.StreamHandler(sys.stdout)],
)
# Set library log levels
logging.getLogger("uvicorn").setLevel(logging.INFO)
logging.getLogger("uvicorn.access").setLevel(logging.INFO)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("boto3").setLevel(logging.WARNING)
logging.getLogger("botocore").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
logger.info(f"Logging configured with level: {settings.LOG_LEVEL}")

View File

@@ -2,7 +2,6 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from app.core.config import settings
@@ -26,4 +25,3 @@ def setup_middleware(app: FastAPI) -> None:
# TrustedHostMiddleware,
# allowed_hosts=["yourdomain.com", "*.yourdomain.com"]
# )

View File

@@ -10,13 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
class BaseSchema(BaseModel):
"""Base schema with common configuration."""
model_config = ConfigDict(
from_attributes=True,
populate_by_name=True,
json_schema_extra={
"example": {}
}
)
model_config = ConfigDict(from_attributes=True, populate_by_name=True, json_schema_extra={"example": {}})
class TimestampSchema(BaseSchema):
@@ -61,4 +55,3 @@ class PaginatedResponse(BaseSchema):
items: list[Any] = Field(..., description="List of items")
pagination: PaginationSchema = Field(..., description="Pagination metadata")

View File

@@ -116,4 +116,3 @@ class StorageClient:
# Global storage client instance
storage_client = StorageClient()

View File

@@ -1,2 +1 @@
"""Database models and session management."""

View File

@@ -14,10 +14,10 @@ class Base(DeclarativeBase):
# Generate __tablename__ automatically from class name
@declared_attr.directive
def __tablename__(cls) -> str:
def __tablename__(self) -> str:
"""Generate table name from class name."""
# Convert CamelCase to snake_case
name = cls.__name__
name = self.__name__
return "".join(["_" + c.lower() if c.isupper() else c for c in name]).lstrip("_")
# Common columns for all models
@@ -27,4 +27,3 @@ class Base(DeclarativeBase):
def dict(self) -> dict[str, Any]:
"""Convert model to dictionary."""
return {c.name: getattr(self, c.name) for c in self.__table__.columns}

View File

@@ -1,11 +1,12 @@
"""Database models."""
from app.database.models.user import User
from app.database.models.board import Board
from app.database.models.image import Image
from app.database.models.board_image import BoardImage
from app.database.models.group import Group
from app.database.models.share_link import ShareLink
from app.database.models.comment import Comment
from app.database.models.group import Group
from app.database.models.image import Image
from app.database.models.share_link import ShareLink
from app.database.models.user import User
__all__ = [
"User",

View File

@@ -1,6 +1,8 @@
"""Board model for reference boards."""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import relationship
@@ -17,11 +19,7 @@ class Board(Base):
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
title = Column(String(255), nullable=False)
description = Column(Text, nullable=True)
viewport_state = Column(
JSONB,
nullable=False,
default={"x": 0, "y": 0, "zoom": 1.0, "rotation": 0}
)
viewport_state = Column(JSONB, nullable=False, default={"x": 0, "y": 0, "zoom": 1.0, "rotation": 0})
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
is_deleted = Column(Boolean, nullable=False, default=False)
@@ -35,4 +33,3 @@ class Board(Base):
def __repr__(self) -> str:
return f"<Board(id={self.id}, title={self.title})>"

View File

@@ -1,6 +1,8 @@
"""BoardImage junction model."""
import uuid
from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import relationship
@@ -26,17 +28,15 @@ class BoardImage(Base):
"opacity": 1.0,
"flipped_h": False,
"flipped_v": False,
"greyscale": False
}
"greyscale": False,
},
)
z_order = Column(Integer, nullable=False, default=0, index=True)
group_id = Column(UUID(as_uuid=True), ForeignKey("groups.id", ondelete="SET NULL"), nullable=True, index=True)
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
__table_args__ = (
UniqueConstraint("board_id", "image_id", name="uq_board_image"),
)
__table_args__ = (UniqueConstraint("board_id", "image_id", name="uq_board_image"),)
# Relationships
board = relationship("Board", back_populates="board_images")
@@ -45,4 +45,3 @@ class BoardImage(Base):
def __repr__(self) -> str:
return f"<BoardImage(board_id={self.board_id}, image_id={self.image_id})>"

View File

@@ -1,6 +1,8 @@
"""Comment model for board comments."""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import relationship
@@ -15,7 +17,9 @@ class Comment(Base):
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
board_id = Column(UUID(as_uuid=True), ForeignKey("boards.id", ondelete="CASCADE"), nullable=False, index=True)
share_link_id = Column(UUID(as_uuid=True), ForeignKey("share_links.id", ondelete="SET NULL"), nullable=True, index=True)
share_link_id = Column(
UUID(as_uuid=True), ForeignKey("share_links.id", ondelete="SET NULL"), nullable=True, index=True
)
author_name = Column(String(100), nullable=False)
content = Column(Text, nullable=False)
position = Column(JSONB, nullable=True) # Optional canvas position
@@ -28,4 +32,3 @@ class Comment(Base):
def __repr__(self) -> str:
return f"<Comment(id={self.id}, author={self.author_name})>"

View File

@@ -1,6 +1,8 @@
"""Group model for image grouping."""
import uuid
from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
@@ -27,4 +29,3 @@ class Group(Base):
def __repr__(self) -> str:
return f"<Group(id={self.id}, name={self.name})>"

View File

@@ -1,6 +1,8 @@
"""Image model for uploaded images."""
import uuid
from datetime import datetime
from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import relationship
@@ -31,4 +33,3 @@ class Image(Base):
def __repr__(self) -> str:
return f"<Image(id={self.id}, filename={self.filename})>"

View File

@@ -1,6 +1,8 @@
"""ShareLink model for board sharing."""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
@@ -29,4 +31,3 @@ class ShareLink(Base):
def __repr__(self) -> str:
return f"<ShareLink(id={self.id}, token={self.token[:8]}...)>"

View File

@@ -1,6 +1,8 @@
"""User model for authentication and ownership."""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
@@ -26,4 +28,3 @@ class User(Base):
def __repr__(self) -> str:
return f"<User(id={self.id}, email={self.email})>"

View File

@@ -25,4 +25,3 @@ def get_db():
yield db
finally:
db.close()

View File

@@ -5,6 +5,7 @@ import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.api import auth
from app.core.config import settings
from app.core.errors import WebRefException
from app.core.logging import setup_logging
@@ -81,7 +82,6 @@ async def root():
# API routers
from app.api import auth
app.include_router(auth.router, prefix=f"{settings.API_V1_PREFIX}")
# Additional routers will be added in subsequent phases
# from app.api import boards, images
@@ -101,4 +101,3 @@ async def startup_event():
async def shutdown_event():
"""Application shutdown tasks."""
logger.info(f"Shutting down {settings.APP_NAME}")

View File

@@ -33,10 +33,6 @@ requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[tool.ruff]
# Enable pycodestyle (`E`), Pyflakes (`F`), isort (`I`)
select = ["E", "F", "I", "W", "N", "UP", "B", "C4", "SIM"]
ignore = []
# Exclude common paths
exclude = [
".git",
@@ -46,16 +42,24 @@ exclude = [
"alembic/versions",
]
# Same as Black.
line-length = 100
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
# Line length (slightly longer for SQLAlchemy models)
line-length = 120
# Target Python 3.12
target-version = "py312"
[tool.ruff.per-file-ignores]
[tool.ruff.lint]
# Enable pycodestyle (`E`), Pyflakes (`F`), isort (`I`)
select = ["E", "F", "I", "W", "N", "UP", "B", "C4", "SIM"]
ignore = [
"B008", # Allow Depends() in FastAPI function defaults
"N818", # Allow WebRefException without Error suffix
]
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"] # Allow unused imports in __init__.py
"tests/*" = ["S101"] # Allow assert in tests