166 lines
6.5 KiB
Python
166 lines
6.5 KiB
Python
import os
|
|
from . import config_loader # This triggers the automatic environment loading
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from slowapi import Limiter
|
|
from slowapi.util import get_remote_address
|
|
from . import models
|
|
from .database import engine
|
|
from .routers import items, operations, users, categories
|
|
from .routers.admin import backups, config
|
|
from .logger import log
|
|
from .scheduler import scheduler, sync_scheduler_config
|
|
|
|
# Create the database tables
|
|
from .database import DATA_DIR, db_path
|
|
log.info(f"Using DATA_DIR: {DATA_DIR}")
|
|
log.info(f"Database path: {db_path}")
|
|
models.Base.metadata.create_all(bind=engine)
|
|
log.info("Database tables verified.")
|
|
|
|
app = FastAPI(title="TFM aInventory API", version="1.1.0")
|
|
log.info("TFM aInventory API process started.")
|
|
|
|
# [SECURITY FIX M-01] CORS Configuration
|
|
# We dynamically build allowed origins from environment variables to simplify deployment.
|
|
_raw_origins = os.environ.get("ALLOWED_ORIGINS", "")
|
|
ALLOWED_ORIGINS = [o.strip() for o in _raw_origins.split(",") if o.strip()]
|
|
|
|
# Automatically add origins based on network_config.env variables if present
|
|
server_ip = os.environ.get("SERVER_IP")
|
|
front_port = os.environ.get("FRONTEND_PORT", "8917")
|
|
front_ssl_port = os.environ.get("FRONTEND_SSL_PORT", "8919")
|
|
back_ssl_port = os.environ.get("BACKEND_SSL_PORT", "8918")
|
|
|
|
# Always allow localhost
|
|
defaults = [
|
|
f"http://localhost:{front_port}",
|
|
f"https://localhost:{front_ssl_port}",
|
|
f"https://localhost:{back_ssl_port}",
|
|
]
|
|
for d in defaults:
|
|
if d not in ALLOWED_ORIGINS:
|
|
ALLOWED_ORIGINS.append(d)
|
|
|
|
# Add IP-based origins if SERVER_IP is set
|
|
if server_ip and server_ip != "localhost":
|
|
ip_origins = [
|
|
f"http://{server_ip}:{front_port}",
|
|
f"https://{server_ip}:{front_ssl_port}",
|
|
f"https://{server_ip}:{back_ssl_port}",
|
|
]
|
|
for ip_o in ip_origins:
|
|
if ip_o not in ALLOWED_ORIGINS:
|
|
ALLOWED_ORIGINS.append(ip_o)
|
|
|
|
# [NEW] Add Extra Allowed Origins (Tailscale, VPN, etc.)
|
|
extra_origins_raw = os.environ.get("EXTRA_ALLOWED_ORIGINS", "")
|
|
if extra_origins_raw:
|
|
for extra_ip in [o.strip() for o in extra_origins_raw.split(",") if o.strip()]:
|
|
# Generate standard combinations for this extra origin
|
|
ext_combos = [
|
|
f"http://{extra_ip}:{front_port}",
|
|
f"https://{extra_ip}:{front_ssl_port}",
|
|
f"https://{extra_ip}:{back_ssl_port}",
|
|
]
|
|
for combo in ext_combos:
|
|
if combo not in ALLOWED_ORIGINS:
|
|
ALLOWED_ORIGINS.append(combo)
|
|
|
|
log.info("🔒 [SECURITY] CORS configuration initialized.")
|
|
for origin in ALLOWED_ORIGINS:
|
|
log.info(f" -> Allowed: {origin}")
|
|
|
|
# Add CORS middleware FIRST (before rate limiter)
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=ALLOWED_ORIGINS,
|
|
allow_credentials=True,
|
|
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# [H-02] Rate limiting on API
|
|
limiter = Limiter(key_func=get_remote_address)
|
|
app.state.limiter = limiter
|
|
|
|
app.include_router(items.router)
|
|
app.include_router(operations.router)
|
|
app.include_router(users.router)
|
|
app.include_router(categories.router)
|
|
app.include_router(backups.router)
|
|
app.include_router(config.router)
|
|
|
|
@app.on_event("startup")
|
|
def startup_event():
|
|
log.info("[STARTUP] Starting background scheduler...")
|
|
scheduler.start()
|
|
sync_scheduler_config()
|
|
|
|
# [NEW] Initialize default system settings
|
|
from .database import SessionLocal
|
|
db = SessionLocal()
|
|
try:
|
|
# Default AI Prompt from User Request
|
|
default_prompt = (
|
|
"identify and summarise the minimal necessary information for a quick description if item. "
|
|
"I need the following output - <field name> : the result from you.\n"
|
|
"For any field, do not add comments in parenthesis. \n\n"
|
|
"Item: in three words type of this item\n"
|
|
"Type: what type of item is, like \"spare parts\", \"consumables\", \"patch cords\" etc.\n"
|
|
"Description: description (max 5 words)\n"
|
|
"Category: category, if any\n"
|
|
"Connector: connectors\n"
|
|
"Size: size or length\n"
|
|
"Color: color if useful\n"
|
|
"PartNr: part number if any\n"
|
|
"OCR: identification string for local OCR matching"
|
|
)
|
|
|
|
# Wrap in JSON instructions for reliable parsing
|
|
final_prompt = f"IMAGE ANALYSIS INSTRUCTIONS:\n{default_prompt}\n\nIMPORTANT: Return ONLY a valid JSON object with the keys: Item, Type, Description, Category, Connector, Size, Color, PartNr, OCR."
|
|
|
|
existing = db.query(models.SystemSetting).filter(models.SystemSetting.key == "ai_extraction_prompt").first()
|
|
if not existing:
|
|
db.add(models.SystemSetting(key="ai_extraction_prompt", value=final_prompt))
|
|
db.commit()
|
|
log.info("Initialized default AI prompt in database.")
|
|
# Refresh existing after commit
|
|
existing = db.query(models.SystemSetting).filter(models.SystemSetting.key == "ai_extraction_prompt").first()
|
|
|
|
# [NEW] Sync/Initialize AI prompt file in /config
|
|
from .database import BASE_DIR
|
|
PROJECT_ROOT = os.path.dirname(BASE_DIR)
|
|
PROMPT_FILE_PATH = os.path.join(PROJECT_ROOT, "config", "ai_prompt.md")
|
|
|
|
if not os.path.exists(PROMPT_FILE_PATH):
|
|
try:
|
|
os.makedirs(os.path.dirname(PROMPT_FILE_PATH), exist_ok=True)
|
|
# Use DB value (which we just ensured exists)
|
|
current_val = existing.value if existing else final_prompt
|
|
with open(PROMPT_FILE_PATH, 'w', encoding='utf-8') as f:
|
|
f.write(current_val)
|
|
log.info(f"✅ Initialized AI prompt configuration file: {PROMPT_FILE_PATH}")
|
|
except Exception as fe:
|
|
log.error(f"❌ Failed to initialize AI prompt file: {fe}")
|
|
|
|
defaults = {
|
|
"backup_retention_count": "10",
|
|
"backup_schedule_hour": "3",
|
|
"backup_schedule_freq_days": "1",
|
|
"ai_provider": "gemini"
|
|
}
|
|
for key, val in defaults.items():
|
|
if not db.query(models.SystemSetting).filter(models.SystemSetting.key == key).first():
|
|
db.add(models.SystemSetting(key=key, value=val))
|
|
log.info(f"Initialized default setting: {key}")
|
|
db.commit()
|
|
except Exception as e:
|
|
log.error(f"Failed to initialize settings: {e}")
|
|
finally:
|
|
db.close()
|
|
|
|
@app.get("/")
|
|
def read_root():
|
|
return {"message": "Inventory API is running"}
|