diff --git a/README.md b/README.md
index e469cda3..ce882791 100644
--- a/README.md
+++ b/README.md
@@ -150,7 +150,7 @@ A plugin implements the `plugin.Plugin` interface (`plugin/plugin.go`). Embed `p
| Hook | What it does |
|---|---|
| `Name()`, `DisplayName()`, `Version()` | Identity. `Name()` is the unique key used to store the plugin's settings. |
-| `Settings()` | Declares settings. They appear under **Admin → Settings** grouped by plugin, are stored in `plugin_settings`, and reach every hook as strings via `ctx.Settings`. The admin UI renders `Type: "textarea"` as a textarea and everything else as a single-line text input (there is no file or checkbox widget for plugin settings yet, so store booleans as `"true"`/`"false"`). Declare an `enabled` setting to get the on/off toggle — the registry calls every plugin regardless, so honour `ctx.Settings["enabled"]` yourself. |
+| `Settings()` | Declares settings. They appear on the plugin's own page under **Admin → Plugins**, are stored in `plugin_settings`, and reach every hook as strings via `ctx.Settings`. The admin UI renders `Type: "textarea"` as a textarea and everything else as a single-line text input (there is no file or checkbox widget for plugin settings yet, so store booleans as `"true"`/`"false"`). Declare an `enabled` setting to get the on/off toggle — the registry calls every plugin regardless, so honour `ctx.Settings["enabled"]` yourself. |
| `TemplateHead(ctx)` / `TemplateFooter(ctx)` | Return raw HTML injected into `
` / before `` on every rendered page. Escape anything that came from settings or the request. |
| `TemplateData(ctx)` | Returns data made available to templates as `.plugins.`. |
| `ScheduledJobs()` | Periodic background jobs (`Name`, `Interval`, `Run(db, settings)`), started at boot. |
diff --git a/admin/admin.go b/admin/admin.go
index 4e1fb55f..9fbcbbf0 100644
--- a/admin/admin.go
+++ b/admin/admin.go
@@ -48,11 +48,12 @@ func New(db *gorm.DB, auth auth.IAuth, b *blog.Blog, version string) Admin {
// ListThemes returns every theme goblog can activate: built-in and installed.
func ListThemes() []string { return theme.List() }
-// getPluginSettings retrieves plugin settings groups from the registry on the Gin context.
-func (a *Admin) getPluginSettings(c *gin.Context) interface{} {
+// pluginRegistry returns the plugin registry the plugin middleware put on
+// the Gin context, or nil when none is wired.
+func pluginRegistry(c *gin.Context) *gplugin.Registry {
if reg, exists := c.Get("plugin_registry"); exists {
if r, ok := reg.(*gplugin.Registry); ok {
- return r.GetAllSettings()
+ return r
}
}
return nil
@@ -588,24 +589,55 @@ func (a *Admin) GetSettings(c *gin.Context) {
//////HTML API///////
-// Admin is the admin dashboard of the website
+// Admin sends /admin to the dashboard. It used to render admin.html, an
+// "all posts + create post" mashup that duplicated two other pages.
func (a *Admin) Admin(c *gin.Context) {
if !a.auth.IsAdmin(c) {
c.JSON(http.StatusUnauthorized, "Not Authorized")
return
}
- c.HTML(http.StatusOK, "admin.html", gin.H{
- "posts": a.b.GetPosts(true),
- "logged_in": a.auth.IsLoggedIn(c),
- "is_admin": a.auth.IsAdmin(c),
- "version": a.version,
- "recent": a.b.GetLatest(),
- "admin_page": true,
- "settings": a.b.GetSettings(),
- "nav_pages": a.b.GetNavPages(),
- })
+ c.Redirect(http.StatusFound, "/admin/dashboard")
+}
+
+// pluginSummary is one enabled plugin as the dashboard's Site panel lists it.
+type pluginSummary struct {
+ Name string
+ DisplayName string
+}
+
+// enabledPlugins lists the registered plugins that are switched on, in
+// registration order, from the registry on the Gin context (nil when the
+// middleware is not installed, e.g. in tests).
+func (a *Admin) enabledPlugins(c *gin.Context) []pluginSummary {
+ var out []pluginSummary
+ if reg, exists := c.Get("plugin_registry"); exists {
+ if r, ok := reg.(*gplugin.Registry); ok {
+ for _, p := range r.Plugins() {
+ if r.IsPluginEnabled(p.Name()) {
+ out = append(out, pluginSummary{Name: p.Name(), DisplayName: p.DisplayName()})
+ }
+ }
+ }
+ }
+ return out
}
+// activeTheme is the theme rendering this request: the installer's view when
+// it is wired (it tracks activations without a restart), else the setting.
+func (a *Admin) activeTheme() string {
+ if a.Themes != nil && a.Themes.ActiveTheme != nil {
+ return a.Themes.ActiveTheme()
+ }
+ if t, ok := a.b.GetSettings()["theme"]; ok && t.Value != "" {
+ return t.Value
+ }
+ return theme.DefaultName
+}
+
+const dashboardRecentPosts = 5
+
+// AdminDashboard renders the admin landing page: content counts, the newest
+// posts and comments, and what the site is running (theme, plugins, version).
func (a *Admin) AdminDashboard(c *gin.Context) {
if !a.auth.IsAdmin(c) {
c.JSON(http.StatusUnauthorized, "Not Authorized")
@@ -617,8 +649,13 @@ func (a *Admin) AdminDashboard(c *gin.Context) {
postIDs = append(postIDs, comment.PostID)
}
commentPosts := a.b.GetPostsByIDs(postIDs)
+ published, drafts := a.b.CountPosts()
+ // ListUsers already counts; one row is the cheapest page that reports it.
+ _, userCount, err := a.auth.ListUsers(0, 1)
+ if err != nil {
+ log.Println("ERROR COUNTING USERS: ", err)
+ }
c.HTML(http.StatusOK, "admin_dashboard.html", gin.H{
- "posts": a.b.GetPosts(true),
"logged_in": a.auth.IsLoggedIn(c),
"is_admin": a.auth.IsAdmin(c),
"version": a.version,
@@ -628,6 +665,14 @@ func (a *Admin) AdminDashboard(c *gin.Context) {
"recent_comments": recentComments,
"comment_posts": commentPosts,
"nav_pages": a.b.GetNavPages(),
+ "post_count": published,
+ "draft_count": drafts,
+ "page_count": a.b.CountPages(),
+ "comment_count": a.b.CountComments(),
+ "user_count": userCount,
+ "recent_posts": a.b.GetRecentPosts(dashboardRecentPosts),
+ "active_theme": a.activeTheme(),
+ "enabled_plugins": a.enabledPlugins(c),
})
}
@@ -672,17 +717,18 @@ func (a *Admin) AdminSettings(c *gin.Context) {
c.JSON(http.StatusUnauthorized, "Not Authorized")
return
}
+ settings := a.b.GetSettings()
c.HTML(http.StatusOK, "admin_settings.html", gin.H{
- "posts": a.b.GetPosts(true),
- "logged_in": a.auth.IsLoggedIn(c),
- "is_admin": a.auth.IsAdmin(c),
- "version": a.version,
- "recent": a.b.GetLatest(),
- "admin_page": true,
- "settings": a.b.GetSettings(),
- "nav_pages": a.b.GetNavPages(),
- "themes": ListThemes(),
- "plugin_settings": a.getPluginSettings(c),
+ "posts": a.b.GetPosts(true),
+ "logged_in": a.auth.IsLoggedIn(c),
+ "is_admin": a.auth.IsAdmin(c),
+ "version": a.version,
+ "recent": a.b.GetLatest(),
+ "admin_page": true,
+ "settings": settings,
+ "setting_groups": GroupSettings(settings),
+ "nav_pages": a.b.GetNavPages(),
+ "themes": ListThemes(),
})
}
diff --git a/admin/admin_test.go b/admin/admin_test.go
index fe2e3ffa..e6b5681b 100644
--- a/admin/admin_test.go
+++ b/admin/admin_test.go
@@ -7,6 +7,7 @@ import (
"goblog/admin"
"goblog/auth"
"goblog/blog"
+ tinstaller "goblog/theme/installer"
"html/template"
"io"
"io/ioutil"
@@ -19,6 +20,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
@@ -458,18 +460,26 @@ func TestCreatePost(t *testing.T) {
t.Fatalf("Expected to get status %d but instead got %d\n%s", http.StatusBadRequest, w.Code, body)
}
- //get admin
+ //get admin: /admin is the dashboard's front door and redirects there
router.SetFuncMap(template.FuncMap{
"rawHTML": func(s string) template.HTML { return template.HTML(s) },
})
router.LoadHTMLGlob("../themes/default/templates/*")
- a.On("IsAdmin", mock.Anything).Return(true).Twice()
- a.On("IsLoggedIn", mock.Anything).Return(true).Once()
+ a.On("IsAdmin", mock.Anything).Return(true).Once()
req, _ = http.NewRequest("GET", "/admin", bytes.NewBuffer(jsonValue))
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("Expected to get status %d but instead got %d\n", http.StatusOK, w.Code)
+ if w.Code != http.StatusFound || w.Header().Get("Location") != "/admin/dashboard" {
+ t.Fatalf("Expected a %d redirect to /admin/dashboard but got %d %q\n", http.StatusFound, w.Code, w.Header().Get("Location"))
+ }
+
+ //get admin: not admin -> same 401 as every other admin page, no redirect
+ a.On("IsAdmin", mock.Anything).Return(false).Once()
+ req, _ = http.NewRequest("GET", "/admin", nil)
+ w = httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("Expected to get status %d for non-admin /admin but instead got %d\n", http.StatusUnauthorized, w.Code)
}
// Create a comment to test deletion
@@ -828,11 +838,7 @@ func TestAdminSettings_RendersCheckboxSetting(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(sessions.Sessions("s", cookie.NewStore([]byte("test"))))
- tmpl := template.Must(template.New("").Funcs(template.FuncMap{
- "rawHTML": func(s string) template.HTML { return template.HTML(s) },
- }).ParseGlob("../templates/shared/*.html"))
- template.Must(tmpl.ParseGlob("../themes/" + theme + "/templates/*.html"))
- router.SetHTMLTemplate(tmpl)
+ router.SetHTMLTemplate(themeTemplates(t, theme))
router.GET("/admin/settings", ad.AdminSettings)
a.On("IsAdmin", mock.Anything).Return(true)
@@ -860,6 +866,122 @@ func TestAdminSettings_RendersCheckboxSetting(t *testing.T) {
}
}
+// newSettingsPage seeds the given settings, renders /admin/settings with the
+// default theme and returns the status and body.
+func newSettingsPage(t *testing.T, isAdmin bool, rows ...blog.Setting) (int, string) {
+ t.Helper()
+ db, _ := gorm.Open(sqlite.Open(":memory:"))
+ db.AutoMigrate(&auth.BlogUser{}, &blog.PostType{}, &blog.Post{}, &blog.Tag{}, &blog.Setting{}, &blog.Page{})
+ for _, s := range rows {
+ db.Create(&s)
+ }
+ a := &Auth{}
+ b := blog.New(db, a, "test")
+ ad := admin.New(db, a, &b, "test")
+
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.Use(sessions.Sessions("s", cookie.NewStore([]byte("test"))))
+ tmpl := template.Must(template.New("").Funcs(template.FuncMap{
+ "rawHTML": func(s string) template.HTML { return template.HTML(s) },
+ }).ParseGlob("../templates/shared/*.html"))
+ template.Must(tmpl.ParseGlob("../themes/default/templates/*.html"))
+ router.SetHTMLTemplate(tmpl)
+ router.GET("/admin/settings", ad.AdminSettings)
+
+ a.On("IsAdmin", mock.Anything).Return(isAdmin)
+ a.On("IsLoggedIn", mock.Anything).Return(isAdmin)
+ w := httptest.NewRecorder()
+ req, _ := http.NewRequest("GET", "/admin/settings", nil)
+ router.ServeHTTP(w, req)
+ return w.Code, w.Body.String()
+}
+
+// TestAdminSettings_NonAdmin_Unauthorized checks the Settings page is gated
+// like every other admin page.
+func TestAdminSettings_NonAdmin_Unauthorized(t *testing.T) {
+ if code, _ := newSettingsPage(t, false); code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", code)
+ }
+}
+
+// TestAdminSettings_GroupsEverySeededKey checks the Settings page draws one
+// tab per group, puts every seeded key's input inside one form under a
+// human label (so Save Settings, which walks #settings-form, sends them
+// all), keeps the theme