🔒 Remove hardcoded passwords, add first-run setup wizard

This commit is contained in:
2026-06-15 23:30:22 +01:00
parent d470966915
commit 7cec72d423
3 changed files with 225 additions and 40 deletions

View File

@@ -105,39 +105,18 @@ COMPONENT_TEMPLATES = {
def seed_database():
"""Create tables and insert preseed data if missing."""
"""Create tables and seed services (no default users — first-run setup creates them)."""
Base.metadata.create_all(bind=engine)
db = SessionLocal()
try:
# Seed users
if not db.query(User).filter(User.username == "admin").first():
db.add(
User(
username="admin",
password_hash=hash_password("admin123"),
display_name="Administrator",
role="admin",
)
)
if not db.query(User).filter(User.username == "viewer").first():
db.add(
User(
username="viewer",
password_hash=hash_password("viewer123"),
display_name="Viewer",
role="viewer",
)
)
# Seed services + components
# Seed services + components (only if no services exist yet)
if not db.query(Service).first():
for name, desc, sell, cost in [
("Atlas", "Core storage service", 4000.0, 2000.0),
("Atlas+", "Premium storage + backup service", 5000.0, 2800.0),
("Rif", "Core server service", 3500.0, 1700.0),
("Rif+", "Premium server + backup service", 4500.0, 2200.0),
]:
existing = db.query(Service).filter(Service.name == name).first()
if not existing:
svc = Service(
name=name,
description=desc,
@@ -146,9 +125,8 @@ def seed_database():
active=True,
)
db.add(svc)
db.flush() # get the id
db.flush()
# Add component templates
for cname, ucost, usell, qty, notes in COMPONENT_TEMPLATES.get(name, []):
db.add(
ServiceComponent(
@@ -160,7 +138,6 @@ def seed_database():
notes=notes,
)
)
db.commit()
finally:
db.close()
@@ -168,6 +145,19 @@ def seed_database():
seed_database()
# ---------------------------------------------------------------------------
# Helper: check if setup is complete
# ---------------------------------------------------------------------------
def is_setup_complete(db: Session) -> bool:
"""Returns True if at least one admin user exists."""
return db.query(User).filter(User.role == "admin").first() is not None
def require_setup(db: Session = Depends(get_db)):
"""Dependency that raises 404 if setup is not complete (caller handles redirect)."""
return is_setup_complete(db)
# ---------------------------------------------------------------------------
# Helper: compute monthly P&L
# ---------------------------------------------------------------------------
@@ -552,9 +542,80 @@ def api_dashboard(db: Session = Depends(get_db)):
# ---------------------------------------------------------------------------
# Frontend Routes
# ---------------------------------------------------------------------------
@app.get("/setup", response_class=HTMLResponse)
def setup_page(request: Request, db: Session = Depends(get_db)):
"""Serve the first-time setup page."""
if is_setup_complete(db):
return RedirectResponse(url="/login")
return templates.TemplateResponse(request, "setup.html")
class SetupInput(BaseModel):
admin_username: str
admin_password: str
admin_display: str = "Administrator"
@app.post("/api/setup")
def api_setup(
input: SetupInput,
db: Session = Depends(get_db),
):
"""Create the first admin user (only works if no admin exists yet)."""
if is_setup_complete(db):
raise HTTPException(status_code=400, detail="Setup already completed")
if not input.admin_username.strip() or len(input.admin_password) < 4:
raise HTTPException(status_code=400, detail="Username required, password min 4 chars")
# Create admin
admin = User(
username=input.admin_username.strip(),
password_hash=hash_password(input.admin_password),
display_name=input.admin_display.strip() or input.admin_username.strip(),
role="admin",
)
db.add(admin)
# Create guest viewer
import secrets
guest_pass = secrets.token_hex(6)
viewer = User(
username="viewer",
password_hash=hash_password(guest_pass),
display_name="Viewer",
role="viewer",
)
db.add(viewer)
db.commit()
db.refresh(admin)
db.refresh(viewer)
# Auto-login as admin
token = create_access_token(admin.id, admin.role)
response = JSONResponse({
"token": token,
"guest_password": guest_pass,
"user": {
"id": admin.id,
"username": admin.username,
"display_name": admin.display_name,
"role": admin.role,
},
})
response.set_cookie(
key="token", value=token,
httponly=True, max_age=86400, samesite="lax",
secure=False, path="/",
)
return response
@app.get("/login", response_class=HTMLResponse)
def login_page(request: Request):
"""Serve the login page."""
def login_page(request: Request, db: Session = Depends(get_db)):
"""Serve the login page. Redirect to /setup if no admin exists."""
if not is_setup_complete(db):
return RedirectResponse(url="/setup")
return templates.TemplateResponse(request, "login.html")
@@ -565,6 +626,8 @@ def dashboard_page(
db: Session = Depends(get_db),
):
"""Serve the dashboard page."""
if not is_setup_complete(db):
return RedirectResponse(url="/setup")
if not current_user:
return RedirectResponse(url="/login")
current_month = datetime.now(timezone.utc).strftime("%Y-%m")
@@ -589,6 +652,8 @@ def transactions_page(
db: Session = Depends(get_db),
):
"""Serve the transactions page."""
if not is_setup_complete(db):
return RedirectResponse(url="/setup")
if not current_user:
return RedirectResponse(url="/login")
current_month = datetime.now(timezone.utc).strftime("%Y-%m")
@@ -610,6 +675,8 @@ def services_page(
db: Session = Depends(get_db),
):
"""Serve the services management page."""
if not is_setup_complete(db):
return RedirectResponse(url="/setup")
if not current_user:
return RedirectResponse(url="/login")
services = db.query(Service).order_by(Service.name).all()

View File

@@ -5,7 +5,10 @@
<div class="col-md-5 col-lg-4">
<div class="card shadow">
<div class="card-body p-4">
<h3 class="card-title text-center mb-4">🔐 Sign In</h3>
<div class="text-center mb-4">
<span style="font-size: 2.5rem;">🏔️</span>
<h4 class="mt-2">Vela Platform</h4>
</div>
<form id="loginForm">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
@@ -20,9 +23,6 @@
<div id="loginError" class="alert alert-danger d-none py-2"></div>
<button type="submit" class="btn btn-primary w-100">Sign In</button>
</form>
<p class="text-muted text-center mt-3 mb-0" style="font-size: 0.85rem;">
Demo: admin / admin123 &nbsp;|&nbsp; viewer / viewer123
</p>
</div>
</div>
</div>

View File

@@ -0,0 +1,118 @@
{% extends "base.html" %}
{% block title %}Setup — Vela Platform{% endblock %}
{% block content %}
<div class="row justify-content-center mt-4">
<div class="col-md-6 col-lg-5">
<div class="card shadow">
<div class="card-body p-4">
<div class="text-center mb-4">
<span style="font-size: 3rem;">🏔️</span>
<h3 class="mt-2">Welcome to Vela Platform</h3>
<p class="text-muted">Let's set up your admin account to get started.</p>
</div>
<form id="setupForm">
<div class="mb-3">
<label for="adminUsername" class="form-label">Admin Username</label>
<input type="text" class="form-control" id="adminUsername" name="admin_username"
placeholder="e.g., admin" required autofocus>
</div>
<div class="mb-3">
<label for="adminPassword" class="form-label">Admin Password</label>
<input type="password" class="form-control" id="adminPassword" name="admin_password"
placeholder="Min 4 characters" minlength="4" required>
</div>
<div class="mb-3">
<label for="adminDisplay" class="form-label">Display Name (optional)</label>
<input type="text" class="form-control" id="adminDisplay" name="admin_display"
placeholder="e.g., Administrator">
</div>
<div id="setupError" class="alert alert-danger d-none py-2"></div>
<button type="submit" class="btn btn-primary w-100 btn-lg">
<i class="bi bi-rocket-takeoff"></i> Create Account &amp; Get Started
</button>
</form>
<div id="setupResult" class="d-none mt-3">
<div class="alert alert-success py-2">
<strong>✅ Setup complete!</strong> Redirecting...
</div>
<div class="card bg-body-tertiary mt-3">
<div class="card-body">
<h6>👤 <span id="resultUsername"></span></h6>
<p class="mb-1 text-muted" style="font-size:0.9rem;">
🔑 Password set — save it somewhere safe.
</p>
<hr>
<h6>👁️ Guest account created</h6>
<p class="mb-0" style="font-size:0.9rem;">
Username: <code>viewer</code><br>
Password: <code id="resultGuestPass"></code>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
document.getElementById('setupForm').addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target;
const errorEl = document.getElementById('setupError');
const resultEl = document.getElementById('setupResult');
errorEl.classList.add('d-none');
resultEl.classList.add('d-none');
const data = {
admin_username: document.getElementById('adminUsername').value.trim(),
admin_password: document.getElementById('adminPassword').value,
admin_display: document.getElementById('adminDisplay').value.trim() || document.getElementById('adminUsername').value.trim(),
};
if (!data.admin_username) {
errorEl.textContent = 'Username is required';
errorEl.classList.remove('d-none');
return;
}
if (data.admin_password.length < 4) {
errorEl.textContent = 'Password must be at least 4 characters';
errorEl.classList.remove('d-none');
return;
}
try {
const resp = await fetch('/api/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!resp.ok) {
const err = await resp.json();
errorEl.textContent = err.detail || 'Setup failed';
errorEl.classList.remove('d-none');
return;
}
const result = await resp.json();
setToken(result.token);
document.getElementById('resultUsername').textContent = result.user.display_name;
document.getElementById('resultGuestPass').textContent = result.guest_password;
resultEl.classList.remove('d-none');
form.style.display = 'none';
setTimeout(() => {
window.location.href = '/';
}, 3000);
} catch (err) {
errorEl.textContent = 'Network error. Please try again.';
errorEl.classList.remove('d-none');
}
});
</script>
{% endblock %}