NextWks/main.go

670 lines
27 KiB
Go

package main
import (
"bytes"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// --- Config types ---
type ServerConfig struct {
Port int `yaml:"port"`
Host string `yaml:"host"`
}
type AppConfig struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
}
type Config struct {
Server ServerConfig `yaml:"server"`
App AppConfig `yaml:"app"`
}
type AppEntry struct {
Name string `yaml:"name"`
Subtitle string `yaml:"subtitle"`
Path string `yaml:"path"`
Upstream string `yaml:"upstream"`
Icon string `yaml:"icon"`
Groups []string `yaml:"groups"`
}
type AppsFile struct {
Apps []AppEntry `yaml:"apps"`
}
// --- Config loading ---
func loadConfig(configDir string) (*Config, error) {
path := filepath.Join(configDir, "config.yaml")
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
var cfg Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
return &cfg, nil
}
func loadApps(configDir string) ([]AppEntry, error) {
path := filepath.Join(configDir, "apps.yaml")
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return []AppEntry{}, nil
}
return nil, fmt.Errorf("reading apps: %w", err)
}
var appsFile AppsFile
if err := yaml.Unmarshal(data, &appsFile); err != nil {
return nil, fmt.Errorf("parsing apps: %w", err)
}
return appsFile.Apps, nil
}
// --- Helpers ---
func userHasAnyGroup(userGroups []string, requiredGroups []string) bool {
for _, ug := range userGroups {
for _, rg := range requiredGroups {
if strings.TrimSpace(ug) == rg {
return true
}
}
}
return false
}
// --- Auth middleware (trusts Remote-User from Caddy forward auth) ---
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("Remote-User")
if user == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
r.Header.Set("X-Auth-User", user)
next(w, r)
}
}
func adminGroupMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
groups := r.Header.Get("Remote-Groups")
if !strings.Contains(groups, "admins") {
http.Error(w, "Forbidden — admins only", http.StatusForbidden)
return
}
next(w, r)
}
}
// --- Handlers ---
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK")
}
func launcherHandler(cfg *Config, apps []AppEntry) http.HandlerFunc {
tmpl := template.Must(template.New("launcher").Parse(launcherHTML))
return func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("Remote-User")
groupsHeader := r.Header.Get("Remote-Groups")
userGroups := strings.Split(groupsHeader, ",")
var allowedApps []AppEntry
for _, app := range apps {
if len(app.Groups) == 0 || userHasAnyGroup(userGroups, app.Groups) {
allowedApps = append(allowedApps, app)
}
}
data := struct {
AppName string
Description string
User string
IsAdmin bool
Apps []AppEntry
}{
AppName: cfg.App.Name,
Description: cfg.App.Description,
User: user,
IsAdmin: strings.Contains(groupsHeader, "admins"),
Apps: allowedApps,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, data)
}
}
func proxyToUpstream(upstream string) http.HandlerFunc {
target, err := url.Parse(upstream)
if err != nil {
log.Fatalf("Invalid upstream URL %q: %v", upstream, err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
return func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Remote-User", r.Header.Get("Remote-User"))
proxy.ServeHTTP(w, r)
}
}
func adminHandler(w http.ResponseWriter, r *http.Request) {
apiBase := "http://127.0.0.1:8080"
apiToken := os.Getenv("AUTHELIA_SECRET")
switch r.Method {
case http.MethodGet:
// List users from authelia-api
req, _ := http.NewRequest("GET", apiBase+"/api/users", nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// If JSON format requested, return raw API response
if r.URL.Query().Get("format") == "json" {
w.Header().Set("Content-Type", "application/json")
w.Write(body)
return
}
tmpl := template.Must(template.New("admin").Parse(adminHTML))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, map[string]interface{}{
"ApiError": resp.StatusCode != 200,
})
case http.MethodPost:
// Create user
body, _ := io.ReadAll(r.Body)
req, _ := http.NewRequest("POST", apiBase+"/api/users/bulk", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
case http.MethodDelete:
username := r.URL.Query().Get("username")
req, _ := http.NewRequest("DELETE", apiBase+"/api/users/"+username, nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("API error: %v", err), http.StatusBadGateway)
return
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
}
func settingsHandler(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("Remote-User")
groups := r.Header.Get("Remote-Groups")
isAdmin := strings.Contains(groups, "admins")
tmpl := template.Must(template.New("settings").Parse(settingsHTML))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, map[string]interface{}{
"User": user,
"IsAdmin": isAdmin,
})
}
// --- Templates ---
const landingPageHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NextWorkspace</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f0f2f5;
color: #1a1a2e;
min-height: 100vh;
}
header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 3rem 2rem; text-align: center; }
header h1 { font-size: 2.5rem; margin-bottom: 0.5rem; }
header p { color: #a0aec0; font-size: 1.2rem; }
.domain { color: #63b3ed; font-size: 0.9rem; margin-top: 0.5rem; }
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
h2 { font-size: 1.5rem; margin: 2rem 0 1rem; color: #2d3748; }
ul { list-style: none; padding: 0; }
li { background: #fff; border-radius: 8px; padding: 1rem 1.25rem; margin-bottom: 0.75rem; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
li a { color: #1a1a2e; text-decoration: none; font-weight: 600; }
li a:hover { color: #63b3ed; }
li span { color: #718096; font-size: 0.9rem; margin-left: 0.5rem; }
.ai-credit { background: #edf2f7; border-radius: 8px; padding: 1.5rem; margin-top: 2rem; text-align: center; font-size: 0.9rem; color: #4a5568; }
footer { text-align: center; padding: 2rem; color: #a0aec0; font-size: 0.85rem; }
</style>
</head>
<body>
<header>
<h1>NextWorkspace</h1>
<p>Your Self-Hosted Workspace for Startups</p>
<div class="domain">nextwks.eu</div>
</header>
<div class="container">
<h2>Components</h2>
<ul>
<li><a href="https://app.nextwks.eu/home">NextWks Core</a><span>— Launcher &amp; Workspace Hub</span></li>
<li><a href="https://app.nextwks.eu/drive">OpenCloud</a><span>— File Storage</span></li>
<li><a href="https://app.nextwks.eu/connect">Alps Webmail</a><span>— Email Client</span></li>
<li><a href="https://app.nextwks.eu/office">Euro Office</a><span>— Collaborative Suite</span></li>
<li><a href="https://app.nextwks.eu/enterprise">ERPNext</a><span>— Enterprise ERP</span></li>
<li><a href="https://app.nextwks.eu/chat">Element Web</a><span>— Matrix Chat</span></li>
<li><a href="https://app.nextwks.eu/meet">Jitsi</a><span>— Video Conferencing</span></li>
<li><a href="https://app.nextwks.eu/aida">Open WebUI</a><span>— AI Chat Frontend</span></li>
</ul>
<div class="ai-credit">
<h2>Built with AI</h2>
<p>NextWorkspace was developed with assistance from AI coding tools, using <strong>DeepSeek</strong> as the provider and <strong>OpenCode</strong> as the development framework.</p>
</div>
</div>
<footer>&copy; 2026 NextWorkspace &mdash; nextwks.eu</footer>
</body>
</html>`
const launcherHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.AppName}}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f0f2f5;
color: #1a1a2e;
min-height: 100vh;
}
header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 2rem; text-align: center; }
header h1 { font-size: 2rem; margin-bottom: 0.25rem; }
header p { color: #a0aec0; font-size: 1rem; }
.user-banner { background: #2d3748; color: #e2e8f0; padding: 0.75rem 2rem; text-align: center; font-size: 0.9rem; display: flex; justify-content: center; gap: 1rem; }
.user-banner a { color: #63b3ed; text-decoration: none; }
.user-banner a:hover { text-decoration: underline; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 1.5rem; padding: 2rem; max-width: 1200px; margin: 0 auto; }
.card { background: #fff; border-radius: 12px; padding: 1.5rem; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.08); transition: transform 0.2s; text-decoration: none; color: inherit; display: block; }
.card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
.icon { width: 48px; height: 48px; margin: 0 auto 1rem; background: #edf2f7; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }
.card h3 { font-size: 1.1rem; margin-bottom: 0.25rem; }
.card p { color: #718096; font-size: 0.85rem; }
</style>
</head>
<body>
<header>
<h1>{{.AppName}}</h1>
<p>{{.Description}}</p>
</header>
<div class="user-banner">
<span>Welcome, {{.User}}</span>
<a href="/settings">&#9881; Settings</a>
<a href="https://auth.nextwks.eu/logout">Logout</a>
</div>
<div class="grid">
{{range .Apps}}
{{if .Upstream}}
<a class="card" href="{{.Path}}/" target="_blank" rel="noopener">
{{else}}
<div class="card" style="opacity:0.5; cursor:default;">
{{end}}
<div class="icon">{{.Icon}}</div>
<h3>{{.Name}}</h3>
<p>{{.Subtitle}}</p>
{{if .Upstream}}</a>{{else}}</div>{{end}}
{{end}}
</div>
</body>
</html>`
const settingsHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings — NextWorkspace</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f0f2f5; color: #1a1a2e; }
header { background: linear-gradient(135deg, #1a1a2e, #16213e); color: #fff; padding: 1.5rem 2rem; display: flex; justify-content: space-between; align-items: center; }
header h1 { font-size: 1.5rem; }
header a { color: #63b3ed; text-decoration: none; font-size: 0.9rem; }
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
.card { background: #fff; border-radius: 8px; padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
.card h2 { font-size: 1.1rem; margin-bottom: 0.5rem; color: #2d3748; }
.card p { color: #718096; font-size: 0.9rem; }
.card a { display: inline-block; margin-top: 0.5rem; color: #63b3ed; text-decoration: none; }
.card a:hover { text-decoration: underline; }
.badge { display: inline-block; background: #edf2f7; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.8rem; margin-right: 0.25rem; }
</style>
</head>
<body>
<header>
<h1>Settings</h1>
<a href="/home/">Back to Launcher</a>
</header>
<div class="container">
<div class="card">
<h2>Account</h2>
<p>Logged in as <strong>{{.User}}</strong></p>
</div>
{{if .IsAdmin}}
<div class="card">
<h2>Administration</h2>
<p>Manage users, groups, and workspace configuration.</p>
<a href="/config">&#9878; Admin Panel →</a>
</div>
{{end}}
</div>
</body>
</html>`
const adminHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Panel — NextWorkspace</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f0f2f5; color: #1a1a2e; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
header { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: #fff; padding: 0.75rem 1.5rem; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
header h1 { font-size: 1.1rem; font-weight: 600; }
header .top-nav { display: flex; gap: 1.5rem; align-items: center; }
header .top-nav a { color: #a0aec0; text-decoration: none; font-size: 0.85rem; transition: color .15s; }
header .top-nav a:hover { color: #fff; }
.layout { display: flex; flex: 1; overflow: hidden; }
.sidebar { width: 250px; background: #fff; border-right: 1px solid #e2e8f0; display: flex; flex-direction: column; flex-shrink: 0; overflow-y: auto; }
.sidebar .section-label { padding: 1.25rem 1.25rem 0.4rem; font-size: 0.65rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #a0aec0; }
.sidebar a { display: flex; align-items: center; gap: 0.6rem; padding: 0.55rem 1.25rem; color: #4a5568; text-decoration: none; font-size: 0.88rem; border-left: 3px solid transparent; transition: all .12s; }
.sidebar a:hover { background: #f7fafc; border-left-color: #63b3ed; color: #1a1a2e; }
.sidebar a.active { background: #ebf4ff; border-left-color: #1a1a2e; color: #1a1a2e; font-weight: 600; }
.sidebar a .icon { width: 1.25rem; text-align: center; font-size: 1rem; opacity: .7; }
.sidebar a.disabled { opacity: .35; cursor: not-allowed; pointer-events: none; }
.sidebar .spacer { flex: 1; }
.sidebar .footer { padding: 1rem 1.25rem; border-top: 1px solid #e2e8f0; font-size: 0.75rem; color: #a0aec0; }
.content { flex: 1; padding: 1.5rem 2rem; overflow-y: auto; background: #f8fafc; }
.page-header { margin-bottom: 1.5rem; }
.page-header h2 { font-size: 1.4rem; font-weight: 700; color: #1a1a2e; margin-bottom: 0.25rem; }
.page-header p { color: #718096; font-size: 0.9rem; }
.card { background: #fff; border-radius: 10px; padding: 1.5rem; margin-bottom: 1.25rem; box-shadow: 0 1px 3px rgba(0,0,0,0.05); border: 1px solid #edf2f7; }
.card h3 { font-size: 1rem; font-weight: 600; color: #2d3748; margin-bottom: 1rem; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 0.55rem 0.75rem; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: #718096; border-bottom: 2px solid #edf2f7; }
td { padding: 0.65rem 0.75rem; font-size: 0.88rem; border-bottom: 1px solid #f7fafc; color: #4a5568; }
tr:hover td { background: #f7fafc; }
.badge { display: inline-block; padding: 0.15rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 500; background: #edf2f7; color: #4a5568; margin-right: 0.2rem; }
.badge-green { background: #c6f6d5; color: #276749; }
.badge-red { background: #fed7d7; color: #c53030; }
.btn { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.45rem 0.9rem; border-radius: 6px; font-size: 0.85rem; font-weight: 500; cursor: pointer; border: none; text-decoration: none; transition: all .12s; }
.btn-primary { background: #1a1a2e; color: #fff; }
.btn-primary:hover { background: #2d3748; }
.btn-danger { background: #fff; color: #e53e3e; border: 1px solid #fed7d7; }
.btn-danger:hover { background: #fff5f5; }
.btn-ghost { background: transparent; color: #718096; border: 1px solid #e2e8f0; }
.btn-ghost:hover { background: #f7fafc; }
.btn-sm { padding: 0.3rem 0.6rem; font-size: 0.8rem; }
input, select { padding: 0.45rem 0.7rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.88rem; color: #4a5568; background: #fff; outline: none; transition: border .12s; }
input:focus, select:focus { border-color: #63b3ed; box-shadow: 0 0 0 2px rgba(99,179,237,0.15); }
.form-row { display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap; margin-bottom: 1rem; }
.success { background: #c6f6d5; color: #276749; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.88rem; border: 1px solid #9ae6b4; }
.error { background: #fed7d7; color: #c53030; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.88rem; border: 1px solid #feb2b2; }
.password-box { background: #1a1a2e; color: #63b3ed; padding: 0.65rem 1rem; border-radius: 6px; font-family: 'SF Mono', 'Fira Code', monospace; font-size: 0.85rem; margin-top: 0.5rem; display: inline-block; }
.hidden { display: none; }
.empty-state { text-align: center; padding: 2.5rem 1rem; color: #a0aec0; }
.empty-state .icon { font-size: 2.5rem; margin-bottom: 0.75rem; }
.empty-state p { font-size: 0.9rem; }
</style>
</head>
<body>
<header>
<h1>NextWorkspace · Admin</h1>
<div class="top-nav">
<a href="/home/">Launcher</a>
<a href="https://auth.nextwks.eu/logout" style="color:#fc8181;">Logout</a>
</div>
</header>
<div class="layout">
<nav class="sidebar">
<div class="section-label">Core Settings</div>
<a href="#" class="active" data-section="global" onclick="return switchSection('global')"><span class="icon">&#9881;</span> Global</a>
<a href="#" data-section="access" onclick="return switchSection('access')"><span class="icon">&#128101;</span> Access</a>
<a href="#" data-section="security" onclick="return switchSection('security')"><span class="icon">&#128274;</span> Security</a>
<a href="#" data-section="domain" onclick="return switchSection('domain')"><span class="icon">&#127760;</span> Domain</a>
<div class="section-label">App Settings</div>
<a href="#" class="disabled"><span class="icon">&#128230;</span> Mail</a>
<a href="#" class="disabled"><span class="icon">&#128196;</span> Docs</a>
<a href="#" class="disabled"><span class="icon">&#128197;</span> Calendar</a>
<div class="spacer"></div>
<div class="footer">NextWorkspace v0.1.0.0011</div>
</nav>
<main class="content">
{{if .ApiError}}<div class="error">Could not connect to authelia-api on :8080</div>{{end}}
<!-- Global -->
<div id="page-global" class="page">
<div class="page-header"><h2>Global Settings</h2><p>General system configuration for your workspace.</p></div>
<div class="card"><h3>System Information</h3><p style="color:#718096;font-size:0.9rem;">NextWorkspace is a self-hosted productivity suite powered by Caddy + Authelia.</p></div>
</div>
<!-- Access (Users) -->
<div id="page-access" class="page hidden">
<div class="page-header">
<h2>Access Management</h2>
<p>Manage users, groups, and authentication policies.</p>
</div>
<div class="card">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
<h3 style="margin:0;">Users</h3>
<button class="btn btn-primary btn-sm" onclick="switchSection('create')">+ Create User</button>
</div>
<table>
<thead><tr><th>Username</th><th>Display Name</th><th>Email</th><th>Groups</th><th>Status</th><th></th></tr></thead>
<tbody id="usersTable"></tbody>
</table>
<div id="accessEmpty" class="empty-state hidden">
<div class="icon">&#128101;</div>
<p>No users found. Create one to get started.</p>
</div>
</div>
<div id="page-create" class="hidden">
<div class="card">
<h3>Create User</h3>
<form id="createForm" onsubmit="createUser(event)">
<div class="form-row">
<input name="username" placeholder="Username" required style="width:180px;">
<input name="display_name" placeholder="Display Name" required style="width:200px;">
<input name="email" placeholder="Email" type="email" required style="width:220px;">
<select name="groups" multiple size="3" style="width:160px;">
<option value="users">users</option>
<option value="drive">drive</option>
<option value="office">office</option>
<option value="erp">erp</option>
<option value="chat">chat</option>
<option value="meet">meet</option>
<option value="mail">mail</option>
<option value="ai">ai</option>
</select>
<button type="submit" class="btn btn-primary">Create</button>
</div>
</form>
<div id="createResult"></div>
</div>
</div>
</div>
<!-- Security -->
<div id="page-security" class="page hidden">
<div class="page-header"><h2>Security</h2><p>Authentication policies, tokens, and session configuration.</p></div>
<div class="card"><h3>Authentication</h3><p style="color:#718096;font-size:0.9rem;">Configured via Authelia. Policies enforced at the proxy level by Caddy.</p></div>
</div>
<!-- Domain -->
<div id="page-domain" class="page hidden">
<div class="page-header"><h2>Domain</h2><p>Domain mapping, email configuration, and network settings.</p></div>
<div class="card"><h3>Domain Configuration</h3><p style="color:#718096;font-size:0.9rem;">Managed through Caddyfile and Authelia configuration.</p></div>
</div>
</main>
</div>
<script>
let currentSection = 'global';
function switchSection(name) {
currentSection = name;
document.querySelectorAll('.sidebar a').forEach(a => a.classList.remove('active'));
document.querySelector('[data-section="' + name + '"]').classList.add('active');
document.querySelectorAll('.page').forEach(p => p.classList.add('hidden'));
const page = document.getElementById('page-' + name);
if (page) page.classList.remove('hidden');
if (name === 'access') loadUsers();
return false;
}
async function loadUsers() {
const resp = await fetch('/config?format=json');
if (!resp.ok) return;
const users = await resp.json();
const tbody = document.getElementById('usersTable');
const empty = document.getElementById('accessEmpty');
if (!users || users.length === 0) {
tbody.innerHTML = '';
empty.classList.remove('hidden');
return;
}
empty.classList.add('hidden');
tbody.innerHTML = users.map(u => {
const groups = (u.groups||[]).map(g => '<span class="badge">' + g + '</span>').join('');
const status = u.disabled ? '<span class="badge badge-red">disabled</span>' : '<span class="badge badge-green">active</span>';
return '<tr><td><strong>' + u.username + '</strong></td><td>' + (u.display_name||'') + '</td><td>' + (u.email||'') + '</td><td>' + groups + '</td><td>' + status + '</td><td><button class="btn btn-danger btn-sm" onclick="deleteUser(\'' + u.username + '\')">Delete</button></td></tr>';
}).join('');
}
async function createUser(e) {
e.preventDefault();
const form = e.target;
const data = Object.fromEntries(new FormData(form));
data.groups = Array.from(form.querySelector('[name=groups]').selectedOptions).map(o => o.value);
if (!data.groups.length) data.groups = ['users'];
const resp = await fetch('/config', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({users:[data]})});
const result = await resp.json();
const div = document.getElementById('createResult');
if (result.success) {
const pwd = (result.users && result.users[0] && result.users[0].placeholder_password) || 'check email';
div.innerHTML = '<div class="success">User created! <div class="password-box">Initial password: ' + pwd + '</div></div>';
setTimeout(() => div.innerHTML = '', 8000);
loadUsers();
} else {
div.innerHTML = '<div class="error">Error: ' + JSON.stringify(result) + '</div>';
}
}
async function deleteUser(username) {
if (!confirm('Delete user "' + username + '"?')) return;
const resp = await fetch('/config?username=' + username, {method:'DELETE'});
if (resp.ok) loadUsers();
else alert('Delete failed: ' + await resp.text());
}
// Load users on initial render if Access tab is active
if (document.querySelector('[data-section="access"].active')) loadUsers();
</script>
</body>
</html>`
// --- Main ---
func main() {
configDir := os.Getenv("CONFIG_DIR")
if configDir == "" {
configDir = "/opt/nextworkspace/config/nextworkspace"
}
cfg, err := loadConfig(configDir)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
apps, err := loadApps(configDir)
if err != nil {
log.Fatalf("Failed to load apps: %v", err)
}
addr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
mux := http.NewServeMux()
// Public
mux.HandleFunc("/health", healthHandler)
// Protected: launcher
mux.Handle("/home/", authMiddleware(launcherHandler(cfg, apps)))
mux.Handle("/home", authMiddleware(launcherHandler(cfg, apps)))
// Protected: settings
mux.Handle("/settings", authMiddleware(settingsHandler))
mux.Handle("/settings/", authMiddleware(settingsHandler))
// Protected: admin — admins only
mux.Handle("/config", adminGroupMiddleware(authMiddleware(adminHandler)))
mux.Handle("/config/", adminGroupMiddleware(authMiddleware(adminHandler)))
// Protected: upstream app proxies
for _, app := range apps {
if app.Path != "" && app.Upstream != "" && app.Path != "/config" && app.Path != "/home" {
proxyHandler := authMiddleware(proxyToUpstream(app.Upstream))
mux.Handle(app.Path+"/", proxyHandler)
mux.Handle(app.Path, proxyHandler)
}
}
// Default: www landing page or redirect to /home/
domain := os.Getenv("DOMAIN")
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, "www.") || (domain != "" && r.Host == "www."+domain) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, landingPageHTML)
return
}
http.Redirect(w, r, "/home/", http.StatusFound)
})
log.Printf("NextWorkspace listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}