Each room gets its own admin page, with a form to rename it and a link
to delete it.
Deleting has a page of its own, where you confirm before anything
happens. Following a link never changes data; only submitting the form
on that page does. Its Cancel link comes before the delete button, so
deleting is always a deliberate choice.
roomAt reads the room's id from the URL. For a room that doesn't
exist it returns op.NotFound, and visit.Refused turns that into
Page not found.
Check it worked
Choose a room on the admin page to open it. You can rename it, and you're asked to confirm before it is deleted.
🤖 These pages were written by an LLM, on the ideas, instruction, and editing of humans. AI-written text here is always marked, visibly — that's factor X.
rooms.go Edit
internal/chat/rooms.go
package chat
import (
"context""errors""strings""unicode/utf8""gorm.io/gorm""amadan.net/rastrillo/rastrillo/op")
// A name longer than this would not fit the room list on a phone.const roomNameLimit = 40
func (app *App) listRooms(ctx context.Context) ([]Room, error) {
var rooms []Room
err := app.database.G.WithContext(ctx).Order("name").Find(&rooms).Error
return rooms, err
}
func (app *App) createRoom(ctx context.Context, name string) (Room, error) {
room := Room{Name: strings.TrimSpace(name)}
if err := checkRoomName(room.Name); err != nil {
return room, err
}
err := app.database.G.WithContext(ctx).Create(&room).Error
return room, nameTaken(err)
}
func (app *App) findRoom(ctx context.Context, id int64) (Room, error) {
var room Room
err := app.database.G.WithContext(ctx).First(&room, id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return room, op.NotFound{}
}
return room, err
}
func (app *App) renameRoom(ctx context.Context, id int64, name string) error {
name = strings.TrimSpace(name)
if err := checkRoomName(name); err != nil {
return err
}
renamed := app.database.G.WithContext(ctx).Model(&Room{}).
Where("id = ?", id).Update("name", name)
if renamed.Error == nil && renamed.RowsAffected == 0 {
return op.NotFound{}
}
return nameTaken(renamed.Error)
}
func (app *App) deleteRoom(ctx context.Context, id int64) error {
deleted := app.database.G.WithContext(ctx).Delete(&Room{}, id)
if deleted.Error == nil && deleted.RowsAffected == 0 {
return op.NotFound{}
}
return deleted.Error
}
func checkRoomName(name string) error {
if name == "" || utf8.RuneCountInString(name) > roomNameLimit {
return op.Invalid{Fields: map[string]string{
"Name": "Give the room a name of 1 to 40 characters.",
}}
}
returnnil}
// nameTaken turns the unique index's refusal into a message the form// can show beside the name.func nameTaken(err error) error {
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
return op.Invalid{Fields: map[string]string{
"Name": "There is already a room with that name.",
}}
}
return err
}
admin.go Edit
internal/chat/admin.go
package chat
import (
"net/http""os""slices""strings""amadan.net/rastrillo/rastrillo/action""amadan.net/rastrillo/rastrillo/auth""amadan.net/rastrillo/rastrillo/form")
const (
adminRoomsPage action.Path = "/admin/rooms" adminRoomPage action.Path = "/admin/rooms/{id}" adminRoomDeletePage action.Path = "/admin/rooms/{id}/delete")
// requireAdmin lets through only the addresses listed in CHAT_ADMINS.// Anyone else gets 404, so the admin pages do not show they exist.func (app *App) requireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter,
request *http.Request) {
identity, _ := auth.From(request)
admins := strings.Split(os.Getenv("CHAT_ADMINS"), ",")
if identity.Address == "" ||
!slices.Contains(admins, identity.Address) {
ErrorPage(response, request, http.StatusNotFound, "")
return }
next.ServeHTTP(response, request)
})
}
// newRoomForm is the admin page: the rooms, and the form that adds one.type newRoomForm struct {
app *App
parsed *form.Parsed
}
func (page newRoomForm) ShowAgain(
visit *action.Visit, status int, errors form.Errors,
) {
rooms, err := page.app.listRooms(visit.Context())
if visit.Refused(err) {
return }
visit.Render("admin_rooms", status, map[string]any{
"Rooms": rooms, "Echo": echoOf(page.parsed), "Errors": errors,
})
}
func (app *App) adminRooms(visit *action.Visit) {
newRoomForm{app: app}.ShowAgain(visit, http.StatusOK, nil)
}
func (app *App) addRoom(visit *action.Visit) {
parsed, err := visit.ReadForm(form.Field{Name: "Name"})
if visit.RefusedShowing(err, newRoomForm{app, parsed}) {
return }
room, err := app.createRoom(visit.Context(), parsed.String("Name"))
if visit.RefusedShowing(err, newRoomForm{app, parsed}) {
return }
visit.Flash("Added " + room.Name + ".")
visit.Redirect(string(adminRoomsPage))
}
// renameForm is one room's admin page.type renameForm struct {
room Room
parsed *form.Parsed
}
func (page renameForm) ShowAgain(
visit *action.Visit, status int, errors form.Errors,
) {
visit.Render("admin_room", status, map[string]any{
"Room": page.room, "Echo": echoOf(page.parsed), "Errors": errors,
})
}
func (app *App) adminRoom(visit *action.Visit) {
room, err := app.roomAt(visit)
if visit.Refused(err) {
return }
renameForm{room: room}.ShowAgain(visit, http.StatusOK, nil)
}
func (app *App) renameRoomAt(visit *action.Visit) {
room, err := app.roomAt(visit)
if visit.Refused(err) {
return }
parsed, err := visit.ReadForm(form.Field{Name: "Name"})
if visit.RefusedShowing(err, renameForm{room, parsed}) {
return }
err = app.renameRoom(visit.Context(), room.ID, parsed.String("Name"))
if visit.RefusedShowing(err, renameForm{room, parsed}) {
return }
visit.Flash("Room renamed.")
visit.Redirect(string(adminRoomsPage))
}
func (app *App) confirmDeleteRoom(visit *action.Visit) {
room, err := app.roomAt(visit)
if visit.Refused(err) {
return }
visit.Render("admin_room_delete", http.StatusOK,
map[string]any{"Room": room})
}
func (app *App) deleteRoomAt(visit *action.Visit) {
room, err := app.roomAt(visit)
if visit.Refused(err) {
return }
err = app.deleteRoom(visit.Context(), room.ID)
if visit.Refused(err) {
return }
visit.Flash("Deleted " + room.Name + ".")
visit.Redirect(string(adminRoomsPage))
}
// roomAt is the room the URL's {id} names.func (app *App) roomAt(visit *action.Visit) (Room, error) {
id, err := visit.PathID("id")
if err != nil {
return Room{}, err
}
return app.findRoom(visit.Context(), id)
}
// echoOf is what the person typed, to fill the form in again.func echoOf(parsed *form.Parsed) map[string]string {
if parsed == nil {
returnmap[string]string{}
}
return parsed.Echo()
}
package chat
import (
"embed""html/template""maps""net/http""amadan.net/rastrillo/rastrillo""amadan.net/rastrillo/rastrillo/flash""amadan.net/rastrillo/rastrillo/live""amadan.net/rastrillo/rastrillo/locales""amadan.net/rastrillo/rastrillo/ui" genlocales "chat/gen/locales""chat/internal/chat/icons")
//go:embed templates staticvar appFS embed.FS
// assets fingerprints static/: {{asset "static/core.css"}} is a URL// with the content's hash in it, so it is cached for a year.var assets = rastrillo.NewAssets(appFS)
var pages, pagesErr = newPages()
func newPages() (*ui.Pages, error) {
config, err := locales.CheckConfig(
genlocales.DefaultLocale, genlocales.Locales)
if err != nil {
returnnil, err
}
files := map[string]ui.PageFile{}
for _, name := range []string{"index", "errors", "tokens", "admin_rooms",
"admin_room", "admin_room_delete"} {
files[name] = ui.PageFile{Path: "templates/" + name + ".html"}
}
return ui.NewPages(ui.PagesConfig{
App: appFS, Layout: "templates/layout.html",
Pages: files, Locale: config, Assets: assets,
// Both icon seams, always: icon alone breaks cdn and js icons. Funcs: template.FuncMap{"icon": icons.Icon, "iconAssets": icons.Assets,
"asset": assets.Path},
})
}
// contextFor is each request's Ctx. Its Render draws through the request// it was built for, so a page has that request's language and base path.func (app *App) contextFor(request *http.Request) (*rastrillo.Ctx, error) {
return &rastrillo.Ctx{
DB: app.database.Writer(), Logger: app.logger, Assets: assets,
Authorize: authorize, ErrorPage: ErrorPage,
Render: func(_ *rastrillo.Ctx, response http.ResponseWriter,
page string, status int, data any) {
renderPage(response, request, app.live, page, status, data)
},
}, nil}
func renderPage(
response http.ResponseWriter, request *http.Request, hub *live.Hub,
page string, status int, data any,
) {
ok := status == http.StatusOK
if ok {
status = 0 // writes no 200, so a status already sent stands }
err := pages.Render(response, request, status, page,
func(takeFlash bool) (any, error) {
values, isMap := data.(map[string]any)
if !isMap && data != nil {
return data, nil }
values = withRequest(request, values)
values["Live"] = hub.View(request)
if takeFlash && ok { // a flash follows a 303 notice, _ := flash.Take(response, request)
values["Notice"] = notice.Message
}
return values, nil })
if err != nil {
http.Error(response, "Something went wrong.",
http.StatusInternalServerError)
}
}
// withRequest copies data, so a map the caller reuses never carries one// request's language into the next.func withRequest(request *http.Request, data map[string]any) map[string]any {
values := map[string]any{}
maps.Copy(values, data)
localized := ui.ForRequest(request)
values["L"] = pages.LocalizerFor(request)
values["Locales"], values["Return"] = localized.Locales, localized.Return
values["Scheme"], values["Base"] = localized.Scheme, localized.Base
values["SignedIn"], _ = request.Context().Value(signedInKey{}).(bool)
return values
}
// ErrorPage draws templates/errors.html for a refusal and, through// Options.ErrorPage, for a panic.func ErrorPage(
response http.ResponseWriter, request *http.Request, status int,
ref string,
) {
if pagesErr != nil {
http.Error(response, "Something went wrong.",
http.StatusInternalServerError)
return }
renderPage(response, request, nil, "errors", status,
map[string]any{"Status": status, "Ref": ref})
}
routes.go Edit
internal/chat/routes.go
package chat
import (
"net/http""amadan.net/rastrillo/rastrillo/action""amadan.net/rastrillo/rastrillo/csrf")
const homePage action.Path = "/"const accountPage action.Path = "/account"const livePage action.Path = "/live"// Routes registers everything the app serves. The API and MCP are outside// the page group: a bearer token is their only credential, so they get no// CSRF check and no page middleware.func Routes(routes *action.Routes, app *App) {
routes.Mount("/static", assets.Handler(), "static")
routes.Mount("/api/v1/mcp", app.mcp, "mcp")
routes.Mount("/api/v1", app.api, "api")
// Every page and form goes in this group: it is what checks CSRF. routes.Group(func(guarded *action.Routes) {
guarded.Guard("csrf", csrf.Protect(app.origin))
guarded.Guard("pages", pages.Middleware)
guarded.Guard("signedIn", app.signedIn)
// After a first link, the offer of a faster way in, once. guarded.Guard("signinGate", app.signins.Gate)
app.mountAuth(guarded)
guarded.Get(homePage, app.home)
// Owned pages and the stream: a visitor signs in first. guarded.Group(func(owned *action.Routes) {
owned.Guard("session", app.auth.RequireSession)
owned.Get(accountPage, app.account)
owned.Group(func(admin *action.Routes) {
admin.Guard("admin", app.requireAdmin)
admin.Get(adminRoomsPage, app.adminRooms)
admin.Post(adminRoomsPage, app.addRoom)
admin.Get(adminRoomPage, app.adminRoom)
admin.Post(adminRoomPage, app.renameRoomAt)
admin.Get(adminRoomDeletePage, app.confirmDeleteRoom)
admin.Post(adminRoomDeletePage, app.deleteRoomAt)
})
owned.Handle(http.MethodGet, livePage, app.live.Handler(),
"live")
})
})
}