1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
|
// Package admin provides an HTTP server for managing posts via a web UI.
// Admin pages are served dynamically and are never written to the static
// output directory — they are intentionally excluded from the site generator.
package admin
import (
"embed"
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/gin-gonic/gin"
"nebbet.no/internal/admin/auth"
"nebbet.no/internal/db"
"nebbet.no/internal/server"
)
//go:embed templates/*.html
var adminTemplates embed.FS
// Server is an http.Handler that serves the admin post-management UI.
type Server struct {
// AuthFile is the path to the htpasswd-compatible passwords file.
// Authentication is skipped when AuthFile is empty or the file doesn't exist.
AuthFile string
// MetaDB provides access to post records
MetaDB *db.MetaDB
// SearchDB provides full-text search indexing
SearchDB *db.SearchDB
// PublicDir is the directory where cache files are stored
PublicDir string
engine *gin.Engine
tmpl *template.Template
}
// Post holds the metadata and content for form display and submission.
type Post struct {
Slug string
Title string
Date string
Tags []string
Draft bool
Blocks string // raw EditorJS JSON
}
// NewServer creates a new admin server with Gin routing and auth middleware.
func NewServer(authFile string, metaDB *db.MetaDB, searchDB *db.SearchDB, publicDir string) *Server {
s := &Server{
AuthFile: authFile,
MetaDB: metaDB,
SearchDB: searchDB,
PublicDir: publicDir,
}
s.engine = gin.Default()
s.engine.SetTrustedProxies([]string{"192.168.1.2"})
s.tmpl = mustParseTemplates()
s.engine.SetHTMLTemplate(s.tmpl)
// Admin post routes (protected)
admin := s.engine.Group("/admin")
admin.Use(s.authMiddleware())
{
admin.GET("/", s.handleList)
admin.GET("/new", s.handleNew)
admin.POST("/", s.handleNewPost)
admin.GET("/:slug", s.handleEdit)
admin.POST("/:slug", s.handleEdit)
admin.DELETE("/:slug", s.handleDelete)
}
// Protected assets route for admin dependencies (EditorJS, etc.)
assets := s.engine.Group("/assets/admin")
assets.Use(s.authMiddleware())
{
adminAssetMIMEs := server.AllowedMIMEs{
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".wasm": "application/wasm",
".woff2": "font/woff2",
".woff": "font/woff",
".ttf": "font/ttf",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".svg": "image/svg+xml",
}
assets.GET("/*filepath", server.FileHandler("assets/admin", adminAssetMIMEs))
}
return s
}
func (s *Server) Engine() *gin.Engine {
return s.engine
}
func (s *Server) authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if s.AuthFile == "" {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if _, err := os.Stat(s.AuthFile); os.IsNotExist(err) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
username, password, ok := c.Request.BasicAuth()
if !ok {
c.Header("WWW-Authenticate", `Basic realm="Admin"`)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
a := auth.New(s.AuthFile)
valid, err := a.Verify(username, password)
if err != nil || !valid {
c.Header("WWW-Authenticate", `Basic realm="Admin"`)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
}
}
func (s *Server) handleList(c *gin.Context) {
posts, err := s.MetaDB.ListPosts(true) // includeDrafts=true for admin view
if err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": "Failed to list posts: " + err.Error(),
})
return
}
// Convert PostRecord to Post for template
var formPosts []Post
for _, p := range posts {
formPosts = append(formPosts, Post{
Slug: p.Slug,
Title: p.Title,
Date: p.Date,
Tags: p.Tags,
Draft: p.Draft,
Blocks: p.Blocks,
})
}
c.HTML(http.StatusOK, "base", gin.H{
"Title": "Posts",
"ContentTemplate": "list-content",
"Posts": formPosts,
})
}
func (s *Server) handleNew(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"Title": "New Post",
"ContentTemplate": "form-content",
"Action": "/admin/",
"Post": Post{
Date: time.Now().Format("2006-01-02"),
Blocks: "[]",
},
"IsNew": true,
})
}
func (s *Server) handleNewPost(c *gin.Context) {
p := postFromForm(c)
if p.Title == "" {
s.renderError(c, "Title is required")
return
}
if p.Slug == "" {
p.Slug = slugify(p.Title)
}
if !validSlug.MatchString(p.Slug) {
s.renderError(c, fmt.Sprintf("Invalid slug %q: use lowercase letters, numbers, and hyphens only", p.Slug))
return
}
// Check if post already exists
existing, err := s.MetaDB.GetPost(p.Slug)
if err == nil && existing != nil {
s.renderError(c, fmt.Sprintf("Post %q already exists", p.Slug))
return
}
// Prepare post record with current timestamp
record := db.PostRecord{
Slug: p.Slug,
Title: p.Title,
Date: p.Date,
Tags: p.Tags,
Draft: p.Draft,
Blocks: p.Blocks,
UpdatedAt: time.Now().UnixMicro(),
}
// Upsert post
if err := s.MetaDB.UpsertPost(record); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
// Index in search database
plainText := extractPlainTextFromEditorJS(p.Blocks)
_ = s.SearchDB.IndexPage(db.SearchPage{
Path: "/" + p.Slug,
Title: p.Title,
Content: plainText,
})
c.Redirect(http.StatusSeeOther, "/admin/")
}
func (s *Server) handleEdit(c *gin.Context) {
slug := c.Param("slug")
rec, err := s.MetaDB.GetPost(slug)
if err != nil {
c.HTML(http.StatusNotFound, "base", gin.H{
"Title": "Not Found",
"ContentTemplate": "error-content",
"Message": "Post not found",
})
return
}
p := Post{
Slug: rec.Slug,
Title: rec.Title,
Date: rec.Date,
Tags: rec.Tags,
Draft: rec.Draft,
Blocks: rec.Blocks,
}
if c.Request.Method == http.MethodPost {
updated := postFromForm(c)
if updated.Title == "" {
s.renderError(c, "Title is required")
return
}
targetSlug := slug // default: slug unchanged
if updated.Slug != "" && updated.Slug != slug {
// Slug rename requested
if !validSlug.MatchString(updated.Slug) {
s.renderError(c, fmt.Sprintf("Invalid slug %q: use lowercase letters, numbers, and hyphens only", updated.Slug))
return
}
// Check target slug is not already taken
if existing, err := s.MetaDB.GetPost(updated.Slug); err == nil && existing != nil {
s.renderError(c, fmt.Sprintf("Post %q already exists", updated.Slug))
return
}
// Perform rename (creates redirect, collapses chains)
if err := s.MetaDB.RenamePost(slug, updated.Slug); err != nil {
s.renderError(c, "Failed to rename post: "+err.Error())
return
}
// Invalidate old cache
s.invalidatePostCache(slug)
// Remove old search index entry
_ = s.SearchDB.DeletePage("/" + slug)
targetSlug = updated.Slug
}
// Update content under the (possibly new) slug
record := db.PostRecord{
Slug: targetSlug,
Title: updated.Title,
Date: updated.Date,
Tags: updated.Tags,
Draft: updated.Draft,
Blocks: updated.Blocks,
UpdatedAt: time.Now().UnixMicro(),
}
if err := s.MetaDB.UpsertPost(record); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
// Invalidate cache for the target slug
s.invalidatePostCache(targetSlug)
// Re-index with target slug
plainText := extractPlainTextFromEditorJS(updated.Blocks)
_ = s.SearchDB.IndexPage(db.SearchPage{
Path: "/" + targetSlug,
Title: updated.Title,
Content: plainText,
})
c.Redirect(http.StatusSeeOther, "/admin/")
return
}
// GET: render form
c.HTML(http.StatusOK, "base", gin.H{
"Title": "Edit Post",
"ContentTemplate": "form-content",
"Action": "/admin/" + slug,
"Post": p,
"IsNew": false,
})
}
func (s *Server) handleDelete(c *gin.Context) {
slug := c.Param("slug")
if err := s.MetaDB.DeletePost(slug); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
// Invalidate cache files
s.invalidatePostCache(slug)
// Remove from search index
_ = s.SearchDB.DeletePage("/" + slug)
c.Redirect(http.StatusSeeOther, "/admin/")
}
// invalidatePostCache removes cache files for a post to force regeneration.
func (s *Server) invalidatePostCache(slug string) {
htmlCache := filepath.Join(s.PublicDir, slug+".html")
jsonCache := filepath.Join(s.PublicDir, slug+".json")
_ = os.Remove(htmlCache)
_ = os.Remove(jsonCache)
}
func (s *Server) renderError(c *gin.Context, msg string) {
c.HTML(http.StatusBadRequest, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": msg,
})
}
func postFromForm(c *gin.Context) Post {
tagsStr := strings.TrimSpace(c.PostForm("tags"))
var tags []string
if tagsStr != "" {
for _, t := range strings.Split(tagsStr, ",") {
t = strings.TrimSpace(t)
if t != "" {
tags = append(tags, t)
}
}
}
draft := c.PostForm("draft") != ""
return Post{
Slug: strings.TrimSpace(c.PostForm("slug")),
Title: strings.TrimSpace(c.PostForm("title")),
Date: strings.TrimSpace(c.PostForm("date")),
Tags: tags,
Blocks: c.PostForm("blocks"),
Draft: draft,
}
}
// slugify converts a title to a URL-safe slug.
var nonAlnum = regexp.MustCompile(`[^a-z0-9]+`)
var validSlug = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
func slugify(title string) string {
s := strings.ToLower(title)
s = nonAlnum.ReplaceAllString(s, "-")
s = strings.Trim(s, "-")
if s == "" {
s = fmt.Sprintf("post-%d", time.Now().Unix())
}
return s
}
// mustParseTemplates loads admin templates from the embedded filesystem.
func mustParseTemplates() *template.Template {
funcs := template.FuncMap{
"splitTags": func(tags []string) []string {
return tags
},
}
// Parse templates from embedded filesystem
tmpl, err := template.New("admin").Funcs(funcs).ParseFS(adminTemplates, "templates/*.html")
if err != nil {
panic(fmt.Sprintf("failed to parse admin templates: %v", err))
}
return tmpl
}
// extractPlainTextFromEditorJS extracts plain text from EditorJS blocks for indexing.
// It's a simple extraction that pulls text from paragraph and header blocks.
func extractPlainTextFromEditorJS(blocksJSON string) string {
if blocksJSON == "" || blocksJSON == "[]" {
return ""
}
type block struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
type doc struct {
Blocks []block `json:"blocks"`
}
var d doc
if err := json.Unmarshal([]byte(blocksJSON), &d); err != nil {
return ""
}
var texts []string
for _, b := range d.Blocks {
switch b.Type {
case "paragraph", "header":
var data struct {
Text string `json:"text"`
}
if err := json.Unmarshal(b.Data, &data); err == nil && data.Text != "" {
texts = append(texts, data.Text)
}
}
}
return strings.Join(texts, " ")
}
|