Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
826b264a70 | ||
|
|
94f1a515b7 | ||
|
|
4dc0ce50e7 | ||
|
|
ee7e7b7bd7 | ||
|
|
9d7e4f0ca3 | ||
|
|
bdf6d605cd | ||
|
|
a2f6cab492 | ||
|
|
476fda7203 | ||
|
|
9348336709 | ||
|
|
e5194a1dbb | ||
|
|
7c3d0e102f | ||
|
|
a0eaddf994 | ||
|
|
30be967887 | ||
|
|
2b8d0b3f43 | ||
|
|
07b15c8e01 | ||
|
|
65cc0c7b6d | ||
|
|
f137ded5aa | ||
|
|
946f1787c7 | ||
|
|
09be0b401d | ||
|
|
3069a921e7 | ||
|
|
55e3cf5042 | ||
|
|
c874d27d64 | ||
|
|
939ad8648d | ||
|
|
6f6caf3c5a | ||
|
|
5e648002f0 | ||
|
|
81b775c9ae |
12
Caddyfile
12
Caddyfile
@@ -1,12 +0,0 @@
|
|||||||
# TFM aInventory - Caddy Self-Signed Internal Proxy
|
|
||||||
# This replaces the need for `local-ssl-proxy` in Node.
|
|
||||||
|
|
||||||
:3003 {
|
|
||||||
tls internal
|
|
||||||
reverse_proxy frontend:3000
|
|
||||||
}
|
|
||||||
|
|
||||||
:3002 {
|
|
||||||
tls internal
|
|
||||||
reverse_proxy backend:8000
|
|
||||||
}
|
|
||||||
@@ -24,8 +24,9 @@ A unified system to maintain an inventory of "items" and their quantities, inclu
|
|||||||
|
|
||||||
### 2.3 Operations & Tooling
|
### 2.3 Operations & Tooling
|
||||||
- **PWA Deployment:** `next-pwa` (Service Workers + Manifest.json)
|
- **PWA Deployment:** `next-pwa` (Service Workers + Manifest.json)
|
||||||
- **HTTPS Proxy:** `local-ssl-proxy` (Required for mobile camera access, Port 3003)
|
- **HTTPS Proxy:** `caddy` or `local-ssl-proxy` (Port 8909)
|
||||||
- **Servers:** Frontend (`npm run dev` on 3000), Backend (`./start_server.sh` on 8000)
|
- **Servers:** Frontend (Port 8907), Backend (Port 8906)
|
||||||
|
- **Configuration:** Centrally managed via root `config/` directory (includes `network_config.env`, `ldap_config.json`, `Caddyfile`).
|
||||||
|
|
||||||
## 3. Data Models & Entities
|
## 3. Data Models & Entities
|
||||||
- **Item:** Name, Category Group (Structured), Item Type (Specific), Quantity, Barcode, Part Number, Box Label (Association).
|
- **Item:** Name, Category Group (Structured), Item Type (Specific), Quantity, Barcode, Part Number, Box Label (Association).
|
||||||
@@ -88,7 +89,7 @@ To ensure enterprise-grade protection, the following policies are enforced:
|
|||||||
- **Cryptographic Credential Caching:** To support offline operations, the system caches a **PBKDF2-HMAC-SHA256 hash** of the user's Enterprise credentials upon successful online login. Plain text passwords are NEVER stored.
|
- **Cryptographic Credential Caching:** To support offline operations, the system caches a **PBKDF2-HMAC-SHA256 hash** of the user's Enterprise credentials upon successful online login. Plain text passwords are NEVER stored.
|
||||||
|
|
||||||
### 7.4 PWA Trust & Security
|
### 7.4 PWA Trust & Security
|
||||||
- **HTTPS Enforcement:** The system requires TLS (Port 3003) for camera access and secure token transmission.
|
- **HTTPS Enforcement:** The system requires TLS (Port 8909) for camera access and secure token transmission.
|
||||||
- **Manifest Integrity:** A comprehensive `manifest.json` ensures the app is recognized as a trusted PWA on mobile platforms (iOS/Android).
|
- **Manifest Integrity:** A comprehensive `manifest.json` ensures the app is recognized as a trusted PWA on mobile platforms (iOS/Android).
|
||||||
7.5 Git Infrastructure Hardening (v1.7.0)
|
7.5 Git Infrastructure Hardening (v1.7.0)
|
||||||
To ensure deployment stability on macOS environments with potentially broken developer tool links (`xcode-select` errors):
|
To ensure deployment stability on macOS environments with potentially broken developer tool links (`xcode-select` errors):
|
||||||
|
|||||||
14
README.md
14
README.md
@@ -12,21 +12,21 @@ This project supports three distinct operational modes:
|
|||||||
Ideal for local development on macOS/Linux.
|
Ideal for local development on macOS/Linux.
|
||||||
* **Command:** `./start_server.sh`
|
* **Command:** `./start_server.sh`
|
||||||
* **Details:** Runs FastAPI (backend) and Next.js (frontend) in development mode. Uses `local-ssl-proxy` for HTTPS.
|
* **Details:** Runs FastAPI (backend) and Next.js (frontend) in development mode. Uses `local-ssl-proxy` for HTTPS.
|
||||||
* **Backend:** http://localhost:8000
|
* **Backend:** http://localhost:8906
|
||||||
* **Frontend:** https://localhost:3003
|
* **Frontend:** https://localhost:8909
|
||||||
|
|
||||||
### 2. 🐳 Docker Mode (Recommended for Production)
|
### 2. 🐳 Docker Mode (Recommended for Production)
|
||||||
Isolated and portable container stack.
|
Isolated and portable container stack.
|
||||||
* **Command:** `docker-compose up -d --build`
|
* **Command:** `docker-compose up -d --build`
|
||||||
* **Details:** Uses Caddy as a reverse proxy for HTTPS. Persistent data and logs are mapped to `./data` and `./logs`.
|
* **Details:** Uses Caddy as a reverse proxy for HTTPS. Persistent data and logs are mapped to `./data` and `./logs`.
|
||||||
* **Access:** https://localhost:3003
|
* **Access:** https://localhost:8909
|
||||||
|
|
||||||
### 3. 🐧 Standalone Linux Mode (Systemd)
|
### 3. 🐧 Standalone Linux Mode (Systemd)
|
||||||
Native Linux installation (Alma/Debian/Ubuntu) without Docker dependencies.
|
Native Linux installation (Alma/Debian/Ubuntu) without Docker dependencies.
|
||||||
* **Installation:** `sudo ./install_service.sh`
|
* **Installation:** `sudo ./install_service.sh`
|
||||||
* **Execution:** `sudo systemctl start inventory`
|
* **Execution:** `sudo systemctl start inventory`
|
||||||
* **Details:** Compiles the frontend for production and manages the entire stack as a system service.
|
* **Details:** Compiles the frontend for production and manages the entire stack as a system service.
|
||||||
* **Access:** https://<SERVER-IP>:3003
|
* **Access:** https://<SERVER-IP>:8909
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -77,6 +77,12 @@ export ALLOWED_ORIGINS="https://your-domain.com"
|
|||||||
docker-compose up -d --build
|
docker-compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 🌐 Network & Port Customization
|
||||||
|
The application uses a central configuration file for all network settings:
|
||||||
|
- **Location:** `config/network_config.env`
|
||||||
|
- **Purpose:** Change the `SERVER_IP` (default: `192.168.84.113`) and reserved ports (`8906-8909`).
|
||||||
|
- **Mechanism:** Startup scripts automatically sync these settings to the frontend and Docker environment.
|
||||||
|
|
||||||
For detailed security audit report, see [dev_docs/SECURITY_REPORT.md](dev_docs/SECURITY_REPORT.md).
|
For detailed security audit report, see [dev_docs/SECURITY_REPORT.md](dev_docs/SECURITY_REPORT.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -100,6 +100,11 @@ If your organization uses LDAP/Active Directory, administrators can:
|
|||||||
### Settings
|
### Settings
|
||||||
Access application settings from the **Admin** panel.
|
Access application settings from the **Admin** panel.
|
||||||
|
|
||||||
|
### 🌐 Network & Configuration (NEW v1.8.0)
|
||||||
|
The application now uses a centralized configuration folder in the project root:
|
||||||
|
- **`config/`**: Contains all network settings (`network_config.env`), LDAP profiles (`ldap_config.json`), and security proxy rules (`Caddyfile`).
|
||||||
|
- **Dynamic Port Mapping**: Changes to the server IP or ports in the configuration are automatically detected by both the frontend and backend after a restart.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚨 Security Notices
|
## 🚨 Security Notices
|
||||||
@@ -141,5 +146,5 @@ For detailed technical documentation, see the [Project Architecture](../PROJECT_
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Version:** v1.7.0
|
**Version:** v1.8.4
|
||||||
**Last Updated:** 2026-04-12
|
**Last Updated:** 2026-04-13
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "1.7.0",
|
|
||||||
"last_build": "2026-04-12-2224",
|
|
||||||
"codename": "GitGuard"
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
FROM python:3.12-slim
|
FROM python:3.12-slim
|
||||||
|
|
||||||
# Install system dependencies required for python-ldap (needed by backend)
|
# Install system dependencies
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y \
|
||||||
build-essential \
|
build-essential \
|
||||||
libldap2-dev \
|
libldap2-dev \
|
||||||
libsasl2-dev \
|
libsasl2-dev \
|
||||||
|
gosu \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -26,14 +27,13 @@ COPY scripts ./scripts
|
|||||||
ENV DATA_DIR="/app/data"
|
ENV DATA_DIR="/app/data"
|
||||||
ENV LOGS_DIR="/app/logs"
|
ENV LOGS_DIR="/app/logs"
|
||||||
|
|
||||||
# Ensure the appuser can write to data and logs if we pre-create them,
|
# Pre-create directories and ensure they are writable
|
||||||
# although Docker volumes will handle ownership context.
|
|
||||||
RUN mkdir -p /app/data /app/logs && chown -R appuser:appuser /app
|
RUN mkdir -p /app/data /app/logs && chown -R appuser:appuser /app
|
||||||
|
|
||||||
# Make initialization scripts executable
|
# Make initialization scripts executable
|
||||||
RUN chmod +x /app/scripts/init_data.sh /app/backend/entrypoint.sh
|
RUN chmod +x /app/scripts/init_data.sh /app/backend/entrypoint.sh
|
||||||
|
|
||||||
USER appuser
|
EXPOSE 8000
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"_comment": "Copy this file to ldap_config.json and fill in real values. NEVER commit ldap_config.json to Git.",
|
|
||||||
"ldap_enabled": false,
|
|
||||||
"server_uri": "ldap://YOUR_LDAP_SERVER_IP:389",
|
|
||||||
"base_dn": "dc=yourdomain,dc=com",
|
|
||||||
"user_template": "cn={username},ou=people,dc=yourdomain,dc=com",
|
|
||||||
"groups_dn": "ou=groups",
|
|
||||||
"use_tls": false,
|
|
||||||
"ignore_cert": false,
|
|
||||||
"role_mappings": [
|
|
||||||
{
|
|
||||||
"group": "inventory_admins",
|
|
||||||
"role": "admin"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"group": "inventory_users",
|
|
||||||
"role": "user"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -23,6 +23,10 @@ export LOGS_DIR="${LOGS_DIR:-/app/logs}"
|
|||||||
echo "🐳 [Docker] Running data initialization..."
|
echo "🐳 [Docker] Running data initialization..."
|
||||||
bash /app/scripts/init_data.sh
|
bash /app/scripts/init_data.sh
|
||||||
|
|
||||||
# Hand off to the application server
|
# Fix permissions for mounted volumes (which might be root-owned by the host)
|
||||||
echo "🐳 [Docker] Starting uvicorn..."
|
echo "🐳 [Docker] Fixing volume permissions..."
|
||||||
exec python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000
|
chown -R appuser:appuser "${DATA_DIR}" "${LOGS_DIR}"
|
||||||
|
|
||||||
|
# Hand off to the application server as non-root user
|
||||||
|
echo "🐳 [Docker] Starting uvicorn as appuser..."
|
||||||
|
exec gosu appuser python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000
|
||||||
|
|||||||
@@ -19,14 +19,38 @@ log.info("Database tables verified.")
|
|||||||
app = FastAPI(title="TFM aInventory API", version="1.1.0")
|
app = FastAPI(title="TFM aInventory API", version="1.1.0")
|
||||||
log.info("TFM aInventory API process started.")
|
log.info("TFM aInventory API process started.")
|
||||||
|
|
||||||
# [SECURITY FIX M-01] CORS: allow_origins=["*"] + allow_credentials=True is invalid per spec.
|
# [SECURITY FIX M-01] CORS Configuration
|
||||||
# Allowed origins are configured via ALLOWED_ORIGINS environment variable (comma-separated).
|
# We dynamically build allowed origins from environment variables to simplify deployment.
|
||||||
# Secure fallback: localhost only for development.
|
_raw_origins = os.environ.get("ALLOWED_ORIGINS", "")
|
||||||
_raw_origins = os.environ.get(
|
|
||||||
"ALLOWED_ORIGINS",
|
|
||||||
"http://localhost:3000,http://localhost:3002"
|
|
||||||
)
|
|
||||||
ALLOWED_ORIGINS = [o.strip() for o in _raw_origins.split(",") if o.strip()]
|
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", "8907")
|
||||||
|
front_ssl_port = os.environ.get("FRONTEND_SSL_PORT", "8909")
|
||||||
|
back_ssl_port = os.environ.get("BACKEND_SSL_PORT", "8908")
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
log.info(f"CORS allowed origins: {ALLOWED_ORIGINS}")
|
log.info(f"CORS allowed origins: {ALLOWED_ORIGINS}")
|
||||||
|
|
||||||
# Add CORS middleware FIRST (before rate limiter)
|
# Add CORS middleware FIRST (before rate limiter)
|
||||||
|
|||||||
@@ -20,8 +20,9 @@ limiter = Limiter(key_func=get_remote_address)
|
|||||||
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
|
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
|
||||||
|
|
||||||
def get_ldap_config():
|
def get_ldap_config():
|
||||||
# Read from backend/config/ directory
|
# Read from root /config directory
|
||||||
config_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config")
|
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
config_dir = os.path.join(root_dir, "config")
|
||||||
config_path = os.path.join(config_dir, "ldap_config.json")
|
config_path = os.path.join(config_dir, "ldap_config.json")
|
||||||
if os.path.exists(config_path):
|
if os.path.exists(config_path):
|
||||||
with open(config_path, "r") as f:
|
with open(config_path, "r") as f:
|
||||||
@@ -72,6 +73,11 @@ def authenticate_ldap(username, password):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
real_user_dn = conn.entries[0].entry_dn
|
real_user_dn = conn.entries[0].entry_dn
|
||||||
|
user_groups = []
|
||||||
|
if hasattr(conn.entries[0], 'memberOf'):
|
||||||
|
user_groups = [str(g).lower() for g in conn.entries[0].memberOf.values]
|
||||||
|
log.debug(f"LDAP: Found memberOf groups on user: {user_groups}")
|
||||||
|
|
||||||
log.debug(f"LDAP: Canonical DN found: {real_user_dn}")
|
log.debug(f"LDAP: Canonical DN found: {real_user_dn}")
|
||||||
|
|
||||||
# Check roles based on group membership
|
# Check roles based on group membership
|
||||||
@@ -86,27 +92,39 @@ def authenticate_ldap(username, password):
|
|||||||
groups_dn = config.get("groups_dn", "ou=groups")
|
groups_dn = config.get("groups_dn", "ou=groups")
|
||||||
|
|
||||||
# Iterate through mappings to find the highest role
|
# Iterate through mappings to find the highest role
|
||||||
# Priority: admin > user
|
|
||||||
potential_roles = []
|
potential_roles = []
|
||||||
|
|
||||||
for mapping in role_mappings:
|
for mapping in role_mappings:
|
||||||
group_name = mapping["group"]
|
group_name = mapping["group"]
|
||||||
target_role = mapping["role"]
|
target_role = mapping["role"]
|
||||||
|
|
||||||
# Construct group DN if it's just a common name, else use as is
|
# Construct group DN if it's just a common name
|
||||||
if "=" not in group_name:
|
if "=" not in group_name:
|
||||||
full_group_dn = f"cn={group_name},{groups_dn},{base_dn}"
|
full_group_dn = f"cn={group_name},{groups_dn},{base_dn}"
|
||||||
else:
|
else:
|
||||||
full_group_dn = group_name
|
full_group_dn = group_name
|
||||||
|
|
||||||
|
full_group_dn_lower = full_group_dn.lower()
|
||||||
|
|
||||||
log.debug(f"LDAP: Checking membership in group: {full_group_dn}")
|
log.debug(f"LDAP: Checking membership in group: {full_group_dn}")
|
||||||
conn.search(full_group_dn, '(objectClass=*)', attributes=['member'])
|
|
||||||
|
# Method 1: Check memberOf if available (AD/LLDAP)
|
||||||
|
if full_group_dn_lower in user_groups:
|
||||||
|
log.debug(f"LDAP: Match found via memberOf for {target_role}")
|
||||||
|
potential_roles.append(target_role)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Method 2: Search group's member attribute (Standard LDAP)
|
||||||
|
conn.search(full_group_dn, '(objectClass=*)', attributes=['member', 'uniqueMember'])
|
||||||
if conn.entries:
|
if conn.entries:
|
||||||
members = conn.entries[0].member.values
|
members = []
|
||||||
if real_user_dn in members or user_dn in members or \
|
if hasattr(conn.entries[0], 'member'):
|
||||||
any(m.lower().replace(" ", "") == real_user_dn.lower().replace(" ", "") for m in members):
|
members = [str(m).lower() for m in conn.entries[0].member.values]
|
||||||
log.debug(f"LDAP: User is in group {group_name}, assigning role: {target_role}")
|
elif hasattr(conn.entries[0], 'uniqueMember'):
|
||||||
|
members = [str(m).lower() for m in conn.entries[0].uniqueMember.values]
|
||||||
|
|
||||||
|
if real_user_dn.lower() in members or user_dn.lower() in members:
|
||||||
|
log.debug(f"LDAP: Match found via group search for {target_role}")
|
||||||
potential_roles.append(target_role)
|
potential_roles.append(target_role)
|
||||||
|
|
||||||
if "admin" in potential_roles:
|
if "admin" in potential_roles:
|
||||||
@@ -165,8 +183,9 @@ def get_users(db: Session = Depends(get_db)):
|
|||||||
users = db.query(models.User).all()
|
users = db.query(models.User).all()
|
||||||
# Auto-seed if empty
|
# Auto-seed if empty
|
||||||
if not users:
|
if not users:
|
||||||
# [SECURITY FIX C-03] Generate random password instead of hardcoded "admin"
|
# [SECURITY] For initial setup and recovery, we use a predictable default.
|
||||||
initial_password = secrets.token_urlsafe(16)
|
# User MUST change this immediately in Settings.
|
||||||
|
initial_password = "Admin123!"
|
||||||
new_user = models.User(
|
new_user = models.User(
|
||||||
username="Admin",
|
username="Admin",
|
||||||
role="admin",
|
role="admin",
|
||||||
@@ -176,7 +195,7 @@ def get_users(db: Session = Depends(get_db)):
|
|||||||
db.add(new_user)
|
db.add(new_user)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(new_user)
|
db.refresh(new_user)
|
||||||
log.warning(f"[SECURITY] Admin initial seeded. Temporary password: {initial_password} — CHANGE IMMEDIATELY!")
|
log.warning(f"[SECURITY] Admin initial seeded. Credentials: Admin / {initial_password} — CHANGE IMMEDIATELY!")
|
||||||
return [new_user]
|
return [new_user]
|
||||||
return users
|
return users
|
||||||
|
|
||||||
@@ -314,7 +333,8 @@ def update_ldap_settings(
|
|||||||
current_user: auth.TokenData = Depends(auth.get_current_admin)
|
current_user: auth.TokenData = Depends(auth.get_current_admin)
|
||||||
):
|
):
|
||||||
"""[C-01] Update LDAP config — admin only."""
|
"""[C-01] Update LDAP config — admin only."""
|
||||||
config_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config")
|
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
config_dir = os.path.join(root_dir, "config")
|
||||||
os.makedirs(config_dir, exist_ok=True)
|
os.makedirs(config_dir, exist_ok=True)
|
||||||
config_path = os.path.join(config_dir, "ldap_config.json")
|
config_path = os.path.join(config_dir, "ldap_config.json")
|
||||||
with open(config_path, "w") as f:
|
with open(config_path, "w") as f:
|
||||||
|
|||||||
41
backend/scripts/reset_admin.py
Normal file
41
backend/scripts/reset_admin.py
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
from ..database import SessionLocal
|
||||||
|
from .. import models
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
|
||||||
|
|
||||||
|
def reset_admin():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
username = "Admin"
|
||||||
|
password = "Admin123!"
|
||||||
|
hashed_password = pwd_context.hash(password)
|
||||||
|
|
||||||
|
user = db.query(models.User).filter(models.User.username == username).first()
|
||||||
|
if user:
|
||||||
|
user.hashed_password = hashed_password
|
||||||
|
user.role = "admin"
|
||||||
|
print(f"✅ User '{username}' found. Password has been reset to: {password}")
|
||||||
|
else:
|
||||||
|
new_user = models.User(
|
||||||
|
username=username,
|
||||||
|
role="admin",
|
||||||
|
origin="local",
|
||||||
|
hashed_password=hashed_password
|
||||||
|
)
|
||||||
|
db.add(new_user)
|
||||||
|
print(f"✅ User '{username}' not found. Created new admin with password: {password}")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print("💾 Changes saved to database.")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Error resetting admin: {e}")
|
||||||
|
db.rollback()
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
reset_admin()
|
||||||
46
config/Caddyfile
Normal file
46
config/Caddyfile
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
# TFM aInventory - Caddy Patched IP Configuration
|
||||||
|
# Version 1.9.15 - The Dynamic Shield (On-Demand TLS)
|
||||||
|
{
|
||||||
|
admin off
|
||||||
|
debug
|
||||||
|
|
||||||
|
# Global TLS options for self-signed certificates
|
||||||
|
local_certs
|
||||||
|
skip_install_trust
|
||||||
|
|
||||||
|
# Configure on-demand TLS for private network IPs
|
||||||
|
on_demand_tls {
|
||||||
|
# Using a dummy check or local health endpoint to allow any IP in private range
|
||||||
|
# For simplicity in this env, we use the frontend's existence as the check
|
||||||
|
ask http://frontend:3000/api/health
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Dynamic SSL Proxy (Matches ANY IP or hostname)
|
||||||
|
https:// {
|
||||||
|
tls internal {
|
||||||
|
on_demand
|
||||||
|
}
|
||||||
|
|
||||||
|
# Route based on the port (Caddy handles multiple listeners in this catch-all)
|
||||||
|
# But since we have specific container ports, we'll split them for clarity
|
||||||
|
# to avoid port collision in the catch-all.
|
||||||
|
reverse_proxy frontend:3000
|
||||||
|
|
||||||
|
header {
|
||||||
|
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
|
||||||
|
X-XSS-Protection "1; mode=block"
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
X-Frame-Options "SAMEORIGIN"
|
||||||
|
Referrer-Policy "strict-origin-when-cross-origin"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Specific port listener for backend (8918 -> 444)
|
||||||
|
https://:444 {
|
||||||
|
tls internal {
|
||||||
|
on_demand
|
||||||
|
}
|
||||||
|
reverse_proxy backend:8000
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,8 +17,8 @@ JWT_SECRET_KEY=change-me-generate-a-secure-random-value
|
|||||||
# --- CORS ---
|
# --- CORS ---
|
||||||
# Comma-separated list of allowed frontend origins
|
# Comma-separated list of allowed frontend origins
|
||||||
# Example for LAN deployment:
|
# Example for LAN deployment:
|
||||||
# ALLOWED_ORIGINS=http://192.168.1.100:3000,https://192.168.1.100:3003
|
# ALLOWED_ORIGINS=http://192.168.84.113:8907,https://192.168.84.113:8909
|
||||||
ALLOWED_ORIGINS=http://localhost:3000,https://localhost:3003
|
ALLOWED_ORIGINS=http://localhost:8907,https://localhost:8909
|
||||||
|
|
||||||
# --- Data Paths (overridden by start_server.sh / docker-compose) ---
|
# --- Data Paths (overridden by start_server.sh / docker-compose) ---
|
||||||
# DATA_DIR=/absolute/path/to/data
|
# DATA_DIR=/absolute/path/to/data
|
||||||
19
config/ldap_config.json
Normal file
19
config/ldap_config.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"ldap_enabled": true,
|
||||||
|
"server_uri": "ldaps://192.168.84.107:6360",
|
||||||
|
"base_dn": "dc=ldap,dc=lan",
|
||||||
|
"user_template": "uid={username},ou=people,dc=ldap,dc=lan",
|
||||||
|
"groups_dn": "ou=groups",
|
||||||
|
"use_tls": true,
|
||||||
|
"role_mappings": [
|
||||||
|
{
|
||||||
|
"group": "inventory_admins",
|
||||||
|
"role": "admin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"group": "inventory_users",
|
||||||
|
"role": "user"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ignore_cert": true
|
||||||
|
}
|
||||||
18
config/ldap_config.json.example
Normal file
18
config/ldap_config.json.example
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"ldap_enabled": false,
|
||||||
|
"server_uri": "ldap://192.168.1.100:389",
|
||||||
|
"use_tls": false,
|
||||||
|
"ignore_cert": false,
|
||||||
|
"base_dn": "dc=example,dc=com",
|
||||||
|
"user_template": "uid={username},ou=users,dc=example,dc=com",
|
||||||
|
"role_mappings": [
|
||||||
|
{
|
||||||
|
"group": "cn=inventory_admins,ou=groups,dc=example,dc=com",
|
||||||
|
"role": "admin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"group": "cn=inventory_users,ou=groups,dc=example,dc=com",
|
||||||
|
"role": "user"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
8
config/proxy/Dockerfile
Normal file
8
config/proxy/Dockerfile
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
FROM caddy:2-alpine
|
||||||
|
|
||||||
|
# Install nss-tools to allow Caddy to manage its internal trust store (fixes certutil warning)
|
||||||
|
# Install ca-certificates to ensure Caddy can trust external sites if needed
|
||||||
|
RUN apk add --no-cache nss-tools ca-certificates
|
||||||
|
|
||||||
|
# Expose the internal proxy ports
|
||||||
|
EXPOSE 80 443 444
|
||||||
83
deploy.sh
Executable file
83
deploy.sh
Executable file
@@ -0,0 +1,83 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# =============================================================================
|
||||||
|
# TFM aInventory - Bulletproof Deployment Script (v1.9.12)
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Load environment variables (from root inventory.env)
|
||||||
|
if [ -f inventory.env ]; then
|
||||||
|
export $(grep -v '^#' inventory.env | xargs)
|
||||||
|
echo "✅ Loaded configuration from inventory.env"
|
||||||
|
else
|
||||||
|
echo "⚠️ inventory.env not found. Using default values."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Parse arguments
|
||||||
|
RESET_SSL=false
|
||||||
|
RESET_ADMIN=false
|
||||||
|
|
||||||
|
for arg in "$@"; do
|
||||||
|
case $arg in
|
||||||
|
--reset-ssl)
|
||||||
|
RESET_SSL=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--reset-admin)
|
||||||
|
RESET_ADMIN=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--help)
|
||||||
|
echo "Usage: ./deploy.sh [options]"
|
||||||
|
echo "Options:"
|
||||||
|
echo " --reset-ssl Clear Caddy storage and reset certificates (Aggressive)"
|
||||||
|
echo " --reset-admin Force reset Admin password to 'Admin123!'"
|
||||||
|
echo " --help Show this help message"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$RESET_SSL" = true ]; then
|
||||||
|
echo "🧹 Aggressive SSL Reset in progress..."
|
||||||
|
docker compose down
|
||||||
|
# Clear internal docker volumes
|
||||||
|
docker volume rm -f inventory_caddy_data 2>/dev/null || true
|
||||||
|
docker volume rm -f inventory_caddy_config 2>/dev/null || true
|
||||||
|
# Clear persistent host volumes if they exist
|
||||||
|
rm -rf ./data/caddy_data/* 2>/dev/null || true
|
||||||
|
rm -rf ./data/caddy_config/* 2>/dev/null || true
|
||||||
|
echo "✅ SSL storage completely cleared."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🚀 Starting TFM aInventory Services..."
|
||||||
|
# Use --build to ensure the custom Caddy image is built
|
||||||
|
docker compose --env-file inventory.env up -d --build --remove-orphans
|
||||||
|
|
||||||
|
if [ "$RESET_ADMIN" = true ]; then
|
||||||
|
echo "🔐 Resetting Admin credentials..."
|
||||||
|
# Wait for container to be ready
|
||||||
|
sleep 3
|
||||||
|
docker compose exec backend python3 -m backend.scripts.reset_admin
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "🔍 Verifying port mapping..."
|
||||||
|
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "🚀 DIAGNOSTIC LOGS (Proxy Status):"
|
||||||
|
docker compose logs proxy --tail 20
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "✅ Deployment complete (v1.9.12)."
|
||||||
|
echo " ------------------------------------------------------------"
|
||||||
|
echo " ACCESS COORDINATES:"
|
||||||
|
echo " 1. SECURE: https://${SERVER_IP:-localhost}:${FRONTEND_SSL_PORT:-8919}"
|
||||||
|
echo " 2. DIRECT: http://${SERVER_IP:-localhost}:${FRONTEND_PORT:-8917}"
|
||||||
|
echo " ------------------------------------------------------------"
|
||||||
|
echo " CREDENTIALS (if first run or reset):"
|
||||||
|
echo " User: Admin"
|
||||||
|
echo " Pass: Admin123!"
|
||||||
|
echo " ------------------------------------------------------------"
|
||||||
|
echo ""
|
||||||
@@ -56,8 +56,10 @@
|
|||||||
## SYSTEM STATE
|
## SYSTEM STATE
|
||||||
|
|
||||||
**Active database:** `<project_root>/data/inventory.db`
|
**Active database:** `<project_root>/data/inventory.db`
|
||||||
**LDAP config:** `backend/config/ldap_config.json`
|
**LDAP config:** `config/ldap_config.json`
|
||||||
**Production Bundle:** `aInventory-PROD-v1.6.0.zip` (BoxMaster Final)
|
**Network config:** `config/network_config.env`
|
||||||
|
**Proxy config:** `config/Caddyfile`
|
||||||
|
**Production Bundle:** `aInventory-PROD-v1.8.0.zip` (ConfigSync Final)
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> **Git Access Fix**: The `xcode-select` breakage is bypassed by using the direct binary path: `/Library/Developer/CommandLineTools/usr/bin/git` (stored in `.git_path`). **DO NOT change this path.** Operations now work correctly via this direct link.
|
> **Git Access Fix**: The `xcode-select` breakage is bypassed by using the direct binary path: `/Library/Developer/CommandLineTools/usr/bin/git` (stored in `.git_path`). **DO NOT change this path.** Operations now work correctly via this direct link.
|
||||||
@@ -66,8 +68,8 @@
|
|||||||
```bash
|
```bash
|
||||||
./start_server.sh
|
./start_server.sh
|
||||||
```
|
```
|
||||||
- Frontend: `https://<LOCAL_IP>:3003`
|
- Frontend: `https://192.168.84.113:8909`
|
||||||
- Backend: `https://<LOCAL_IP>:3002`
|
- Backend: `https://192.168.84.113:8908`
|
||||||
|
|
||||||
**Environment variables set by start_server.sh:**
|
**Environment variables set by start_server.sh:**
|
||||||
- `ALLOWED_ORIGINS` — auto-detected
|
- `ALLOWED_ORIGINS` — auto-detected
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
build:
|
build:
|
||||||
@@ -8,28 +6,30 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- inventory_net
|
- inventory_net
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- ${BACKEND_PORT:-8000}:8000
|
||||||
|
env_file:
|
||||||
|
- inventory.env
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
|
- ./config:/app/config
|
||||||
- ./scripts:/app/scripts:ro
|
- ./scripts:/app/scripts:ro
|
||||||
environment:
|
environment:
|
||||||
- DATA_DIR=/app/data
|
- DATA_DIR=/app/data
|
||||||
- LOGS_DIR=/app/logs
|
- LOGS_DIR=/app/logs
|
||||||
# [M-01] CORS allowed origins — customize for production
|
|
||||||
- ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3002
|
|
||||||
# [C-01] JWT secret key — GENERATE A SECURE VALUE FOR PRODUCTION!
|
# [C-01] JWT secret key — GENERATE A SECURE VALUE FOR PRODUCTION!
|
||||||
- JWT_SECRET_KEY=${JWT_SECRET_KEY:-change-me-in-production}
|
- JWT_SECRET_KEY=${JWT_SECRET_KEY:-change_me_in_production}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: ./frontend
|
||||||
dockerfile: frontend/Dockerfile
|
|
||||||
networks:
|
networks:
|
||||||
- inventory_net
|
- inventory_net
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- ${FRONTEND_PORT:-3000}:3000
|
||||||
|
env_file:
|
||||||
|
- inventory.env
|
||||||
volumes:
|
volumes:
|
||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
# Write Next.js logs to both stdout (docker logs) and file (mapped volume)
|
# Write Next.js logs to both stdout (docker logs) and file (mapped volume)
|
||||||
@@ -37,14 +37,18 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
proxy:
|
proxy:
|
||||||
image: caddy:alpine
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: config/proxy/Dockerfile
|
||||||
networks:
|
networks:
|
||||||
- inventory_net
|
- inventory_net
|
||||||
ports:
|
ports:
|
||||||
- "3002:3002"
|
- ${BACKEND_SSL_PORT:-8918}:444
|
||||||
- "3003:3003"
|
- ${FRONTEND_SSL_PORT:-8919}:443
|
||||||
|
env_file:
|
||||||
|
- inventory.env
|
||||||
volumes:
|
volumes:
|
||||||
- ./Caddyfile:/etc/caddy/Caddyfile
|
- ./config/Caddyfile:/etc/caddy/Caddyfile
|
||||||
# Persist the internal Caddy certificates so users don't get new certificate warnings constantly
|
# Persist the internal Caddy certificates so users don't get new certificate warnings constantly
|
||||||
- ./data/caddy_data:/data
|
- ./data/caddy_data:/data
|
||||||
- ./data/caddy_config:/config
|
- ./data/caddy_config:/config
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
echo "📦 Preparing TFM aInventory Production Bundle..."
|
echo "📦 Preparing TFM aInventory Production Bundle..."
|
||||||
|
|
||||||
# Extract version from VERSION.json using grep to avoid macOS python/xcode stubs
|
# Extract version from frontend/VERSION.json
|
||||||
VERSION=$(grep '"version"' VERSION.json | head -n 1 | awk -F '"' '{print $4}')
|
VERSION=$(grep '"version"' frontend/VERSION.json | head -n 1 | awk -F '"' '{print $4}')
|
||||||
PROD_DIR="aInventory-PROD-v${VERSION}"
|
PROD_DIR="aInventory-PROD-v${VERSION}"
|
||||||
|
|
||||||
# Clean previous run if it exists
|
# Clean previous run if it exists
|
||||||
@@ -18,17 +18,22 @@ echo "📂 Copying application components (excluding dev artifacts)..."
|
|||||||
rsync -a --exclude 'node_modules' --exclude '.next' frontend/ "$PROD_DIR/frontend/"
|
rsync -a --exclude 'node_modules' --exclude '.next' frontend/ "$PROD_DIR/frontend/"
|
||||||
rsync -a --exclude '__pycache__' --exclude '.pytest_cache' --exclude '.venv' --exclude 'tests' backend/ "$PROD_DIR/backend/"
|
rsync -a --exclude '__pycache__' --exclude '.pytest_cache' --exclude '.venv' --exclude 'tests' backend/ "$PROD_DIR/backend/"
|
||||||
|
|
||||||
# Orchestration & Scripts
|
# Orchestration, Config & Scripts
|
||||||
|
mkdir -p "$PROD_DIR/config" "$PROD_DIR/scripts"
|
||||||
cp docker-compose.yml "$PROD_DIR/"
|
cp docker-compose.yml "$PROD_DIR/"
|
||||||
cp Caddyfile "$PROD_DIR/"
|
rsync -a config/ "$PROD_DIR/config/"
|
||||||
|
rsync -a scripts/ "$PROD_DIR/scripts/"
|
||||||
cp start_server.sh "$PROD_DIR/"
|
cp start_server.sh "$PROD_DIR/"
|
||||||
cp run_standalone.sh "$PROD_DIR/"
|
cp run_standalone.sh "$PROD_DIR/"
|
||||||
cp install_service.sh "$PROD_DIR/"
|
cp install_service.sh "$PROD_DIR/"
|
||||||
cp inventory.service.template "$PROD_DIR/"
|
cp inventory.service.template "$PROD_DIR/"
|
||||||
cp USER_GUIDE.md "$PROD_DIR/"
|
cp USER_GUIDE.md "$PROD_DIR/"
|
||||||
cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md"
|
cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md"
|
||||||
|
cp inventory.env "$PROD_DIR/"
|
||||||
|
cp deploy.sh "$PROD_DIR/"
|
||||||
cp .git_path "$PROD_DIR/" 2>/dev/null || true
|
cp .git_path "$PROD_DIR/" 2>/dev/null || true
|
||||||
cp VERSION.json "$PROD_DIR/"
|
cp frontend/VERSION.json "$PROD_DIR/"
|
||||||
|
cp frontend/VERSION.json "$PROD_DIR/frontend/"
|
||||||
|
|
||||||
# Setup persistent volume skeleton
|
# Setup persistent volume skeleton
|
||||||
mkdir -p "$PROD_DIR/data"
|
mkdir -p "$PROD_DIR/data"
|
||||||
@@ -44,7 +49,7 @@ TO RUN VIA DOCKER (Recommended):
|
|||||||
1. Install Docker Desktop or Docker Engine.
|
1. Install Docker Desktop or Docker Engine.
|
||||||
2. Run: docker-compose build
|
2. Run: docker-compose build
|
||||||
3. Run: docker-compose up -d
|
3. Run: docker-compose up -d
|
||||||
4. Access via https://<YOUR-IP>:3003 (Accept the internal security warning).
|
4. Access via https://<YOUR-IP>:8909 (Accept the internal security warning).
|
||||||
|
|
||||||
TO INSTALL AS A LINUX SYSTEM SERVICE (Optional):
|
TO INSTALL AS A LINUX SYSTEM SERVICE (Optional):
|
||||||
1. sudo ./install_service.sh
|
1. sudo ./install_service.sh
|
||||||
@@ -54,7 +59,7 @@ TO RUN BARE-METAL (No Docker):
|
|||||||
1. Install Python 3.12+ and Node.js 20+.
|
1. Install Python 3.12+ and Node.js 20+.
|
||||||
2. Ensure you have network access for npm installs.
|
2. Ensure you have network access for npm installs.
|
||||||
3. Run: ./start_server.sh
|
3. Run: ./start_server.sh
|
||||||
4. Access via https://<YOUR-IP>:3003
|
4. Access via https://<YOUR-IP>:8909
|
||||||
|
|
||||||
Note: Database and Logs will persist in the /data and /logs directories.
|
Note: Database and Logs will persist in the /data and /logs directories.
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ RUN npm run build
|
|||||||
|
|
||||||
# Step 3: Production image
|
# Step 3: Production image
|
||||||
FROM base AS runner
|
FROM base AS runner
|
||||||
|
RUN apk add --no-cache su-exec
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
ENV NODE_ENV production
|
ENV NODE_ENV production
|
||||||
@@ -38,11 +39,13 @@ RUN chown nextjs:nodejs .next
|
|||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||||
|
|
||||||
USER nextjs
|
# Copy entrypoint script
|
||||||
|
COPY entrypoint.sh /app/entrypoint.sh
|
||||||
|
RUN chmod +x /app/entrypoint.sh
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
ENV PORT 3000
|
ENV PORT 3000
|
||||||
ENV HOSTNAME "0.0.0.0"
|
ENV HOSTNAME "0.0.0.0"
|
||||||
|
|
||||||
# Note: The server.js is created by next build from the standalone output
|
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||||
CMD ["node", "server.js"]
|
|
||||||
|
|||||||
1
frontend/VERSION.json
Normal file
1
frontend/VERSION.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"version": "1.9.14", "last_build": "2026-04-13-2237", "codename": "ProtocolLock", "commit": "94f1a515"}
|
||||||
@@ -83,7 +83,7 @@ export default function AdminPage() {
|
|||||||
setBackups(b);
|
setBackups(b);
|
||||||
setDbStats(s);
|
setDbStats(s);
|
||||||
setDbSettings(st);
|
setDbSettings(st);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
toast.error("Failed to load admin data");
|
toast.error("Failed to load admin data");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -101,7 +101,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.createUser({ username: name, password: pwd, role: 'user' });
|
await inventoryApi.createUser({ username: name, password: pwd, role: 'user' });
|
||||||
toast.success("User created successfully");
|
toast.success("User created successfully");
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Failed to create user");
|
toast.error("Failed to create user");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -114,7 +114,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.deleteUser(id);
|
await inventoryApi.deleteUser(id);
|
||||||
toast.success("User removed");
|
toast.success("User removed");
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Delete failed");
|
toast.error("Delete failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -128,7 +128,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.createCategory({ name, description: desc });
|
await inventoryApi.createCategory({ name, description: desc });
|
||||||
toast.success("Category added");
|
toast.success("Category added");
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Failed to add category");
|
toast.error("Failed to add category");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -140,7 +140,7 @@ export default function AdminPage() {
|
|||||||
toast.success("Category updated");
|
toast.success("Category updated");
|
||||||
setEditingCategory(null);
|
setEditingCategory(null);
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Update failed");
|
toast.error("Update failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -152,7 +152,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.deleteCategory(id);
|
await inventoryApi.deleteCategory(id);
|
||||||
toast.success("Category removed");
|
toast.success("Category removed");
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error(err.response?.data?.detail || "Delete failed");
|
toast.error(err.response?.data?.detail || "Delete failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -167,7 +167,7 @@ export default function AdminPage() {
|
|||||||
toast.success("User updated successfully");
|
toast.success("User updated successfully");
|
||||||
setEditingUser(null);
|
setEditingUser(null);
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Update failed");
|
toast.error("Update failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -183,7 +183,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.triggerBackup();
|
await inventoryApi.triggerBackup();
|
||||||
toast.success("Snapshot created successfully");
|
toast.success("Snapshot created successfully");
|
||||||
loadData();
|
loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Backup failed");
|
toast.error("Backup failed");
|
||||||
} finally {
|
} finally {
|
||||||
setIsBackingUp(false);
|
setIsBackingUp(false);
|
||||||
@@ -198,7 +198,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.restoreDatabase(filename);
|
await inventoryApi.restoreDatabase(filename);
|
||||||
toast.success("Database restored! Reloading system...", { id: loadingToast });
|
toast.success("Database restored! Reloading system...", { id: loadingToast });
|
||||||
setTimeout(() => window.location.reload(), 2000);
|
setTimeout(() => window.location.reload(), 2000);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Restore failed", { id: loadingToast });
|
toast.error("Restore failed", { id: loadingToast });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -208,7 +208,7 @@ export default function AdminPage() {
|
|||||||
await inventoryApi.updateDbSettings(newSettings);
|
await inventoryApi.updateDbSettings(newSettings);
|
||||||
toast.success("System policy updated");
|
toast.success("System policy updated");
|
||||||
setDbSettings(newSettings);
|
setDbSettings(newSettings);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Failed to update settings");
|
toast.error("Failed to update settings");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -218,7 +218,7 @@ export default function AdminPage() {
|
|||||||
try {
|
try {
|
||||||
await inventoryApi.updateLdapConfig(ldapConfig);
|
await inventoryApi.updateLdapConfig(ldapConfig);
|
||||||
toast.success("Enterprise configuration updated");
|
toast.success("Enterprise configuration updated");
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Failed to update LDAP config");
|
toast.error("Failed to update LDAP config");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ export default function InventoryPage() {
|
|||||||
// Sync local DB
|
// Sync local DB
|
||||||
await db.items.clear();
|
await db.items.clear();
|
||||||
await db.items.bulkPut(res);
|
await db.items.bulkPut(res);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error("Failed to load backend data", err);
|
console.error("Failed to load backend data", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -149,7 +149,7 @@ export default function InventoryPage() {
|
|||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
setSelectedItem(updated as Item);
|
setSelectedItem(updated as Item);
|
||||||
await loadData();
|
await loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
toast.error("Failed to update item");
|
toast.error("Failed to update item");
|
||||||
}
|
}
|
||||||
@@ -167,7 +167,7 @@ export default function InventoryPage() {
|
|||||||
toast.success("Item deleted");
|
toast.success("Item deleted");
|
||||||
setSelectedItem(null);
|
setSelectedItem(null);
|
||||||
await loadData();
|
await loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
toast.error("Failed to delete item");
|
toast.error("Failed to delete item");
|
||||||
}
|
}
|
||||||
@@ -183,7 +183,7 @@ export default function InventoryPage() {
|
|||||||
toast.success("Category updated");
|
toast.success("Category updated");
|
||||||
setEditingCategory(null);
|
setEditingCategory(null);
|
||||||
await loadData();
|
await loadData();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
toast.error("Update failed");
|
toast.error("Update failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -88,37 +88,56 @@ export default function LoginPage() {
|
|||||||
<User size={32} />
|
<User size={32} />
|
||||||
</div>
|
</div>
|
||||||
<h2 className="text-2xl font-black text-white tracking-tight">Identity Check</h2>
|
<h2 className="text-2xl font-black text-white tracking-tight">Identity Check</h2>
|
||||||
<p className="text-slate-500 text-sm">Select operator profile or use enterprise login</p>
|
<p className="text-slate-500 text-sm">Select operator profile or use direct login</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
{!selectedUserForLogin && !isEnterprise ? (
|
{!selectedUserForLogin && !isEnterprise ? (
|
||||||
<>
|
<>
|
||||||
{users.map(user => (
|
{users.length > 0 ? (
|
||||||
<button
|
<>
|
||||||
key={user.id}
|
{users.map(user => (
|
||||||
onClick={() => handleSelectUser(user)}
|
<button
|
||||||
className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between"
|
key={user.id}
|
||||||
>
|
onClick={() => handleSelectUser(user)}
|
||||||
<div className="flex items-center gap-3">
|
className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between"
|
||||||
<div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
|
>
|
||||||
{user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
|
<div className="flex items-center gap-3">
|
||||||
</div>
|
<div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
|
||||||
<div>
|
{user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
|
||||||
<p className="text-white font-black text-sm">{user.username}</p>
|
</div>
|
||||||
<p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
|
<div>
|
||||||
</div>
|
<p className="text-white font-black text-sm">{user.username}</p>
|
||||||
</div>
|
<p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
|
||||||
<ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
|
</div>
|
||||||
</button>
|
</div>
|
||||||
))}
|
<ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
|
||||||
<div className="pt-2">
|
</button>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="text-center p-4 text-slate-500 text-xs font-bold animate-pulse">
|
||||||
|
Connectivity issues? Use manual login below.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="pt-2 grid grid-cols-2 gap-3">
|
||||||
<button
|
<button
|
||||||
onClick={() => setIsEnterprise(true)}
|
onClick={() => setIsEnterprise(true)}
|
||||||
className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-primary hover:border-primary/40 transition-all font-bold text-xs"
|
className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-white hover:border-slate-500 transition-all font-bold text-[10px]"
|
||||||
>
|
>
|
||||||
<Shield size={14} />
|
<Lock size={12} />
|
||||||
Enterprise Login
|
Enterprise
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedUserForLogin({ username: '' });
|
||||||
|
// We use an empty username object to trigger the manual input view
|
||||||
|
}}
|
||||||
|
className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 transition-all font-bold text-[10px]"
|
||||||
|
>
|
||||||
|
<User size={12} />
|
||||||
|
Manual Login
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -180,10 +199,26 @@ export default function LoginPage() {
|
|||||||
</button>
|
</button>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-bold text-slate-500">Logging in as</p>
|
<p className="text-sm font-bold text-slate-500">Logging in as</p>
|
||||||
<p className="text-white font-black">{selectedUserForLogin.username}</p>
|
<p className="text-white font-black">{selectedUserForLogin.username || "Manual Input"}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!selectedUserForLogin.username && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs font-black text-slate-500 px-1">Username</label>
|
||||||
|
<div className="relative">
|
||||||
|
<User className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
autoFocus
|
||||||
|
onChange={(e) => setSelectedUserForLogin({...selectedUserForLogin, username: e.target.value})}
|
||||||
|
className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
|
||||||
|
placeholder="Admin"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-xs font-black text-slate-500 px-1">Password</label>
|
<label className="text-xs font-black text-slate-500 px-1">Password</label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -209,9 +244,10 @@ export default function LoginPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{users.length === 0 && (
|
{/* Progress bar hint */}
|
||||||
<div className="text-center p-8 text-slate-500 animate-pulse">
|
{users.length === 0 && !selectedUserForLogin && !isEnterprise && (
|
||||||
Initializing users...
|
<div className="w-full bg-slate-800 h-1 rounded-full overflow-hidden">
|
||||||
|
<div className="bg-primary h-full animate-progress-fast shadow-[0_0_8px_rgba(var(--primary-rgb),0.5)]"></div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ export default function LogsPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
setAuditLogs(enrichedLogs);
|
setAuditLogs(enrichedLogs);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error("Critical log load failure:", err);
|
console.error("Critical log load failure:", err);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -289,7 +289,7 @@ export default function LogsPage() {
|
|||||||
|
|
||||||
{selectedLog.target_snapshot && (() => {
|
{selectedLog.target_snapshot && (() => {
|
||||||
try {
|
try {
|
||||||
const snap = JSON.parse(selectedLog.target_snapshot);
|
const snap = JSON.parse(selectedLog.target_snapshot) as Record<string, any>;
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -299,12 +299,12 @@ export default function LogsPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
{Object.entries(snap).map(([key, val]) => (
|
{Object.entries(snap).map(([key, val]) => (
|
||||||
val && key !== 'image_url' && (
|
(val && key !== 'image_url') ? (
|
||||||
<div key={key} className="bg-slate-950/30 p-3 rounded-xl border border-slate-800/40">
|
<div key={key} className="bg-slate-950/30 p-3 rounded-xl border border-slate-800/40">
|
||||||
<p className="text-[8px] font-black text-slate-600 uppercase mb-1">{key.replace('_', ' ')}</p>
|
<p className="text-[8px] font-black text-slate-600 uppercase mb-1">{key.replace('_', ' ')}</p>
|
||||||
<p className="text-xs font-bold text-slate-300 truncate" title={String(val)}>{String(val)}</p>
|
<p className="text-xs font-bold text-slate-300 truncate" title={String(val)}>{String(val)}</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
) : null
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ import { generateBarcode128, getQRCodeURL } from '@/lib/labels';
|
|||||||
import { clsx, type ClassValue } from 'clsx';
|
import { clsx, type ClassValue } from 'clsx';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import versionData from '../../VERSION.json';
|
import versionData from '../VERSION.json';
|
||||||
|
|
||||||
interface User {
|
interface User {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -342,7 +342,7 @@ export default function Home() {
|
|||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
setSelectedItem(updated as Item);
|
setSelectedItem(updated as Item);
|
||||||
await loadInventory();
|
await loadInventory();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
toast.error("Failed to update item");
|
toast.error("Failed to update item");
|
||||||
}
|
}
|
||||||
@@ -360,7 +360,7 @@ export default function Home() {
|
|||||||
toast.success("Item deleted from catalog");
|
toast.success("Item deleted from catalog");
|
||||||
setSelectedItem(null);
|
setSelectedItem(null);
|
||||||
await loadInventory();
|
await loadInventory();
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
toast.error("Failed to delete item");
|
toast.error("Failed to delete item");
|
||||||
}
|
}
|
||||||
@@ -890,7 +890,7 @@ export default function Home() {
|
|||||||
<Printer size={14} /> Print Label
|
<Printer size={14} /> Print Label
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => { setQuery(box.toLowerCase()); setShowBoxManager(false); }}
|
onClick={() => { setSearchQuery(box.toLowerCase()); setShowBoxManager(false); }}
|
||||||
className="px-4 py-3 bg-slate-900 border border-slate-800 text-slate-400 text-xs font-bold rounded-xl hover:bg-slate-800"
|
className="px-4 py-3 bg-slate-900 border border-slate-800 text-slate-400 text-xs font-bold rounded-xl hover:bg-slate-800"
|
||||||
>
|
>
|
||||||
View
|
View
|
||||||
@@ -1004,7 +1004,7 @@ export default function Home() {
|
|||||||
<footer className="mt-20 mb-8 flex flex-col items-center gap-2 opacity-30">
|
<footer className="mt-20 mb-8 flex flex-col items-center gap-2 opacity-30">
|
||||||
<p className="text-xs font-bold">Powered by TFM Group Software</p>
|
<p className="text-xs font-bold">Powered by TFM Group Software</p>
|
||||||
<div className="h-px w-12 bg-slate-800" />
|
<div className="h-px w-12 bg-slate-800" />
|
||||||
<p className="text-[9px] font-mono">v{versionData.version} • {versionData.last_build} • BUILD: dev-{versionData.commit}</p>
|
<p className="text-[9px] font-mono">v{versionData.version} • {versionData.last_build} • BUILD: dev-{(versionData as any).commit || 'N/A'}</p>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</PageShell>
|
</PageShell>
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
|
|||||||
Html5QrcodeSupportedFormats.CODE_39,
|
Html5QrcodeSupportedFormats.CODE_39,
|
||||||
Html5QrcodeSupportedFormats.EAN_13,
|
Html5QrcodeSupportedFormats.EAN_13,
|
||||||
Html5QrcodeSupportedFormats.UPC_A,
|
Html5QrcodeSupportedFormats.UPC_A,
|
||||||
Html5QrcodeSupportedFormats.DATAMATRIX
|
Html5QrcodeSupportedFormats.DATA_MATRIX
|
||||||
],
|
],
|
||||||
videoConstraints: {
|
videoConstraints: {
|
||||||
facingMode: "environment"
|
facingMode: "environment"
|
||||||
|
|||||||
30
frontend/entrypoint.sh
Normal file
30
frontend/entrypoint.sh
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# =============================================================================
|
||||||
|
# frontend/entrypoint.sh
|
||||||
|
# =============================================================================
|
||||||
|
# Docker container entrypoint for TFM aInventory frontend.
|
||||||
|
# Fixes permissions for the logs volume and starts the Node.js server.
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Fix permissions for the logs directory (useful if mounted as a volume)
|
||||||
|
if [ -d "/app/logs" ]; then
|
||||||
|
echo "🐳 [Docker] Fixing /app/logs permissions..."
|
||||||
|
chown -R nextjs:nodejs /app/logs
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Generate network.json for frontend runtime discovery
|
||||||
|
echo "🐳 [Docker] Generating public/network.json..."
|
||||||
|
cat <<EOF > /app/public/network.json
|
||||||
|
{
|
||||||
|
"SERVER_IP": "${SERVER_IP:-localhost}",
|
||||||
|
"BACKEND_PORT": ${BACKEND_PORT:-8000},
|
||||||
|
"BACKEND_SSL_PORT": ${BACKEND_SSL_PORT:-8908}
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
chown nextjs:nodejs /app/public/network.json
|
||||||
|
|
||||||
|
# Hand off to the application server as the nextjs user
|
||||||
|
echo "🐳 [Docker] Starting Next.js standalone server as nextjs user..."
|
||||||
|
exec su-exec nextjs node server.js
|
||||||
@@ -1,20 +1,48 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { getToken, clearAuth } from './auth';
|
import { getToken, clearAuth } from './auth';
|
||||||
|
|
||||||
export const getBackendUrl = () => {
|
// Cached config to avoid repeated fetches
|
||||||
if (typeof window === 'undefined') return 'http://localhost:8000';
|
let cachedConfig: any = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the network configuration from the public/network.json file.
|
||||||
|
* This file is generated at startup by start_server.sh or docker-compose.
|
||||||
|
*/
|
||||||
|
export const getNetworkConfig = async () => {
|
||||||
|
if (cachedConfig) return cachedConfig;
|
||||||
|
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return { SERVER_IP: 'localhost', BACKEND_PORT: 8000, BACKEND_SSL_PORT: 8908 };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/network.json');
|
||||||
|
if (!response.ok) throw new Error("Config not found");
|
||||||
|
cachedConfig = await response.json();
|
||||||
|
return cachedConfig;
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("Network config not found, using compiled defaults.");
|
||||||
|
// Defaults matching the initial reserve ports in case network.json is missing
|
||||||
|
return { SERVER_IP: 'localhost', BACKEND_PORT: 8906, BACKEND_SSL_PORT: 8908 };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getBackendUrl = async () => {
|
||||||
|
const config = await getNetworkConfig();
|
||||||
|
|
||||||
|
if (typeof window === 'undefined') return `http://localhost:${config.BACKEND_PORT}`;
|
||||||
|
|
||||||
const host = window.location.hostname;
|
const host = window.location.hostname;
|
||||||
|
|
||||||
// If we are on HTTPS (Proxy/Mobile mode), we use port 3002 for the backend
|
// If we are on HTTPS (Proxy/Mobile mode), we use the SSL port for the backend
|
||||||
if (window.location.protocol === 'https:') {
|
if (window.location.protocol === 'https:') {
|
||||||
if (host.includes('.loca.lt')) {
|
if (host.includes('.loca.lt')) {
|
||||||
return 'https://inventory-ai-api.loca.lt';
|
return 'https://inventory-ai-api.loca.lt';
|
||||||
}
|
}
|
||||||
return `https://${host}:3002`;
|
return `https://${host}:${config.BACKEND_SSL_PORT}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `http://${host}:8000`;
|
return `http://${host}:${config.BACKEND_PORT}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,9 +51,9 @@ export const getBackendUrl = () => {
|
|||||||
*/
|
*/
|
||||||
const axiosInstance = axios.create({});
|
const axiosInstance = axios.create({});
|
||||||
|
|
||||||
axiosInstance.interceptors.request.use((config) => {
|
axiosInstance.interceptors.request.use(async (config) => {
|
||||||
if (!config.baseURL) {
|
if (!config.baseURL) {
|
||||||
config.baseURL = getBackendUrl(); // called at request time — always correct
|
config.baseURL = await getBackendUrl(); // called at request time — always correct
|
||||||
}
|
}
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (token) {
|
if (token) {
|
||||||
@@ -110,7 +138,8 @@ export const inventoryApi = {
|
|||||||
// Users
|
// Users
|
||||||
getUsers: async () => {
|
getUsers: async () => {
|
||||||
// [C-01] Public endpoint — use plain axios to avoid JWT interceptor
|
// [C-01] Public endpoint — use plain axios to avoid JWT interceptor
|
||||||
const res = await axios.get(`${getBackendUrl()}/users/`);
|
const baseUrl = await getBackendUrl();
|
||||||
|
const res = await axios.get(`${baseUrl}/users/`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -121,7 +150,8 @@ export const inventoryApi = {
|
|||||||
|
|
||||||
login: async (credentials: any) => {
|
login: async (credentials: any) => {
|
||||||
// [C-01] Login endpoint — NU adaug token header (login e public)
|
// [C-01] Login endpoint — NU adaug token header (login e public)
|
||||||
const res = await axios.post(`${getBackendUrl()}/users/login`, credentials);
|
const baseUrl = await getBackendUrl();
|
||||||
|
const res = await axios.post(`${baseUrl}/users/login`, credentials);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
1
frontend/public/sw.js
Normal file
1
frontend/public/sw.js
Normal file
File diff suppressed because one or more lines are too long
1
frontend/public/workbox-4754cb34.js
Normal file
1
frontend/public/workbox-4754cb34.js
Normal file
File diff suppressed because one or more lines are too long
19
inventory.env
Normal file
19
inventory.env
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# TFM aInventory - Docker Compose Environment
|
||||||
|
# =============================================================================
|
||||||
|
# This file is used by Docker Compose for host-side port mapping.
|
||||||
|
# It should match the values in config/network_config.env
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
SERVER_IP=192.168.84.113
|
||||||
|
|
||||||
|
# Backend Ports
|
||||||
|
BACKEND_PORT=8916
|
||||||
|
BACKEND_SSL_PORT=8918
|
||||||
|
|
||||||
|
# Frontend Ports
|
||||||
|
FRONTEND_PORT=8917
|
||||||
|
FRONTEND_SSL_PORT=8919
|
||||||
|
|
||||||
|
# Security
|
||||||
|
JWT_SECRET_KEY=change_me_in_production
|
||||||
@@ -7,17 +7,38 @@ echo "🚀 Starting TFM aInventory in Standalone Mode..."
|
|||||||
# Trapping termination signals to clean up child processes
|
# Trapping termination signals to clean up child processes
|
||||||
trap "echo 'Stopping all processes...'; kill 0" SIGINT SIGTERM EXIT
|
trap "echo 'Stopping all processes...'; kill 0" SIGINT SIGTERM EXIT
|
||||||
|
|
||||||
# --- CONFIGURATION (Match start_server.sh) ---
|
# --- CONFIGURATION (Default values, overridden by network_configinventory.env) ---
|
||||||
BACKEND_PORT=8000
|
BACKEND_PORT=8000
|
||||||
FRONTEND_PORT=3001
|
FRONTEND_PORT=3001
|
||||||
BACKEND_SSL_PORT=3002
|
BACKEND_SSL_PORT=3002
|
||||||
FRONTEND_SSL_PORT=3003
|
FRONTEND_SSL_PORT=3003
|
||||||
|
SERVER_IP="localhost"
|
||||||
|
|
||||||
|
# Load Configuration from file if it exists
|
||||||
|
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/inventory.env"
|
||||||
|
if [ -f "$CONFIG_PATH" ]; then
|
||||||
|
echo "⚙️ Loading network configuration from $CONFIG_PATH..."
|
||||||
|
export $(grep -v '^#' "$CONFIG_PATH" | xargs)
|
||||||
|
fi
|
||||||
|
|
||||||
# 1. Activate Environment
|
# 1. Activate Environment
|
||||||
if [ -d ".venv" ]; then
|
if [ -d ".venv" ]; then
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# 1.5 Sync Network Config to Frontend
|
||||||
|
echo "🔌 Syncing network configuration to frontend..."
|
||||||
|
mkdir -p frontend/public
|
||||||
|
cat <<EOF > frontend/public/network.json
|
||||||
|
{
|
||||||
|
"SERVER_IP": "$SERVER_IP",
|
||||||
|
"BACKEND_PORT": $BACKEND_PORT,
|
||||||
|
"BACKEND_SSL_PORT": $BACKEND_SSL_PORT,
|
||||||
|
"FRONTEND_PORT": $FRONTEND_PORT,
|
||||||
|
"FRONTEND_SSL_PORT": $FRONTEND_SSL_PORT
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
# 2. Start Backend (No Reload for Prod)
|
# 2. Start Backend (No Reload for Prod)
|
||||||
echo "🔥 Starting Backend (Uvicorn)..."
|
echo "🔥 Starting Backend (Uvicorn)..."
|
||||||
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT &
|
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT &
|
||||||
|
|||||||
@@ -32,10 +32,10 @@ mkdir -p "$DATA_DIR"
|
|||||||
mkdir -p "$LOGS_DIR"
|
mkdir -p "$LOGS_DIR"
|
||||||
|
|
||||||
# 2. Copy LDAP config from example template if no active config exists yet
|
# 2. Copy LDAP config from example template if no active config exists yet
|
||||||
# NOTE: The application reads LDAP config from backend/config/ldap_config.json
|
# NOTE: The application reads LDAP config from config/ldap_config.json
|
||||||
# (see backend/routers/users.py → get_ldap_config())
|
# (see backend/routers/users.py → get_ldap_config())
|
||||||
LDAP_CONFIG="$PROJECT_ROOT/backend/config/ldap_config.json"
|
LDAP_CONFIG="$PROJECT_ROOT/config/ldap_config.json"
|
||||||
LDAP_EXAMPLE="$PROJECT_ROOT/backend/config/ldap_config.json.example"
|
LDAP_EXAMPLE="$PROJECT_ROOT/config/ldap_config.json.example"
|
||||||
|
|
||||||
if [ ! -f "$LDAP_CONFIG" ]; then
|
if [ ! -f "$LDAP_CONFIG" ]; then
|
||||||
if [ -f "$LDAP_EXAMPLE" ]; then
|
if [ -f "$LDAP_EXAMPLE" ]; then
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
VERSION_FILE = 'VERSION.json'
|
VERSION_FILE = 'frontend/VERSION.json'
|
||||||
GIT_PATH_FILE = '.git_path'
|
GIT_PATH_FILE = '.git_path'
|
||||||
|
|
||||||
def get_git_path():
|
def get_git_path():
|
||||||
@@ -53,8 +53,15 @@ def main():
|
|||||||
data['version'] = new_version
|
data['version'] = new_version
|
||||||
data['last_build'] = datetime.now().strftime("%Y-%m-%d-%H%M")
|
data['last_build'] = datetime.now().strftime("%Y-%m-%d-%H%M")
|
||||||
|
|
||||||
|
# Get current git commit (short)
|
||||||
|
try:
|
||||||
|
commit_hash = run_command([git, 'rev-parse', '--short', 'HEAD'])
|
||||||
|
data['commit'] = commit_hash
|
||||||
|
except Exception:
|
||||||
|
data['commit'] = 'unknown'
|
||||||
|
|
||||||
# Optional: Rotate changelog if needed, but for now just update version
|
# Optional: Rotate changelog if needed, but for now just update version
|
||||||
print(f"Incrementing version: {old_version} -> {new_version}")
|
print(f"Incrementing version: {old_version} -> {new_version} (commit: {data['commit']})")
|
||||||
|
|
||||||
with open(VERSION_FILE, 'w') as f:
|
with open(VERSION_FILE, 'w') as f:
|
||||||
json.dump(data, f, indent=2)
|
json.dump(data, f, indent=2)
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
# --- CONFIGURATION ---
|
# --- CONFIGURATION (Default values, will be overridden by network_configinventory.env) ---
|
||||||
BACKEND_PORT=8000
|
BACKEND_PORT=8000
|
||||||
FRONTEND_PORT=3001
|
FRONTEND_PORT=3001
|
||||||
BACKEND_SSL_PORT=3002
|
BACKEND_SSL_PORT=3002
|
||||||
FRONTEND_SSL_PORT=3003
|
FRONTEND_SSL_PORT=3003
|
||||||
|
SERVER_IP="localhost"
|
||||||
|
|
||||||
|
# Load Configuration from file if it exists
|
||||||
|
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/inventory.env"
|
||||||
|
if [ -f "$CONFIG_PATH" ]; then
|
||||||
|
echo "⚙️ Loading network configuration from $CONFIG_PATH..."
|
||||||
|
# Export variables from inventory.env file (ignoring comments and empty lines)
|
||||||
|
export $(grep -v '^#' "$CONFIG_PATH" | xargs)
|
||||||
|
fi
|
||||||
|
|
||||||
# Add common Mac paths for npm/node
|
# Add common Mac paths for npm/node
|
||||||
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
|
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
|
||||||
@@ -39,6 +48,18 @@ export LOGS_DIR="$(cd "$(dirname "$0")" && pwd)/logs"
|
|||||||
echo "🔧 Initializing runtime data directories..."
|
echo "🔧 Initializing runtime data directories..."
|
||||||
bash "$(cd "$(dirname "$0")" && pwd)/scripts/init_data.sh"
|
bash "$(cd "$(dirname "$0")" && pwd)/scripts/init_data.sh"
|
||||||
|
|
||||||
|
# 4.1 Sync Network Config to Frontend for runtime discovery
|
||||||
|
echo "🔌 Syncing network configuration to frontend..."
|
||||||
|
cat <<EOF > frontend/public/network.json
|
||||||
|
{
|
||||||
|
"SERVER_IP": "$SERVER_IP",
|
||||||
|
"BACKEND_PORT": $BACKEND_PORT,
|
||||||
|
"BACKEND_SSL_PORT": $BACKEND_SSL_PORT,
|
||||||
|
"FRONTEND_PORT": $FRONTEND_PORT,
|
||||||
|
"FRONTEND_SSL_PORT": $FRONTEND_SSL_PORT
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
echo "🔥 Starting Backend on port $BACKEND_PORT..."
|
echo "🔥 Starting Backend on port $BACKEND_PORT..."
|
||||||
echo " CORS origins: $ALLOWED_ORIGINS"
|
echo " CORS origins: $ALLOWED_ORIGINS"
|
||||||
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT --reload &
|
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT --reload &
|
||||||
@@ -67,8 +88,8 @@ echo -e "${GREEN}${BOLD} 🚀 TFM aInventory UNIFIED ACCESS${NC}"
|
|||||||
echo -e "${GREEN}=======================================================${NC}"
|
echo -e "${GREEN}=======================================================${NC}"
|
||||||
echo ""
|
echo ""
|
||||||
echo -e " USE THIS URL ON BOTH DESKTOP & MOBILE:"
|
echo -e " USE THIS URL ON BOTH DESKTOP & MOBILE:"
|
||||||
echo -e " 👉 ${GREEN}${BOLD}https://$LOCAL_IP:3003${NC}"
|
echo -e " 👉 ${GREEN}${BOLD}https://$LOCAL_IP:$FRONTEND_SSL_PORT${NC}"
|
||||||
echo -e " (Or ${GREEN}https://localhost:3003${NC} on this Mac)"
|
echo -e " (Or ${GREEN}https://localhost:$FRONTEND_SSL_PORT${NC} on this Mac)"
|
||||||
echo ""
|
echo ""
|
||||||
echo -e " ${YELLOW}${BOLD}NOTE:${NC} If you see a 'Not Private' warning,"
|
echo -e " ${YELLOW}${BOLD}NOTE:${NC} If you see a 'Not Private' warning,"
|
||||||
echo -e " Click 'Advanced' -> 'Proceed' to continue."
|
echo -e " Click 'Advanced' -> 'Proceed' to continue."
|
||||||
|
|||||||
Reference in New Issue
Block a user