feat(C2): admin panel /admin med create-customer endpoint

This commit is contained in:
Chris Christiansen 2026-05-30 15:07:10 +00:00
parent a807b0dd89
commit a316f34c35
2 changed files with 237 additions and 0 deletions

65
main.py
View File

@ -202,6 +202,71 @@ async def auth_me(request: Request):
"""Returns current user information.""" """Returns current user information."""
return JSONResponse(request.session.get('user')) return JSONResponse(request.session.get('user'))
@app.get('/admin')
@require_auth
async def admin_panel(request: Request):
return FileResponse("static/admin.html")
@app.post('/admin/create-customer')
@require_auth
async def create_customer(request: Request):
import subprocess, shlex
data = await request.json()
customer_name = data.get("customer_name", "").strip()
project_id = data.get("project_id", "").strip()
billing_account_id = data.get("billing_account_id", "").strip()
alert_email = data.get("alert_email", "").strip()
container_image = data.get("container_image", "").strip()
region = data.get("region", "europe-north1").strip()
if not all([customer_name, project_id, billing_account_id, alert_email, container_image]):
raise HTTPException(status_code=400, detail="Alle felt er påkrevd")
import re
if not re.match(r'^[a-z0-9_-]+$', customer_name):
raise HTTPException(status_code=400, detail="customer_name kan kun inneholde a-z, 0-9, - og _")
customer_dir = f"infrastructure/terraform/customers/{customer_name}"
template_dir = "infrastructure/terraform/customers/_template"
import os, shutil
if os.path.exists(customer_dir):
raise HTTPException(status_code=409, detail=f"Kunde {customer_name} eksisterer allerede")
shutil.copytree(template_dir, customer_dir)
tfvars_content = f'''customer_id = "{customer_name}"
project_id = "{project_id}"
region = "{region}"
billing_account_id = "{billing_account_id}"
alert_email = "{alert_email}"
billing_viewer_emails = ["chris.christiansen@vauco.no", "jason.vauger@vauco.no"]
container_image = "{container_image}"
'''
with open(f"{customer_dir}/terraform.tfvars", "w") as f:
f.write(tfvars_content)
try:
init = subprocess.run(
["terraform", f"-chdir={customer_dir}", "init", "-no-color"],
capture_output=True, text=True, timeout=120
)
if init.returncode != 0:
shutil.rmtree(customer_dir)
raise HTTPException(status_code=500, detail=f"terraform init feilet: {init.stderr[-500:]}")
apply = subprocess.run(
["terraform", f"-chdir={customer_dir}", "apply", "-auto-approve", "-no-color"],
capture_output=True, text=True, timeout=600
)
if apply.returncode != 0:
raise HTTPException(status_code=500, detail=f"terraform apply feilet: {apply.stderr[-500:]}")
return {"status": "ok", "customer": customer_name, "project_id": project_id}
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Terraform tok for lang tid (>10 min)")
# ── BILLING ENDPOINTS (CG1 + CG2) ──────────────────────────────────────────── # ── BILLING ENDPOINTS (CG1 + CG2) ────────────────────────────────────────────

172
static/admin.html Normal file
View File

@ -0,0 +1,172 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OSVauco Admin - Ny kunde</title>
<style>
body {
background-color: #121212;
color: #e0e0e0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
width: 100%;
max-width: 500px;
padding: 2rem;
background: #1e1e1e;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #ffffff;
}
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
label {
font-weight: 500;
}
input {
background: #2c2c2c;
border: 1px solid #444;
color: #e0e0e0;
padding: 0.8rem;
border-radius: 4px;
font-size: 1rem;
}
button {
background-color: #4CAF50;
color: white;
padding: 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
font-weight: bold;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #555;
cursor: not-allowed;
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 1rem auto;
display: none;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#result {
margin-top: 1rem;
padding: 1rem;
border-radius: 4px;
text-align: center;
}
.success {
background-color: #2e7d32;
color: white;
}
.error {
background-color: #c62828;
color: white;
}
</style>
</head>
<body>
<div class="container">
<h1>OSVauco Admin — Ny kunde</h1>
<form id="create-customer-form">
<label for="customer_name">Customer Name</label>
<input type="text" id="customer_name" name="customer_name" required>
<label for="project_id">Project ID</label>
<input type="text" id="project_id" name="project_id" required>
<label for="billing_account_id">Billing Account ID</label>
<input type="text" id="billing_account_id" name="billing_account_id" required>
<label for="alert_email">Alert Email</label>
<input type="email" id="alert_email" name="alert_email" required>
<label for="container_image">Container Image</label>
<input type="text" id="container_image" name="container_image" required>
<label for="region">Region</label>
<input type="text" id="region" name="region" value="europe-north1" required>
<p style="color:#aaa; font-size:0.85rem; margin:0">
⚠️ Dette oppretter et nytt GCP-prosjekt og koster penger. Bekreft at
alle verdier er riktige før du trykker.
</p>
<button type="submit">Create Customer</button>
</form>
<div class="spinner" id="spinner"></div>
<div id="result"></div>
</div>
<script>
document.getElementById('create-customer-form').addEventListener('submit', async function(event) {
event.preventDefault();
const form = event.target;
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
const spinner = document.getElementById('spinner');
const resultDiv = document.getElementById('result');
const submitButton = form.querySelector('button');
spinner.style.display = 'block';
resultDiv.innerHTML = '';
resultDiv.className = '';
submitButton.disabled = true;
try {
const response = await fetch('/admin/create-customer', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok) {
resultDiv.textContent = `Success! Customer ${result.customer} created with project ID ${result.project_id}.`;
resultDiv.classList.add('success');
form.reset();
} else {
resultDiv.textContent = `Error: ${result.detail}`;
resultDiv.classList.add('error');
}
} catch (error) {
resultDiv.textContent = `An unexpected error occurred: ${error.message}`;
resultDiv.classList.add('error');
} finally {
spinner.style.display = 'none';
submitButton.disabled = false;
}
});
</script>
</body>
</html>