Add admin interface with trip and trip-admin management

This commit is contained in:
Ian Gulliver
2026-02-14 22:17:32 -08:00
parent f31a22d5f8
commit 7cc73fe02c
5 changed files with 409 additions and 31 deletions

224
main.go
View File

@@ -14,7 +14,7 @@ import (
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
_ "github.com/lib/pq"
@@ -30,7 +30,7 @@ var (
)
func main() {
for _, key := range []string{"PGCONN", "CLIENT_ID", "CLIENT_SECRET"} {
for _, key := range []string{"PGCONN", "CLIENT_ID", "CLIENT_SECRET", "ADMINS"} {
if os.Getenv(key) == "" {
log.Fatalf("%s environment variable is required", key)
}
@@ -54,8 +54,17 @@ func main() {
htmlTemplates = template.Must(template.New("").ParseGlob("static/*.html"))
jsTemplates = texttemplate.Must(texttemplate.New("").ParseGlob("static/*.js"))
http.HandleFunc("/", handleStatic)
http.HandleFunc("GET /{$}", serveHTML("index.html"))
http.HandleFunc("GET /admin", serveHTML("admin.html"))
http.HandleFunc("GET /app.js", serveJS("app.js"))
http.HandleFunc("GET /admin.js", serveJS("admin.js"))
http.HandleFunc("POST /auth/google/callback", handleGoogleCallback)
http.HandleFunc("GET /api/admin/check", handleAdminCheck)
http.HandleFunc("GET /api/trips", handleListTrips(db))
http.HandleFunc("POST /api/trips", handleCreateTrip(db))
http.HandleFunc("DELETE /api/trips/{tripID}", handleDeleteTrip(db))
http.HandleFunc("POST /api/trips/{tripID}/admins", handleAddTripAdmin(db))
http.HandleFunc("DELETE /api/trips/{tripID}/admins/{adminID}", handleRemoveTripAdmin(db))
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if err := db.Ping(); err != nil {
http.Error(w, "db unhealthy", http.StatusServiceUnavailable)
@@ -84,39 +93,22 @@ func envMap() map[string]string {
return m
}
func handleStatic(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
path := r.URL.Path
if path == "/" {
path = "/index.html"
}
name := strings.TrimPrefix(path, "/")
if strings.HasSuffix(name, ".html") {
func serveHTML(name string) http.HandlerFunc {
t := htmlTemplates.Lookup(name)
if t == nil {
http.NotFound(w, r)
return
}
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, templateData())
return
}
}
if strings.HasSuffix(name, ".js") {
func serveJS(name string) http.HandlerFunc {
t := jsTemplates.Lookup(name)
if t == nil {
http.NotFound(w, r)
return
}
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Content-Type", "application/javascript")
t.Execute(w, templateData())
return
}
http.ServeFile(w, r, filepath.Join("static", name))
}
func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
@@ -169,3 +161,181 @@ func authorize(r *http.Request) (string, bool) {
}
return email, true
}
func isAdmin(email string) bool {
for _, a := range strings.Split(os.Getenv("ADMINS"), ",") {
if strings.TrimSpace(a) == email {
return true
}
}
return false
}
func requireAdmin(w http.ResponseWriter, r *http.Request) (string, bool) {
email, ok := authorize(r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return "", false
}
if !isAdmin(email) {
http.Error(w, "forbidden", http.StatusForbidden)
return "", false
}
return email, true
}
func handleAdminCheck(w http.ResponseWriter, r *http.Request) {
email, ok := authorize(r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"admin": isAdmin(email)})
}
func handleListTrips(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := requireAdmin(w, r); !ok {
return
}
rows, err := db.Query(`
SELECT t.id, t.name, COALESCE(
json_agg(json_build_object('id', ta.id, 'email', ta.email)) FILTER (WHERE ta.id IS NOT NULL),
'[]'
)
FROM trips t
LEFT JOIN trip_admins ta ON ta.trip_id = t.id
GROUP BY t.id, t.name
ORDER BY t.id`)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
type tripAdmin struct {
ID int64 `json:"id"`
Email string `json:"email"`
}
type trip struct {
ID int64 `json:"id"`
Name string `json:"name"`
Admins []tripAdmin `json:"admins"`
}
var trips []trip
for rows.Next() {
var t trip
var adminsJSON string
if err := rows.Scan(&t.ID, &t.Name, &adminsJSON); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.Unmarshal([]byte(adminsJSON), &t.Admins)
trips = append(trips, t)
}
if trips == nil {
trips = []trip{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(trips)
}
}
func handleCreateTrip(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := requireAdmin(w, r); !ok {
return
}
var body struct {
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Name == "" {
http.Error(w, "name is required", http.StatusBadRequest)
return
}
var id int64
err := db.QueryRow("INSERT INTO trips (name) VALUES ($1) RETURNING id", body.Name).Scan(&id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"id": id, "name": body.Name})
}
}
func handleDeleteTrip(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := requireAdmin(w, r); !ok {
return
}
tripID, err := strconv.ParseInt(r.PathValue("tripID"), 10, 64)
if err != nil {
http.Error(w, "invalid trip ID", http.StatusBadRequest)
return
}
result, err := db.Exec("DELETE FROM trips WHERE id = $1", tripID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if n, _ := result.RowsAffected(); n == 0 {
http.Error(w, "trip not found", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func handleAddTripAdmin(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := requireAdmin(w, r); !ok {
return
}
tripID, err := strconv.ParseInt(r.PathValue("tripID"), 10, 64)
if err != nil {
http.Error(w, "invalid trip ID", http.StatusBadRequest)
return
}
var body struct {
Email string `json:"email"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Email == "" {
http.Error(w, "email is required", http.StatusBadRequest)
return
}
var id int64
err = db.QueryRow("INSERT INTO trip_admins (trip_id, email) VALUES ($1, $2) RETURNING id", tripID, body.Email).Scan(&id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"id": id, "email": body.Email})
}
}
func handleRemoveTripAdmin(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := requireAdmin(w, r); !ok {
return
}
adminID, err := strconv.ParseInt(r.PathValue("adminID"), 10, 64)
if err != nil {
http.Error(w, "invalid admin ID", http.StatusBadRequest)
return
}
result, err := db.Exec("DELETE FROM trip_admins WHERE id = $1", adminID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if n, _ := result.RowsAffected(); n == 0 {
http.Error(w, "trip admin not found", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
}

77
static/admin.html Normal file
View File

@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin - Rooms</title>
<style>
body {
font-family: var(--wa-font-sans);
max-width: 800px;
margin: 0 auto;
padding: 1rem;
opacity: 0;
}
.header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 2rem;
}
.header img {
width: 40px;
height: 40px;
border-radius: 50%;
}
.header .spacer { flex: 1; }
wa-card {
margin-bottom: 1rem;
display: block;
}
wa-card h3 { margin: 0 0 0.5rem 0; }
.admin-row {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.25rem;
}
.add-admin-row {
display: flex;
gap: 0.5rem;
margin-top: 0.5rem;
}
.add-admin-row wa-input { flex: 1; }
.create-trip {
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
}
.create-trip wa-input { flex: 1; }
.trip-header {
display: flex;
align-items: center;
gap: 0.5rem;
}
.trip-header h3 { flex: 1; }
</style>
</head>
<body>
<div id="signin" style="display: none; align-items: center; justify-content: center; height: 100vh;"></div>
<div id="main" style="display: none;">
<div class="header">
<img data-bind="picture" alt="Profile">
<span data-bind="name"></span>
<span class="spacer"></span>
<wa-button variant="neutral" size="small" id="logout-btn">Switch User</wa-button>
</div>
<h2>Create Trip</h2>
<div class="create-trip">
<wa-input id="new-trip-name" placeholder="Trip name"></wa-input>
<wa-button variant="brand" id="create-trip-btn">Create</wa-button>
</div>
<h2>Trips</h2>
<div id="trips"></div>
</div>
<script type="module" src="/admin.js"></script>
</body>
</html>

99
static/admin.js Normal file
View File

@@ -0,0 +1,99 @@
import { init, logout, api } from '/app.js';
const profile = await init();
try {
const check = await api('GET', '/api/admin/check');
if (!check.admin) {
document.body.style.opacity = 1;
document.body.textContent = 'Access denied.';
throw new Error('not admin');
}
} catch (e) {
document.body.style.opacity = 1;
if (!document.body.textContent) document.body.textContent = 'Access denied.';
throw e;
}
document.getElementById('main').style.display = 'block';
document.getElementById('logout-btn').addEventListener('click', logout);
async function loadTrips() {
const trips = await api('GET', '/api/trips');
const container = document.getElementById('trips');
container.innerHTML = '';
for (const trip of trips) {
const card = document.createElement('wa-card');
const header = document.createElement('div');
header.className = 'trip-header';
const h3 = document.createElement('h3');
h3.textContent = trip.name;
const deleteBtn = document.createElement('wa-button');
deleteBtn.variant = 'danger';
deleteBtn.size = 'small';
deleteBtn.textContent = 'Delete Trip';
deleteBtn.addEventListener('click', async () => {
if (!confirm('Delete trip "' + trip.name + '"?')) return;
await api('DELETE', '/api/trips/' + trip.id);
loadTrips();
});
header.appendChild(h3);
header.appendChild(deleteBtn);
card.appendChild(header);
const adminLabel = document.createElement('strong');
adminLabel.textContent = 'Trip Admins:';
card.appendChild(adminLabel);
for (const admin of trip.admins) {
const row = document.createElement('div');
row.className = 'admin-row';
const span = document.createElement('span');
span.textContent = admin.email;
const removeBtn = document.createElement('wa-button');
removeBtn.variant = 'danger';
removeBtn.size = 'small';
removeBtn.textContent = 'Remove';
removeBtn.addEventListener('click', async () => {
await api('DELETE', '/api/trips/' + trip.id + '/admins/' + admin.id);
loadTrips();
});
row.appendChild(span);
row.appendChild(removeBtn);
card.appendChild(row);
}
const addRow = document.createElement('div');
addRow.className = 'add-admin-row';
const input = document.createElement('wa-input');
input.placeholder = 'Admin email';
const addBtn = document.createElement('wa-button');
addBtn.variant = 'neutral';
addBtn.size = 'small';
addBtn.textContent = 'Add Admin';
addBtn.addEventListener('click', async () => {
const email = input.value.trim();
if (!email) return;
await api('POST', '/api/trips/' + trip.id + '/admins', { email });
loadTrips();
});
addRow.appendChild(input);
addRow.appendChild(addBtn);
card.appendChild(addRow);
container.appendChild(card);
}
}
document.getElementById('create-trip-btn').addEventListener('click', async () => {
const input = document.getElementById('new-trip-name');
const name = input.value.trim();
if (!name) return;
await api('POST', '/api/trips', { name });
input.value = '';
loadTrips();
});
await loadTrips();
await customElements.whenDefined('wa-button');
document.body.style.opacity = 1;

View File

@@ -1,5 +1,29 @@
const CLIENT_ID = '{{.env.CLIENT_ID}}';
function initHead() {
document.documentElement.className = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'wa-dark' : 'wa-light';
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
document.documentElement.className = e.matches ? 'wa-dark' : 'wa-light';
});
const head = document.head;
const addLink = (rel, type, href) => {
const link = document.createElement('link');
link.rel = rel;
if (type) link.type = type;
link.href = href;
head.appendChild(link);
};
addLink('stylesheet', null, 'https://cdn.jsdelivr.net/npm/@awesome.me/webawesome@3/dist-cdn/styles/themes/default.css');
const script = document.createElement('script');
script.type = 'module';
script.src = 'https://cdn.jsdelivr.net/npm/@awesome.me/webawesome@3/dist-cdn/webawesome.loader.js';
head.appendChild(script);
}
initHead();
function getProfile() {
const data = localStorage.getItem('profile');
return data ? JSON.parse(data) : null;
@@ -97,9 +121,10 @@ export async function init() {
const buttonContainer = document.createElement('div');
signin.appendChild(buttonContainer);
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
google.accounts.id.renderButton(buttonContainer, {
type: 'standard',
theme: 'filled_black',
theme: isDark ? 'outline' : 'filled_black',
size: 'large',
text: 'sign_in_with',
shape: 'pill',

View File

@@ -10,11 +10,18 @@
<div id="main" style="display: none;">
<h1>Rooms</h1>
<p>Signed in as <span data-bind="email"></span></p>
<p id="admin-link" style="display: none;"><a href="/admin">Admin Dashboard</a></p>
</div>
<script type="module">
import { init } from '/app.js';
import { init, api } from '/app.js';
const profile = await init();
document.getElementById('main').style.display = 'block';
try {
const check = await api('GET', '/api/admin/check');
if (check.admin) {
document.getElementById('admin-link').style.display = 'block';
}
} catch (e) {}
</script>
</body>
</html>