summaryrefslogtreecommitdiffstats
path: root/internal/admin/server.go
blob: 33413ee0552d9f24a5a9ebe271d3fcad7e3fcc84 (plain) (blame)
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
// 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 (
	"fmt"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"nebbet.no/internal/admin/auth"
	"nebbet.no/internal/builder"
)

// Server is an http.Handler that serves the admin post-management UI.
type Server struct {
	// PostsDir is the directory where post markdown files are stored,
	// e.g. "content/posts". It is created on first use if it doesn't exist.
	PostsDir string
	// 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
	// Builder is used to rebuild pages after create/edit/delete operations.
	Builder *builder.Builder

	engine *gin.Engine
	tmpl   *template.Template
}

// Post holds the metadata and content of a single Post.
type Post struct {
	Slug    string
	Title   string
	Date    string
	Tags    string // comma-separated
	Content string // raw markdown body
}

// NewServer creates a new admin server with Gin routing and auth middleware.
func NewServer(postsDir, authFile string, builder *builder.Builder) *Server {
	s := &Server{
		PostsDir: postsDir,
		AuthFile: authFile,
		Builder:  builder,
	}

	// Initialize Gin engine
	s.engine = gin.Default()

	// Load templates
	s.tmpl = mustParseTemplates()

	// Apply auth middleware to all routes
	s.engine.Use(s.authMiddleware())

	// Register routes under /admin prefix
	admin := s.engine.Group("/admin")
	{
		// List posts
		admin.GET("/", s.handleList)
		// Create form and create post
		admin.GET("/new", s.handleNew)
		admin.POST("/", s.handleNewPost)
		// Edit form and update post
		admin.GET("/:slug", s.handleEdit)
		admin.POST("/:slug", s.handleEdit)
		// Delete post
		admin.DELETE("/:slug", s.handleDelete)
	}

	return s
}

// Engine returns the Gin engine for this server.
func (s *Server) Engine() *gin.Engine {
	return s.engine
}

// authMiddleware returns a Gin middleware that validates Basic Auth credentials.
func (s *Server) authMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Skip auth if no auth file is configured
		if s.AuthFile == "" {
			c.Next()
			return
		}

		// Skip auth if auth file doesn't exist
		if _, err := os.Stat(s.AuthFile); os.IsNotExist(err) {
			c.Next()
			return
		}

		// Extract Basic Auth credentials
		username, password, ok := c.Request.BasicAuth()
		if !ok {
			c.Header("WWW-Authenticate", `Basic realm="Admin"`)
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			return
		}

		// Verify credentials
		a := auth.New(s.AuthFile)
		valid, err := a.Verify(username, password)
		if err != nil || !valid {
			c.Header("WWW-Authenticate", `Basic realm="Admin"`)
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			return
		}

		// Auth succeeded, continue
		c.Next()
	}
}

// ── Handlers ─────────────────────────────────────────────────────────────────

func (s *Server) handleList(c *gin.Context) {
	posts, err := s.listPosts()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "base", gin.H{
			"Title":           "Error",
			"ContentTemplate": "error-content",
			"Message":         "Failed to list posts: " + err.Error(),
		})
		return
	}
	c.HTML(http.StatusOK, "base", gin.H{
		"Title":           "Posts",
		"ContentTemplate": "list-content",
		"Posts":           posts,
	})
}

func (s *Server) handleNew(c *gin.Context) {
	c.HTML(http.StatusOK, "base", gin.H{
		"Title":           "New Post",
		"ContentTemplate": "form-content",
		"Action":          "/admin/new",
		"Post":            Post{Date: time.Now().Format("2006-01-02")},
		"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)
	}

	mdPath := filepath.Join(s.PostsDir, p.Slug+".md")
	if err := os.MkdirAll(s.PostsDir, 0755); err != nil {
		c.HTML(http.StatusInternalServerError, "base", gin.H{
			"Title":           "Error",
			"ContentTemplate": "error-content",
			"Message":         err.Error(),
		})
		return
	}
	if _, err := os.Stat(mdPath); err == nil {
		s.renderError(c, fmt.Sprintf("Post %q already exists", p.Slug))
		return
	}
	if err := writePostFile(mdPath, p); err != nil {
		c.HTML(http.StatusInternalServerError, "base", gin.H{
			"Title":           "Error",
			"ContentTemplate": "error-content",
			"Message":         err.Error(),
		})
		return
	}
	s.rebuild(mdPath)
	c.Redirect(http.StatusSeeOther, "/admin/")
}

func (s *Server) handleEdit(c *gin.Context) {
	slug := c.Param("slug")
	mdPath := filepath.Join(s.PostsDir, slug+".md")
	p, err := readPostFile(mdPath, slug)
	if err != nil {
		c.HTML(http.StatusNotFound, "base", gin.H{
			"Title":           "Not Found",
			"ContentTemplate": "error-content",
			"Message":         "Post not found",
		})
		return
	}

	if c.Request.Method == http.MethodPost {
		updated := postFromForm(c)
		updated.Slug = slug // slug is immutable after creation
		if updated.Title == "" {
			s.renderError(c, "Title is required")
			return
		}
		if err := writePostFile(mdPath, updated); err != nil {
			c.HTML(http.StatusInternalServerError, "base", gin.H{
				"Title":           "Error",
				"ContentTemplate": "error-content",
				"Message":         err.Error(),
			})
			return
		}
		s.rebuild(mdPath)
		c.Redirect(http.StatusSeeOther, "/admin/")
		return
	}

	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")
	mdPath := filepath.Join(s.PostsDir, slug+".md")
	if err := os.Remove(mdPath); err != nil && !os.IsNotExist(err) {
		c.HTML(http.StatusInternalServerError, "base", gin.H{
			"Title":           "Error",
			"ContentTemplate": "error-content",
			"Message":         err.Error(),
		})
		return
	}
	if s.Builder != nil {
		_ = s.Builder.RemovePage(mdPath)
	}
	c.Redirect(http.StatusSeeOther, "/admin/")
}

func (s *Server) rebuild(mdPath string) {
	if s.Builder == nil {
		return
	}
	importMap, _ := builder.GenerateImportMap(s.Builder.LibDir)
	_ = s.Builder.BuildFile(mdPath, importMap)
}

func (s *Server) listPosts() ([]Post, error) {
	if err := os.MkdirAll(s.PostsDir, 0755); err != nil {
		return nil, err
	}
	entries, err := os.ReadDir(s.PostsDir)
	if err != nil {
		return nil, err
	}
	var posts []Post
	for _, e := range entries {
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
			continue
		}
		slug := strings.TrimSuffix(e.Name(), ".md")
		p, err := readPostFile(filepath.Join(s.PostsDir, e.Name()), slug)
		if err == nil {
			posts = append(posts, p)
		}
	}
	return posts, nil
}

func (s *Server) renderError(c *gin.Context, msg string) {
	c.HTML(http.StatusBadRequest, "base", gin.H{
		"Title":           "Error",
		"ContentTemplate": "error-content",
		"Message":         msg,
	})
}

// postFromForm reads a post from an HTTP form submission.
func postFromForm(c *gin.Context) Post {
	return Post{
		Title:   strings.TrimSpace(c.PostForm("title")),
		Date:    strings.TrimSpace(c.PostForm("date")),
		Tags:    strings.TrimSpace(c.PostForm("tags")),
		Content: c.PostForm("content"),
	}
}

// readPostFile reads and parses a markdown file into a post struct.
func readPostFile(path, slug string) (Post, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Post{}, err
	}
	p := Post{Slug: slug}
	body := string(data)

	// Parse frontmatter manually — keep it simple.
	if strings.HasPrefix(body, "---\n") {
		end := strings.Index(body[4:], "\n---\n")
		if end >= 0 {
			fm := body[4 : end+4]
			p.Content = strings.TrimSpace(body[end+9:])
			for _, line := range strings.Split(fm, "\n") {
				k, v, ok := strings.Cut(line, ":")
				if !ok {
					continue
				}
				k = strings.TrimSpace(k)
				v = strings.TrimSpace(v)
				switch k {
				case "title":
					p.Title = v
				case "date":
					p.Date = v
				case "tags":
					p.Tags = v
				}
			}
		}
	} else {
		p.Content = body
	}
	return p, nil
}

// writePostFile writes a post to disk as a markdown file with frontmatter.
func writePostFile(path string, p Post) error {
	date := p.Date
	if date == "" {
		date = time.Now().Format("2006-01-02")
	}
	content := fmt.Sprintf("---\ntitle: %s\ndate: %s\ntags: %s\n---\n%s\n",
		p.Title, date, p.Tags, p.Content)
	return os.WriteFile(path, []byte(content), 0644)
}

// slugify converts a title to a URL-safe slug.
var nonAlnum = regexp.MustCompile(`[^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 templates/admin/ directory.
func mustParseTemplates() *template.Template {
	funcs := template.FuncMap{
		"splitTags": func(s string) []string {
			var tags []string
			for _, t := range strings.Split(s, ",") {
				t = strings.TrimSpace(t)
				if t != "" {
					tags = append(tags, t)
				}
			}
			return tags
		},
	}
	// Load all .html files from templates/admin/ directory
	tmpl, err := template.New("admin").Funcs(funcs).ParseGlob("templates/admin/*.html")
	if err != nil {
		panic(fmt.Sprintf("failed to parse admin templates: %v", err))
	}
	return tmpl
}