High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Refactor admin error page handling to use HTML views.
Kailash Nadh6077fc0dad68
diff --git a/cmd/handlers.go b/cmd/handlers.goindex df8362f0..8d970364 100644--- a/cmd/handlers.go+++ b/cmd/handlers.go@@ -1,7 +1,6 @@package mainimport (- "errors""net/http""net/url""path"@@ -31,14 +30,7 @@ var (// registerHandlers registers HTTP handlers.func initHTTPHandlers(e *echo.Echo, a *App) {- // Default error handler.- e.HTTPErrorHandler = func(err error, c echo.Context) {- // Generic, non-echo error. Log it.- if _, ok := err.(*echo.HTTPError); !ok {- a.log.Println(err.Error())- }- e.DefaultHTTPErrorHandler(err, c)- }+ e.HTTPErrorHandler = a.handleHTTPErr// Configure CORS middleware if domains are configured.if corsOrigins := trustedURLsToCORSOrigins(a.cfg.Security.TrustedURLs); len(corsOrigins) > 0 {@@ -67,13 +59,7 @@ func initHTTPHandlers(e *echo.Echo, a *App) {return c.Redirect(http.StatusTemporaryRedirect, u.String())}- err := next(c)- var httpErr *echo.HTTPError- if errors.As(err, &httpErr) && httpErr.Code == http.StatusForbidden && !c.Response().Committed {- return a.renderAdminMessage(c, "Error", a.i18n.Ts("globals.messages.permissionDenied", "name", c.Path()))- }-- return err+ return next(c)}})@@ -81,51 +67,51 @@ func initHTTPHandlers(e *echo.Echo, a *App) {// their routes here. Unported /admin/* paths fall through to the 404 handler.g.GET(path.Join(uriAdmin, "/custom.css"), serveCustomAppearance("admin.custom_css"))g.GET(path.Join(uriAdmin, "/custom.js"), serveCustomAppearance("admin.custom_js"))- g.GET(uriAdmin, a.ViewDashboard)- g.GET(path.Join(uriAdmin, "/lists"), a.ViewLists)- g.GET(path.Join(uriAdmin, "/lists/analytics"), a.ViewListAnalytics)- g.GET(path.Join(uriAdmin, "/lists/new"), pm(a.ViewNewList, auth.PermListManageAll))- g.GET(path.Join(uriAdmin, "/lists/:id"), hasID(a.ViewList))- g.GET(path.Join(uriAdmin, "/lists/:id/edit"), hasID(a.ViewList))- g.GET(path.Join(uriAdmin, "/lists/forms"), a.ViewForms)- g.GET(path.Join(uriAdmin, "/campaigns"), pm(a.ViewCampaigns, auth.PermCampaignsGetAll, auth.PermCampaignsGet))- g.GET(path.Join(uriAdmin, "/campaigns/media"), pm(a.ViewMedia, auth.PermMediaGet))- g.GET(path.Join(uriAdmin, "/campaigns/media/fragment"), pm(a.ViewMediaFragment, auth.PermMediaGet))- g.GET(path.Join(uriAdmin, "/campaigns/analytics"), pm(a.ViewCampaignAnalytics, auth.PermCampaignsGetAnalytics))- g.GET(path.Join(uriAdmin, "/campaigns/new"), pm(a.ViewNewCampaign, auth.PermCampaignsManageAll, auth.PermCampaignsManage))- g.GET(path.Join(uriAdmin, "/campaigns/:id"), pm(hasID(a.ViewCampaign), auth.PermCampaignsGetAll, auth.PermCampaignsGet))- g.GET(path.Join(uriAdmin, "/campaigns/:id/:tab"), pm(hasID(a.ViewCampaign), auth.PermCampaignsGetAll, auth.PermCampaignsGet))- g.GET(path.Join(uriAdmin, "/templates"), pm(a.ViewTemplates, auth.PermTemplatesGet))- g.GET(path.Join(uriAdmin, "/templates/new"), pm(a.ViewNewTemplate, auth.PermTemplatesManage))- g.GET(path.Join(uriAdmin, "/templates/:id"), pm(hasID(a.ViewTemplate), auth.PermTemplatesGet))- g.GET(path.Join(uriAdmin, "/subscribers/import"), pm(a.ViewImport, auth.PermSubscribersImport))- g.GET(path.Join(uriAdmin, "/subscribers/bounces"), pm(a.ViewBounces, auth.PermBouncesGet))- g.GET(path.Join(uriAdmin, "/subscribers"), pm(a.ViewSubscribers, auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.POST(path.Join(uriAdmin, "/subscribers"), pm(a.ViewSubscribers, auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.GET(path.Join(uriAdmin, "/subscribers/lists/:id"), pm(hasID(a.ViewSubscribers), auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.POST(path.Join(uriAdmin, "/subscribers/lists/:id"), pm(hasID(a.ViewSubscribers), auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.GET(path.Join(uriAdmin, "/subscribers/new"), pm(a.ViewNewSubscriber, auth.PermSubscribersManage))- g.GET(path.Join(uriAdmin, "/subscribers/:id/edit"), pm(hasID(a.ViewSubscriber), auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.GET(path.Join(uriAdmin, "/subscribers/:id"), pm(hasID(a.ViewSubscriberInfo), auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.GET(path.Join(uriAdmin, "/subscribers/:id/lists"), pm(hasID(a.ViewSubscriber), auth.PermSubscribersGetAll, auth.PermSubscribersGet))- g.GET(path.Join(uriAdmin, "/subscribers/:id/bounces"), pm(pm(hasID(a.ViewSubscriberBounces), auth.PermBouncesGet), auth.PermSubscribersGetAll, auth.PermSubscribersGet))+ g.GET(uriAdmin, a.adminPage(a.ViewDashboard))+ g.GET(path.Join(uriAdmin, "/lists"), a.adminPage(a.ViewLists))+ g.GET(path.Join(uriAdmin, "/lists/analytics"), a.adminPage(a.ViewListAnalytics))+ g.GET(path.Join(uriAdmin, "/lists/new"), a.adminPage(pm(a.ViewNewList, auth.PermListManageAll)))+ g.GET(path.Join(uriAdmin, "/lists/:id"), a.adminPage(hasID(a.ViewList)))+ g.GET(path.Join(uriAdmin, "/lists/:id/edit"), a.adminPage(hasID(a.ViewList)))+ g.GET(path.Join(uriAdmin, "/lists/forms"), a.adminPage(a.ViewForms))+ g.GET(path.Join(uriAdmin, "/campaigns"), a.adminPage(pm(a.ViewCampaigns, auth.PermCampaignsGetAll, auth.PermCampaignsGet)))+ g.GET(path.Join(uriAdmin, "/campaigns/media"), a.adminPage(pm(a.ViewMedia, auth.PermMediaGet)))+ g.GET(path.Join(uriAdmin, "/campaigns/media/fragment"), a.adminPage(pm(a.ViewMediaFragment, auth.PermMediaGet)))+ g.GET(path.Join(uriAdmin, "/campaigns/analytics"), a.adminPage(pm(a.ViewCampaignAnalytics, auth.PermCampaignsGetAnalytics)))+ g.GET(path.Join(uriAdmin, "/campaigns/new"), a.adminPage(pm(a.ViewNewCampaign, auth.PermCampaignsManageAll, auth.PermCampaignsManage)))+ g.GET(path.Join(uriAdmin, "/campaigns/:id"), a.adminPage(pm(hasID(a.ViewCampaign), auth.PermCampaignsGetAll, auth.PermCampaignsGet)))+ g.GET(path.Join(uriAdmin, "/campaigns/:id/:tab"), a.adminPage(pm(hasID(a.ViewCampaign), auth.PermCampaignsGetAll, auth.PermCampaignsGet)))+ g.GET(path.Join(uriAdmin, "/templates"), a.adminPage(pm(a.ViewTemplates, auth.PermTemplatesGet)))+ g.GET(path.Join(uriAdmin, "/templates/new"), a.adminPage(pm(a.ViewNewTemplate, auth.PermTemplatesManage)))+ g.GET(path.Join(uriAdmin, "/templates/:id"), a.adminPage(pm(hasID(a.ViewTemplate), auth.PermTemplatesGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/import"), a.adminPage(pm(a.ViewImport, auth.PermSubscribersImport)))+ g.GET(path.Join(uriAdmin, "/subscribers/bounces"), a.adminPage(pm(a.ViewBounces, auth.PermBouncesGet)))+ g.GET(path.Join(uriAdmin, "/subscribers"), a.adminPage(pm(a.ViewSubscribers, auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.POST(path.Join(uriAdmin, "/subscribers"), a.adminPage(pm(a.ViewSubscribers, auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/lists/:id"), a.adminPage(pm(hasID(a.ViewSubscribers), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.POST(path.Join(uriAdmin, "/subscribers/lists/:id"), a.adminPage(pm(hasID(a.ViewSubscribers), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/new"), a.adminPage(pm(a.ViewNewSubscriber, auth.PermSubscribersManage)))+ g.GET(path.Join(uriAdmin, "/subscribers/:id/edit"), a.adminPage(pm(hasID(a.ViewSubscriber), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/:id"), a.adminPage(pm(hasID(a.ViewSubscriberInfo), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/:id/lists"), a.adminPage(pm(hasID(a.ViewSubscriber), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))+ g.GET(path.Join(uriAdmin, "/subscribers/:id/bounces"), a.adminPage(pm(pm(hasID(a.ViewSubscriberBounces), auth.PermBouncesGet), auth.PermSubscribersGetAll, auth.PermSubscribersGet)))// Users and roles. Static segments are registered before the :id param routes.- g.GET(path.Join(uriAdmin, "/users"), pm(a.ViewUsers, auth.PermUsersGet))- g.GET(path.Join(uriAdmin, "/users/new"), pm(a.ViewUser, auth.PermUsersManage))- g.GET(path.Join(uriAdmin, "/users/roles"), pm(a.ViewUserRoles, auth.PermRolesGet))- g.GET(path.Join(uriAdmin, "/users/roles/new"), pm(a.ViewUserRole, auth.PermRolesManage))- g.GET(path.Join(uriAdmin, "/users/roles/lists"), pm(a.ViewListRoles, auth.PermRolesGet))- g.GET(path.Join(uriAdmin, "/users/roles/lists/new"), pm(a.ViewListRole, auth.PermRolesManage))- g.GET(path.Join(uriAdmin, "/users/roles/lists/:id"), pm(hasID(a.ViewListRole), auth.PermRolesGet))- g.GET(path.Join(uriAdmin, "/users/roles/:id"), pm(hasID(a.ViewUserRole), auth.PermRolesGet))- g.GET(path.Join(uriAdmin, "/users/:id"), pm(hasID(a.ViewUser), auth.PermUsersGet))- g.GET(path.Join(uriAdmin, "/user/profile"), a.ViewProfile)+ g.GET(path.Join(uriAdmin, "/users"), a.adminPage(pm(a.ViewUsers, auth.PermUsersGet)))+ g.GET(path.Join(uriAdmin, "/users/new"), a.adminPage(pm(a.ViewUser, auth.PermUsersManage)))+ g.GET(path.Join(uriAdmin, "/users/roles"), a.adminPage(pm(a.ViewUserRoles, auth.PermRolesGet)))+ g.GET(path.Join(uriAdmin, "/users/roles/new"), a.adminPage(pm(a.ViewUserRole, auth.PermRolesManage)))+ g.GET(path.Join(uriAdmin, "/users/roles/lists"), a.adminPage(pm(a.ViewListRoles, auth.PermRolesGet)))+ g.GET(path.Join(uriAdmin, "/users/roles/lists/new"), a.adminPage(pm(a.ViewListRole, auth.PermRolesManage)))+ g.GET(path.Join(uriAdmin, "/users/roles/lists/:id"), a.adminPage(pm(hasID(a.ViewListRole), auth.PermRolesGet)))+ g.GET(path.Join(uriAdmin, "/users/roles/:id"), a.adminPage(pm(hasID(a.ViewUserRole), auth.PermRolesGet)))+ g.GET(path.Join(uriAdmin, "/users/:id"), a.adminPage(pm(hasID(a.ViewUser), auth.PermUsersGet)))+ g.GET(path.Join(uriAdmin, "/user/profile"), a.adminPage(a.ViewProfile))// Settings.- g.GET(path.Join(uriAdmin, "/settings"), pm(a.ViewSettings, auth.PermSettingsGet))- g.GET(path.Join(uriAdmin, "/settings/logs"), pm(a.ViewLogs, auth.PermSettingsGet))- g.GET(path.Join(uriAdmin, "/settings/maintenance"), pm(a.ViewMaintenance, auth.PermSettingsMaintain))+ g.GET(path.Join(uriAdmin, "/settings"), a.adminPage(pm(a.ViewSettings, auth.PermSettingsGet)))+ g.GET(path.Join(uriAdmin, "/settings/logs"), a.adminPage(pm(a.ViewLogs, auth.PermSettingsGet)))+ g.GET(path.Join(uriAdmin, "/settings/maintenance"), a.adminPage(pm(a.ViewMaintenance, auth.PermSettingsMaintain)))}// =================================================================@@ -297,14 +283,14 @@ func initHTTPHandlers(e *echo.Echo, a *App) {})// Public admin endpoints (login page, OIDC endpoints, password reset).- g.GET(path.Join(uriAdmin, "/login"), a.LoginPage)- g.POST(path.Join(uriAdmin, "/login"), a.LoginPage)- g.GET(path.Join(uriAdmin, "/login/twofa"), a.TwofaPage)- g.POST(path.Join(uriAdmin, "/login/twofa"), a.TwofaPage)- g.GET(path.Join(uriAdmin, "/forgot"), a.ForgotPage)- g.POST(path.Join(uriAdmin, "/forgot"), a.ForgotPage)- g.GET(path.Join(uriAdmin, "/reset"), a.ResetPage)- g.POST(path.Join(uriAdmin, "/reset"), a.ResetPage)+ g.GET(path.Join(uriAdmin, "/login"), a.adminPage(a.LoginPage))+ g.POST(path.Join(uriAdmin, "/login"), a.adminPage(a.LoginPage))+ g.GET(path.Join(uriAdmin, "/login/twofa"), a.adminPage(a.TwofaPage))+ g.POST(path.Join(uriAdmin, "/login/twofa"), a.adminPage(a.TwofaPage))+ g.GET(path.Join(uriAdmin, "/forgot"), a.adminPage(a.ForgotPage))+ g.POST(path.Join(uriAdmin, "/forgot"), a.adminPage(a.ForgotPage))+ g.GET(path.Join(uriAdmin, "/reset"), a.adminPage(a.ResetPage))+ g.POST(path.Join(uriAdmin, "/reset"), a.adminPage(a.ResetPage))if a.cfg.Security.OIDC.Enabled {g.POST("/auth/oidc", a.OIDCLogin)@@ -355,9 +341,9 @@ func initHTTPHandlers(e *echo.Echo, a *App) {g.RouteNotFound("/api/*", func(c echo.Context) error {return echo.NewHTTPError(http.StatusNotFound, "404 unknown endpoint")})- g.RouteNotFound("/admin/*", func(c echo.Context) error {+ g.RouteNotFound("/admin/*", a.adminPage(func(c echo.Context) error {return echo.NewHTTPError(http.StatusNotFound, "404 page not found")- })+ }))}}@@ -455,6 +441,15 @@ func (a *App) hasSub(next echo.HandlerFunc) echo.HandlerFunc {}}+// handleHTTPErr logs errors and delegates response formatting to Echo.+func (a *App) handleHTTPErr(err error, c echo.Context) {+ if _, ok := err.(*echo.HTTPError); !ok {+ a.log.Println(err.Error())+ }++ c.Echo().DefaultHTTPErrorHandler(err, c)+}+// noIndex adds the HTTP header requesting robots to not crawl the page.func noIndex(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {diff --git a/cmd/lists.go b/cmd/lists.goindex c1912b7a..b91db178 100644--- a/cmd/lists.go+++ b/cmd/lists.go@@ -110,7 +110,7 @@ func (a *App) ViewList(c echo.Context) error {// Check if the user has access to the list.id := getID(c)if err := user.HasListPerm(auth.PermTypeGet, id); err != nil {- return a.renderAdminMessage(c, "Error", a.i18n.Ts("globals.messages.permissionDenied", "name", "lists"))+ return echo.NewHTTPError(http.StatusForbidden, a.i18n.Ts("globals.messages.permissionDenied", "name", "lists"))}list, err := a.core.GetList(id, "")diff --git a/cmd/subscribers.go b/cmd/subscribers.goindex 07de57ce..b0cf6803 100644--- a/cmd/subscribers.go+++ b/cmd/subscribers.go@@ -122,7 +122,7 @@ func (a *App) ViewSubscribers(c echo.Context) error {if listID > 0 {user := auth.GetUser(c)if err := user.HasListPerm(auth.PermTypeGet, listID); err != nil {- return a.renderAdminMessage(c, "Error", a.i18n.Ts("globals.messages.permissionDenied", "name", "lists"))+ return echo.NewHTTPError(http.StatusForbidden, a.i18n.Ts("globals.messages.permissionDenied", "name", "lists"))}}diff --git a/cmd/views.go b/cmd/views.goindex aeea394d..74fc966e 100644--- a/cmd/views.go+++ b/cmd/views.go@@ -1,6 +1,7 @@package mainimport (+ "errors""net/http""strings"@@ -16,11 +17,14 @@ type adminView struct {}func newAdminView(c echo.Context, title, description, pageID string) adminView {+ // Admin views like error pages can be rendereded inside/outside auth.+ profile, _ := c.Get(auth.UserHTTPCtxKey).(auth.User)+return adminView{Title: title,Description: description,PageID: pageID,- Profile: auth.GetUser(c),+ Profile: profile,}}@@ -55,6 +59,59 @@ func canManageList(user auth.User, id int) bool {}// renderAdminMessage renders a message page.-func (a *App) renderAdminMessage(c echo.Context, title, description string) error {- return c.Render(http.StatusForbidden, "admin-message", newAdminView(c, title, description, ""))+func (a *App) renderAdminMessage(c echo.Context, status int, title, description string) error {+ return c.Render(status, "admin-message", newAdminView(c, title, description, ""))+}++// adminPage captures errors from admin HTML handlers and converts+// error messages into HTML renders.+func (a *App) adminPage(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if err := next(c); err != nil {+ return a.renderAdminError(c, err)+ }++ return nil+ }+}++// renderAdminError renders an error as an admin message page.+func (a *App) renderAdminError(c echo.Context, err error) error {+ if c.Response().Committed {+ return nil+ }++ var (+ status = http.StatusInternalServerError+ msg = http.StatusText(status)+ )+ if httpErr, ok := errors.AsType[*echo.HTTPError](err); ok {+ if internal, ok := httpErr.Internal.(*echo.HTTPError); ok {+ httpErr = internal+ }++ status = httpErr.Code+ msg = http.StatusText(status)+ switch m := httpErr.Message.(type) {+ case string:+ msg = m+ case error:+ msg = m.Error()+ }+ } else {+ a.log.Println(err.Error())+ }++ if c.Request().Method == http.MethodHead {+ return c.NoContent(status)+ }++ if err := a.renderAdminMessage(c, status, "Error", msg); err != nil {+ a.log.Println(err.Error())+ // The template renderer itself failed!+ if !c.Response().Committed {+ return c.HTML(http.StatusInternalServerError, "Internal Server Error")+ }+ }+ return nil}diff --git a/internal/core/subscribers.go b/internal/core/subscribers.goindex 70f404fc..c767f5fe 100644--- a/internal/core/subscribers.go+++ b/internal/core/subscribers.go@@ -52,11 +52,13 @@ func (c *Core) GetSubscriber(id int, uuid, email string) (models.Subscriber, errc.i18n.Ts("globals.messages.errorFetching","name", "{globals.terms.subscriber}", "error", pqErrMsg(err)))}+if len(out) == 0 {return models.Subscriber{}, echo.NewHTTPError(http.StatusBadRequest,c.i18n.Ts("globals.messages.notFound", "name",fmt.Sprintf("{globals.terms.subscriber} (%d: %s%s)", id, uuid, email)))}+if err := out.LoadLists(c.q.GetSubscriberListsLazy); err != nil {c.log.Printf("error loading subscriber lists: %v", err)return models.Subscriber{}, echo.NewHTTPError(http.StatusInternalServerError,diff --git a/static/admin/views/message.html b/static/admin/views/message.htmlindex 3ca46620..114e7443 100644--- a/static/admin/views/message.html+++ b/static/admin/views/message.html@@ -1,10 +1,24 @@{{ define "admin-message" }}-{{ template "admin-header" .}}--<article class="card">- <h2>{{ .Data.Title }}</h2>- <div>{{ .Data.Description }}</div>-</article>--{{ template "admin-footer" .}}+<!DOCTYPE html>+<html>+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>{{ .Data.Title }} - listmonk</title>+ <meta name="color-scheme" content="light dark" />+ <link href="{{ URI "/admin/static/oat.min.css" }}?v={{ .AssetVersion }}" rel="stylesheet" type="text/css" />+ <link href="{{ URI "/admin/static/style.css" }}?v={{ .AssetVersion }}" rel="stylesheet" type="text/css" />+</head>+<body>+ <main class="container mt-8">+ <div class="row">+ <article class="card col-6 offset-3">+ <header><h1>{{ .Data.Title }}</h1></header>+ <div>{{ .Data.Description }}</div>+ <footer class="mt-6"><a class="button" href="{{ URI "/admin" }}">← Dashboard</a></footer>+ </article>+ </div>+ </main>+</body>+</html>{{ end }}