initial commit
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
DATABASE_URL: str = "sqlite:///./data/ams.db"
|
||||
SECRET_KEY: str = "change-me-in-production-32-chars-min"
|
||||
UPLOAD_DIR: str = "./data/uploads"
|
||||
TIMEZONE: str = "Asia/Kolkata"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
|
||||
ALGORITHM: str = "HS256"
|
||||
MAX_UPLOAD_SIZE_MB: int = 10
|
||||
AI_PROVIDER: str = "none" # none | ollama | openai_compatible
|
||||
AI_BASE_URL: str = "http://localhost:11434"
|
||||
AI_MODEL: str = ""
|
||||
AI_API_KEY: str = ""
|
||||
AI_TIMEOUT_SECONDS: int = 300
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,42 @@
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from contextlib import contextmanager
|
||||
from .config import settings
|
||||
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragmas(dbapi_conn, connection_record):
|
||||
cursor = dbapi_conn.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_scheduler_db() -> Session:
|
||||
"""Short-lived session for APScheduler jobs — never share with request sessions."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,57 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError
|
||||
from sqlalchemy.orm import Session
|
||||
from .db import get_db
|
||||
from .security import decode_token
|
||||
from ..models.masters import User
|
||||
from ..services.permissions import Role
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||||
|
||||
|
||||
def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
sub = payload.get("sub")
|
||||
if sub is None:
|
||||
raise credentials_exception
|
||||
user_id = int(sub)
|
||||
except (JWTError, ValueError, TypeError):
|
||||
raise credentials_exception
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None or not user.is_active:
|
||||
raise credentials_exception
|
||||
|
||||
token_tv = payload.get("tv", 0)
|
||||
user_tv = getattr(user, "token_version", 0)
|
||||
if token_tv != user_tv:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been invalidated. Please log in again.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def require_roles(*roles: Role | str):
|
||||
allowed = {r.value if isinstance(r, Role) else r for r in roles}
|
||||
|
||||
def _dependency(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions for this action.",
|
||||
)
|
||||
return current_user
|
||||
|
||||
return _dependency
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class CodedHTTPException(HTTPException):
|
||||
def __init__(self, status_code: int, detail: str, code: str):
|
||||
super().__init__(status_code=status_code, detail=detail)
|
||||
self.code = code
|
||||
|
||||
|
||||
async def coded_http_exception_handler(request: Request, exc: CodedHTTPException) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={"detail": exc.detail, "code": exc.code},
|
||||
headers=exc.headers,
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
import logging
|
||||
from sqlalchemy.engine import Engine
|
||||
from ..models import Base
|
||||
|
||||
logger = logging.getLogger("poona_ams")
|
||||
|
||||
|
||||
def run_sqlite_migrations(engine: Engine) -> None:
|
||||
"""
|
||||
Auto-migrate SQLite database schema additions for existing databases.
|
||||
SQLite create_all() creates missing tables but does not alter existing
|
||||
tables to add newly defined columns. This reconciles table columns
|
||||
safely on startup without losing existing data.
|
||||
"""
|
||||
if engine.dialect.name != "sqlite":
|
||||
return
|
||||
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
existing_tables = {
|
||||
row[0]
|
||||
for row in conn.exec_driver_sql(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||
).fetchall()
|
||||
}
|
||||
|
||||
for table_name, table in Base.metadata.tables.items():
|
||||
if table_name not in existing_tables:
|
||||
continue
|
||||
|
||||
existing_cols = {
|
||||
row[1]
|
||||
for row in conn.exec_driver_sql(
|
||||
f"PRAGMA table_info({table_name})"
|
||||
).fetchall()
|
||||
}
|
||||
|
||||
for col in table.columns:
|
||||
if col.name not in existing_cols:
|
||||
col_type = col.type.compile(engine.dialect)
|
||||
if col.name == "token_version":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL"
|
||||
elif col.name == "acquisition_mode":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} VARCHAR(20) DEFAULT 'purchased'"
|
||||
else:
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||
logger.info("Auto-migrating SQLite: %s", sql)
|
||||
conn.exec_driver_sql(sql)
|
||||
except Exception:
|
||||
logger.exception("Failed running SQLite auto-migrations.")
|
||||
raise
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import timedelta
|
||||
import bcrypt
|
||||
from fastapi import HTTPException, status
|
||||
from jose import JWTError, jwt
|
||||
from .config import settings
|
||||
from .time_utils import utc_now
|
||||
|
||||
BLOCKLIST_PASSWORDS = {
|
||||
"123456",
|
||||
"12345678",
|
||||
"password",
|
||||
"password1",
|
||||
"qwerty123",
|
||||
"admin123",
|
||||
"welcome1",
|
||||
}
|
||||
|
||||
|
||||
def validate_password(password: str, email: str | None = None) -> None:
|
||||
"""Validate password rules:
|
||||
- Length: at least 8, at most 128 characters.
|
||||
- Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.)
|
||||
- Must NOT start or end with a space (reject with a clear message, do not silently strip).
|
||||
- Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'.
|
||||
(NOTE: demo password 'demo@123' must remain allowed)
|
||||
- Must not contain the user's username/email local-part if length >= 4 (case-insensitive).
|
||||
"""
|
||||
if not isinstance(password, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be a string.",
|
||||
)
|
||||
|
||||
if password.startswith(" ") or password.endswith(" "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must not start or end with a space.",
|
||||
)
|
||||
|
||||
if len(password) < 8:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 8 characters long.",
|
||||
)
|
||||
|
||||
if len(password) > 128:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at most 128 characters long.",
|
||||
)
|
||||
|
||||
has_letter = any(c.isalpha() for c in password)
|
||||
has_digit = any(c.isdigit() for c in password)
|
||||
if not has_letter or not has_digit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must contain at least one letter and at least one digit.",
|
||||
)
|
||||
|
||||
lower_pass = password.lower()
|
||||
if lower_pass in BLOCKLIST_PASSWORDS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password is too common or easily guessable.",
|
||||
)
|
||||
|
||||
if email:
|
||||
local_part = email.split("@")[0].strip().lower()
|
||||
if len(local_part) >= 4 and local_part in lower_pass:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must not contain your email username.",
|
||||
)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
if not plain or not hashed:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(
|
||||
plain.encode("utf-8")[:72],
|
||||
hashed.encode("utf-8"),
|
||||
)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def hash_password(plain: str) -> str:
|
||||
hashed = bcrypt.hashpw(plain.encode("utf-8")[:72], bcrypt.gensalt())
|
||||
return hashed.decode("utf-8")
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if "tv" not in to_encode:
|
||||
to_encode["tv"] = 0
|
||||
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict:
|
||||
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
@@ -0,0 +1,97 @@
|
||||
import calendar
|
||||
from datetime import date, datetime, timezone
|
||||
import json
|
||||
import pytz
|
||||
from .config import settings
|
||||
|
||||
try:
|
||||
KOLKATA = pytz.timezone(settings.TIMEZONE)
|
||||
except Exception:
|
||||
KOLKATA = pytz.timezone("Asia/Kolkata")
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _read_demo_date_from_db(db) -> date | None:
|
||||
from ..models.masters import Setting
|
||||
|
||||
row = db.query(Setting).filter(Setting.key == "demo_as_of_date").first()
|
||||
if row and row.value_json:
|
||||
val = json.loads(row.value_json)
|
||||
if isinstance(val, str) and val.strip():
|
||||
return date.fromisoformat(val.strip())
|
||||
return None
|
||||
|
||||
|
||||
def effective_today(db=None) -> date:
|
||||
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata)."""
|
||||
try:
|
||||
if db is not None:
|
||||
demo_date = _read_demo_date_from_db(db)
|
||||
if demo_date is not None:
|
||||
return demo_date
|
||||
else:
|
||||
from .db import SessionLocal
|
||||
|
||||
with SessionLocal() as session:
|
||||
demo_date = _read_demo_date_from_db(session)
|
||||
if demo_date is not None:
|
||||
return demo_date
|
||||
except Exception:
|
||||
pass
|
||||
return datetime.now(KOLKATA).date()
|
||||
|
||||
|
||||
def effective_now_utc(db=None) -> datetime:
|
||||
"""Returns current UTC datetime anchored to effective_today(db) in Asia/Kolkata when demo date is set."""
|
||||
now_kol = datetime.now(KOLKATA)
|
||||
today = effective_today(db)
|
||||
if today == now_kol.date():
|
||||
return now_kol.astimezone(timezone.utc)
|
||||
return KOLKATA.localize(datetime.combine(today, now_kol.timetz().replace(tzinfo=None))).astimezone(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
|
||||
def to_kolkata(dt: datetime) -> datetime:
|
||||
return dt.astimezone(KOLKATA)
|
||||
|
||||
|
||||
def format_datetime(dt: datetime | None) -> str | None:
|
||||
if dt is None:
|
||||
return None
|
||||
local = to_kolkata(dt) if dt.tzinfo else KOLKATA.localize(dt)
|
||||
return local.strftime("%d-%b-%Y %H:%M")
|
||||
|
||||
|
||||
def format_date(d: date | None) -> str | None:
|
||||
if d is None:
|
||||
return None
|
||||
return d.strftime("%d-%b-%Y")
|
||||
|
||||
|
||||
def add_months(d: date, months: int) -> date:
|
||||
"""Add calendar months to a date, clamping day-of-month to the target month's length."""
|
||||
total_months = (d.year * 12 + (d.month - 1)) + months
|
||||
year, zero_month = divmod(total_months, 12)
|
||||
month = zero_month + 1
|
||||
max_day = calendar.monthrange(year, month)[1]
|
||||
return date(year, month, min(d.day, max_day))
|
||||
|
||||
|
||||
def format_duration(minutes: int | None) -> str:
|
||||
if minutes is None:
|
||||
return "\u2014"
|
||||
minutes = int(minutes)
|
||||
d, rem = divmod(minutes, 1440)
|
||||
h, m = divmod(rem, 60)
|
||||
parts = []
|
||||
if d:
|
||||
parts.append(f"{d}d")
|
||||
if h:
|
||||
parts.append(f"{h}h")
|
||||
if m or not parts:
|
||||
parts.append(f"{m}m")
|
||||
return " ".join(parts)
|
||||
Reference in New Issue
Block a user