feat(web): console pages for monitors, incidents and notification channels
The dashboard lists monitors with status, latency and 24-hour uptime bars rendered as SVG on the server; monitor pages add 90-day uptime, latency and recent checks; an editor shows the settings of the selected check type. Closes #17 Closes #19 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
9a050ea712
commit
b831478143
18 files changed
+4268
-323
No files matched your search
@@ -0,0 +1,428 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
const timeLayout = "2006-01-02 15:04 MST"
|
||||
|
||||
func (s *Server) registerConsole(r gin.IRouter) {
|
||||
r.GET("/", s.dashboard)
|
||||
r.GET("/monitors/new", s.orgPage("monitors.new", authz.MonitorsWrite, s.monitorEditor))
|
||||
r.GET("/monitors/:id", s.orgPage("console.monitors.title", authz.MonitorsRead, s.monitorDetail))
|
||||
r.GET("/monitors/:id/edit", s.orgPage("monitors.edit", authz.MonitorsWrite, s.monitorEditor))
|
||||
r.GET("/incidents", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentsView))
|
||||
r.GET("/settings/channels", s.orgPage("channels.title", authz.NotificationsRead, s.channelsView))
|
||||
}
|
||||
|
||||
// dashboard is the landing page. Unlike other console pages it renders for
|
||||
// users without an organization or permission instead of redirecting, since
|
||||
// it is where those redirects lead.
|
||||
func (s *Server) dashboard(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
me, p, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v := web.DashboardView{Counts: map[web.Status]int{}}
|
||||
if p != nil && me.Policy == "" && p.Grants.Can(authz.MonitorsRead) {
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v.Monitors = data.rows
|
||||
v.CanWrite = p.Grants.Can(authz.MonitorsWrite)
|
||||
for _, m := range v.Monitors {
|
||||
v.Counts[m.Status]++
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
}
|
||||
|
||||
type monitorData struct {
|
||||
rows []web.MonitorRow
|
||||
byID map[uuid.UUID]store.Monitor
|
||||
hourly map[uuid.UUID][]web.Bucket
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
}
|
||||
|
||||
// loadMonitorData assembles everything the monitor list shows.
|
||||
func (s *Server) loadMonitorData(ctx context.Context, p *principal) (monitorData, error) {
|
||||
d := monitorData{byID: map[uuid.UUID]store.Monitor{}, hourly: map[uuid.UUID][]web.Bucket{}, regionOf: map[uuid.UUID]store.Region{}}
|
||||
now := time.Now()
|
||||
var (
|
||||
monitors []store.Monitor
|
||||
assigned []store.AllMonitorRegionsRow
|
||||
regions []store.Region
|
||||
latest []store.LatestResultsRow
|
||||
open []store.Incident
|
||||
hourly []store.HourlyBucketsRow
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if monitors, err = q.ListMonitors(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned, err = q.AllMonitorRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{OrgID: p.Org.ID, Bucket: now.Add(-24 * time.Hour).Truncate(time.Hour)})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
for _, r := range regions {
|
||||
d.regionOf[r.ID] = r
|
||||
}
|
||||
regionsOf := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, a := range assigned {
|
||||
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
|
||||
}
|
||||
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
|
||||
for _, l := range latest {
|
||||
if latestOf[l.MonitorID] == nil {
|
||||
latestOf[l.MonitorID] = map[string]store.LatestResultsRow{}
|
||||
}
|
||||
latestOf[l.MonitorID][l.Region] = l
|
||||
}
|
||||
down := map[uuid.UUID]bool{}
|
||||
for _, i := range open {
|
||||
down[i.MonitorID] = true
|
||||
}
|
||||
for _, h := range hourly {
|
||||
d.hourly[h.MonitorID] = append(d.hourly[h.MonitorID], web.Bucket{Start: h.Bucket, Total: h.Total, OK: h.OkCount, Latency: h.AvgLatencyMs})
|
||||
}
|
||||
for _, m := range monitors {
|
||||
d.byID[m.ID] = m
|
||||
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"}
|
||||
var latencies []int32
|
||||
failing, reported := 0, 0
|
||||
for _, rid := range regionsOf[m.ID] {
|
||||
rs := web.RegionStatus{Name: d.regionName(rid), Status: web.StatusUnknown, Detail: "–"}
|
||||
if l, ok := latestOf[m.ID][rid.String()]; ok {
|
||||
reported++
|
||||
rs.Detail = l.Time.Format("15:04:05")
|
||||
if l.Ok {
|
||||
rs.Status = web.StatusUp
|
||||
if l.LatencyMs != nil {
|
||||
latencies = append(latencies, *l.LatencyMs)
|
||||
rs.Detail = fmt.Sprintf("%d ms", *l.LatencyMs)
|
||||
}
|
||||
} else {
|
||||
failing++
|
||||
rs.Status = web.StatusDown
|
||||
rs.Detail = deref(l.Error)
|
||||
}
|
||||
}
|
||||
row.Regions = append(row.Regions, rs)
|
||||
}
|
||||
switch {
|
||||
case !m.Enabled:
|
||||
row.Status = web.StatusPaused
|
||||
case down[m.ID]:
|
||||
row.Status = web.StatusDown
|
||||
case reported == 0:
|
||||
row.Status = web.StatusUnknown
|
||||
case failing > 0:
|
||||
row.Status = web.StatusDegraded
|
||||
default:
|
||||
row.Status = web.StatusUp
|
||||
}
|
||||
if len(latencies) > 0 {
|
||||
var sum int32
|
||||
for _, l := range latencies {
|
||||
sum += l
|
||||
}
|
||||
row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies)))
|
||||
}
|
||||
if u := web.Uptime(d.hourly[m.ID]); u >= 0 {
|
||||
row.Uptime = web.Percent(u)
|
||||
}
|
||||
row.Bars = web.UptimeBars(d.hourly[m.ID], now, time.Hour, 24, "15:04")
|
||||
d.rows = append(d.rows, row)
|
||||
}
|
||||
// Problems first, then by name.
|
||||
rank := map[web.Status]int{web.StatusDown: 0, web.StatusDegraded: 1, web.StatusUnknown: 2, web.StatusUp: 3, web.StatusPaused: 4}
|
||||
slices.SortStableFunc(d.rows, func(a, b web.MonitorRow) int { return rank[a.Status] - rank[b.Status] })
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d monitorData) regionName(id uuid.UUID) string {
|
||||
if r, ok := d.regionOf[id]; ok {
|
||||
return r.Name
|
||||
}
|
||||
return id.String()[:8]
|
||||
}
|
||||
|
||||
func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
d, err := s.loadMonitorData(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, ok := d.byID[id]
|
||||
if !ok {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
v := web.MonitorDetailView{
|
||||
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
|
||||
CanWrite: p.Grants.Can(authz.MonitorsWrite),
|
||||
Latency: web.Latency(d.hourly[id], 480, 96),
|
||||
Uptime90: "–",
|
||||
}
|
||||
for _, r := range d.rows {
|
||||
if r.ID == id.String() {
|
||||
v.Row = r
|
||||
}
|
||||
}
|
||||
var (
|
||||
daily []store.DailyBucketsRow
|
||||
recent []store.RecentResultsRow
|
||||
incidents []store.Incident
|
||||
)
|
||||
now := time.Now()
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if daily, err = q.DailyBuckets(ctx, store.DailyBucketsParams{OrgID: p.Org.ID, MonitorID: id, Bucket: now.AddDate(0, 0, -90)}); err != nil {
|
||||
return err
|
||||
}
|
||||
if recent, err = q.RecentResults(ctx, store.RecentResultsParams{OrgID: p.Org.ID, MonitorID: id, Time: now.Add(-24 * time.Hour)}); err != nil {
|
||||
return err
|
||||
}
|
||||
incidents, err = q.MonitorIncidents(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buckets := make([]web.Bucket, len(daily))
|
||||
for i, b := range daily {
|
||||
buckets[i] = web.Bucket{Start: b.Bucket, Total: b.Total, OK: b.OkCount}
|
||||
}
|
||||
v.Daily = web.UptimeBars(buckets, now, 24*time.Hour, 90, "2006-01-02")
|
||||
if u := web.Uptime(buckets); u >= 0 {
|
||||
v.Uptime90 = web.Percent(u)
|
||||
}
|
||||
for _, r := range recent[:min(len(recent), 50)] {
|
||||
row := web.ResultRow{Time: r.Time.Format("01-02 15:04:05"), Region: d.regionNameString(r.Region), OK: r.Ok, Latency: "–", Detail: deref(r.Error)}
|
||||
if r.LatencyMs != nil {
|
||||
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMs)
|
||||
}
|
||||
if r.StatusCode != nil && row.Detail == "" {
|
||||
row.Detail = fmt.Sprint(*r.StatusCode)
|
||||
}
|
||||
v.Recent = append(v.Recent, row)
|
||||
}
|
||||
for _, i := range incidents {
|
||||
v.Incidents = append(v.Incidents, d.incidentRow(i, m.Name))
|
||||
}
|
||||
page.TitleID = "console.monitors.title"
|
||||
return web.MonitorDetail(page, me, v), nil
|
||||
}
|
||||
|
||||
func (d monitorData) regionNameString(id string) string {
|
||||
if u, err := uuid.Parse(id); err == nil {
|
||||
return d.regionName(u)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentRow {
|
||||
row := web.IncidentRow{
|
||||
ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor,
|
||||
Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil,
|
||||
}
|
||||
end := time.Now()
|
||||
if i.ResolvedAt != nil {
|
||||
end = *i.ResolvedAt
|
||||
}
|
||||
row.Duration = humanDuration(end.Sub(i.StartedAt))
|
||||
var cause map[string]string
|
||||
_ = json.Unmarshal(i.Cause, &cause)
|
||||
for region, msg := range cause {
|
||||
row.Cause = append(row.Cause, d.regionNameString(region)+": "+msg)
|
||||
}
|
||||
slices.Sort(row.Cause)
|
||||
return row
|
||||
}
|
||||
|
||||
// humanDuration prints the two most significant units, e.g. "2h 5m".
|
||||
func humanDuration(d time.Duration) string {
|
||||
d = d.Round(time.Second)
|
||||
days := int(d / (24 * time.Hour))
|
||||
h := int(d/time.Hour) % 24
|
||||
m := int(d/time.Minute) % 60
|
||||
sec := int(d/time.Second) % 60
|
||||
switch {
|
||||
case days > 0:
|
||||
return fmt.Sprintf("%dd %dh", days, h)
|
||||
case h > 0:
|
||||
return fmt.Sprintf("%dh %dm", h, m)
|
||||
case m > 0:
|
||||
return fmt.Sprintf("%dm %ds", m, sec)
|
||||
}
|
||||
return fmt.Sprintf("%ds", sec)
|
||||
}
|
||||
|
||||
func notFoundPage(c *gin.Context) (templ.Component, error) {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return nil, errAborted
|
||||
}
|
||||
|
||||
// errAborted tells orgPage that the view already wrote a response.
|
||||
var errAborted = errors.New("api: response already written")
|
||||
|
||||
func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
f := web.MonitorForm{
|
||||
Type: "http", IntervalSeconds: 60, TimeoutMS: 10000, Confirmations: 2, Enabled: true,
|
||||
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx",
|
||||
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
|
||||
}
|
||||
var (
|
||||
regions []store.Region
|
||||
assigned []uuid.UUID
|
||||
)
|
||||
idParam := c.Param("id")
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if idParam == "" {
|
||||
return nil
|
||||
}
|
||||
id, err := uuid.Parse(idParam)
|
||||
if err != nil {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
m, err := q.GetMonitor(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fillForm(&f, m)
|
||||
assigned, err = q.MonitorRegions(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i, r := range regions {
|
||||
live, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
|
||||
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live})
|
||||
}
|
||||
return web.MonitorEditor(page, me, f), nil
|
||||
}
|
||||
|
||||
func fillForm(f *web.MonitorForm, m store.Monitor) {
|
||||
f.ID, f.Name, f.Type, f.Target = m.ID.String(), m.Name, m.Type, m.Target
|
||||
f.IntervalSeconds, f.TimeoutMS = int(m.IntervalSeconds), int(m.TimeoutMs)
|
||||
f.Confirmations, f.Enabled = int(m.Confirmations), m.Enabled
|
||||
switch check.Type(m.Type) {
|
||||
case check.HTTP:
|
||||
var c check.HTTPConfig
|
||||
_ = json.Unmarshal(m.Config, &c)
|
||||
f.Method, f.ExpectStatus, f.Keyword, f.KeywordAbsent = c.Method, strings.Join(c.ExpectStatus, ", "), c.Keyword, c.KeywordAbsent
|
||||
f.FollowRedirects, f.VerifyTLS = c.FollowRedirects, c.VerifyTLS
|
||||
case check.DNS:
|
||||
var c check.DNSConfig
|
||||
_ = json.Unmarshal(m.Config, &c)
|
||||
f.DNSRecord, f.DNSResolver, f.DNSExpect = c.Record, c.Resolver, c.Expect
|
||||
case check.TLS:
|
||||
var c check.TLSConfig
|
||||
_ = json.Unmarshal(m.Config, &c)
|
||||
f.TLSMinDays, f.TLSServerName = c.MinDaysValid, c.ServerName
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListIncidentsRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListIncidents(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := s.loadMonitorData(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]web.IncidentRow, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = d.incidentRow(store.Incident{
|
||||
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause,
|
||||
}, r.MonitorName)
|
||||
}
|
||||
return web.IncidentsPage(page, me, out), nil
|
||||
}
|
||||
|
||||
func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.NotificationChannel
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListChannels(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.ChannelsView{EmailAvailable: s.smtp != nil, CanWrite: p.Grants.Can(authz.NotificationsWrite), Languages: s.catalog.Supported()}
|
||||
for _, r := range rows {
|
||||
cv := viewChannel(r)
|
||||
target := cv.URL
|
||||
if cv.Type == "email" {
|
||||
target = strings.Join(cv.To, ", ")
|
||||
}
|
||||
v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled})
|
||||
}
|
||||
return web.ChannelsPage(page, me, v), nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// page fetches path and returns the final status, path and body.
|
||||
func (b *browser) page(path string) (int, string, string) {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, resp.Request.URL.Path, string(body)
|
||||
}
|
||||
|
||||
func TestConsolePages(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
}))
|
||||
defer target.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("p")+".test", uniq("pages-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Checkout API", "type": "http", "target": target.URL, "interval_seconds": 60,
|
||||
"confirmations": 1, "regions": []string{region}, "config": map[string]any{"keyword": "ok"},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
waitFor(t, 10*time.Second, "incident opened", func() bool {
|
||||
_, body := owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
return len(body["incidents"].([]any)) == 1
|
||||
})
|
||||
owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Hook", "type": "webhook", "url": "https://hooks.example.test/x"})
|
||||
|
||||
pages := map[string][]string{
|
||||
"/": {"Checkout API", "<svg"},
|
||||
"/monitors/" + id: {"Checkout API", "unexpected status 502"},
|
||||
"/monitors/" + id + "/edit": {`value="Checkout API"`, `name="config.keyword"`, `value="ok"`},
|
||||
"/monitors/new": {`name="regions"`},
|
||||
"/incidents": {"Checkout API", "unexpected status 502"},
|
||||
"/settings/channels": {"hooks.example.test"},
|
||||
}
|
||||
for path, wants := range pages {
|
||||
st, final, html := owner.page(path)
|
||||
if st != http.StatusOK || final != path {
|
||||
t.Errorf("GET %s = %d at %s", path, st, final)
|
||||
continue
|
||||
}
|
||||
for _, w := range wants {
|
||||
if !strings.Contains(html, w) {
|
||||
t.Errorf("GET %s: page lacks %q", path, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("v")+".test", owner.roleID("viewer")))
|
||||
for path, want := range map[string]string{"/monitors/new": "/", "/monitors/" + id + "/edit": "/", "/monitors/" + id: "/monitors/" + id} {
|
||||
if _, final, _ := viewer.page(path); final != want {
|
||||
t.Errorf("viewer GET %s ended at %s, want %s", path, final, want)
|
||||
}
|
||||
}
|
||||
if _, _, html := viewer.page("/"); strings.Contains(html, "/monitors/new") {
|
||||
t.Error("viewer dashboard offers creating monitors")
|
||||
}
|
||||
}
|
||||
+5
-17
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -23,7 +24,7 @@ func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/login", s.loginPage)
|
||||
r.GET("/signup", s.signupPage)
|
||||
r.GET("/invite/:token", s.invitePage)
|
||||
r.GET("/", s.page("console.monitors.title", web.Dashboard))
|
||||
s.registerConsole(r)
|
||||
r.GET("/settings/security", s.securityPage)
|
||||
r.GET("/settings/sso", s.orgPage("sso.settings.title", authz.OrgManage, s.ssoSettingsView))
|
||||
r.GET("/settings/org", s.orgPage("org.title", authz.OrgManage, s.orgSettingsView))
|
||||
@@ -127,22 +128,6 @@ func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *princip
|
||||
return me, p, nil
|
||||
}
|
||||
|
||||
func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
|
||||
return
|
||||
}
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), me))
|
||||
}
|
||||
}
|
||||
|
||||
type orgPageView func(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error)
|
||||
|
||||
// orgPage renders an organization settings page. perm may be empty for
|
||||
@@ -171,6 +156,9 @@ func (s *Server) orgPage(titleID string, perm authz.Permission, view orgPageView
|
||||
return
|
||||
}
|
||||
comp, err := view(c, p, s.pageFor(c, titleID), me)
|
||||
if errors.Is(err, errAborted) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user