Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Move all HTTP handlers directly to `App` and remove the redundant in-between layer.

Kailash Nadhe327ebbbdfc2
diff --git a/cmd/admin.go b/cmd/admin.go
index 00c45aad..b02db47d 100644
--- a/cmd/admin.go
+++ b/cmd/admin.go
@@ -24,41 +24,41 @@ type serverConfig struct {
}
// GetServerConfig returns general server config.
-func (h *Handlers) GetServerConfig(c echo.Context) error {
+func (a *App) GetServerConfig(c echo.Context) error {
out := serverConfig{
- RootURL: h.app.constants.RootURL,
- FromEmail: h.app.constants.FromEmail,
- Lang: h.app.constants.Lang,
- Permissions: h.app.constants.PermissionsRaw,
- HasLegacyUser: h.app.constants.HasLegacyUser,
+ RootURL: a.constants.RootURL,
+ FromEmail: a.constants.FromEmail,
+ Lang: a.constants.Lang,
+ Permissions: a.constants.PermissionsRaw,
+ HasLegacyUser: a.constants.HasLegacyUser,
}
// Language list.
- langList, err := getI18nLangList(h.app)
+ langList, err := getI18nLangList(a.fs)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
fmt.Sprintf("Error loading language list: %v", err))
}
out.Langs = langList
- out.Messengers = make([]string, 0, len(h.app.messengers))
- for _, m := range h.app.messengers {
+ out.Messengers = make([]string, 0, len(a.messengers))
+ for _, m := range a.messengers {
out.Messengers = append(out.Messengers, m.Name())
}
- h.app.Lock()
- out.NeedsRestart = h.app.needsRestart
- out.Update = h.app.update
- h.app.Unlock()
+ a.Lock()
+ out.NeedsRestart = a.needsRestart
+ out.Update = a.update
+ a.Unlock()
out.Version = versionString
return c.JSON(http.StatusOK, okResp{out})
}
// GetDashboardCharts returns chart data points to render ont he dashboard.
-func (h *Handlers) GetDashboardCharts(c echo.Context) error {
+func (a *App) GetDashboardCharts(c echo.Context) error {
// Get the chart data from the DB.
- out, err := h.app.core.GetDashboardCharts()
+ out, err := a.core.GetDashboardCharts()
if err != nil {
return err
}
@@ -67,9 +67,9 @@ func (h *Handlers) GetDashboardCharts(c echo.Context) error {
}
// GetDashboardCounts returns stats counts to show on the dashboard.
-func (h *Handlers) GetDashboardCounts(c echo.Context) error {
+func (a *App) GetDashboardCounts(c echo.Context) error {
// Get the chart data from the DB.
- out, err := h.app.core.GetDashboardCounts()
+ out, err := a.core.GetDashboardCounts()
if err != nil {
return err
}
@@ -78,12 +78,12 @@ func (h *Handlers) GetDashboardCounts(c echo.Context) error {
}
// ReloadApp sends a reload signal to the app, causing a full restart.
-func (h *Handlers) ReloadApp(c echo.Context) error {
+func (a *App) ReloadApp(c echo.Context) error {
go func() {
<-time.After(time.Millisecond * 500)
// Send the reload signal to trigger the wait loop in main.
- h.app.chReload <- syscall.SIGHUP
+ a.chReload <- syscall.SIGHUP
}()
return c.JSON(http.StatusOK, okResp{true})
diff --git a/cmd/archive.go b/cmd/archive.go
index 08c71db1..22e5a6bf 100644
--- a/cmd/archive.go
+++ b/cmd/archive.go
@@ -24,10 +24,10 @@ type campArchive struct {
}
// GetCampaignArchives renders the public campaign archives page.
-func (h *Handlers) GetCampaignArchives(c echo.Context) error {
+func (a *App) GetCampaignArchives(c echo.Context) error {
// Get archives from the DB.
- pg := h.app.paginator.NewFromURL(c.Request().URL.Query())
- camps, total, err := h.getCampaignArchives(pg.Offset, pg.Limit, false)
+ pg := a.paginator.NewFromURL(c.Request().URL.Query())
+ camps, total, err := a.getCampaignArchives(pg.Offset, pg.Limit, false)
if err != nil {
return err
}
@@ -50,14 +50,14 @@ func (h *Handlers) GetCampaignArchives(c echo.Context) error {
}
// GetCampaignArchivesFeed renders the public campaign archives RSS feed.
-func (h *Handlers) GetCampaignArchivesFeed(c echo.Context) error {
+func (a *App) GetCampaignArchivesFeed(c echo.Context) error {
var (
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
- showFullContent = h.app.constants.EnablePublicArchiveRSSContent
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
+ showFullContent = a.constants.EnablePublicArchiveRSSContent
)
// Get archives from the DB.
- camps, _, err := h.getCampaignArchives(pg.Offset, pg.Limit, showFullContent)
+ camps, _, err := a.getCampaignArchives(pg.Offset, pg.Limit, showFullContent)
if err != nil {
return err
}
@@ -81,31 +81,31 @@ func (h *Handlers) GetCampaignArchivesFeed(c echo.Context) error {
// Generate the feed.
feed := &feeds.Feed{
- Title: h.app.constants.SiteName,
- Link: &feeds.Link{Href: h.app.constants.RootURL},
- Description: h.app.i18n.T("public.archiveTitle"),
+ Title: a.constants.SiteName,
+ Link: &feeds.Link{Href: a.constants.RootURL},
+ Description: a.i18n.T("public.archiveTitle"),
Items: out,
}
if err := feed.WriteRss(c.Response().Writer); err != nil {
- h.app.log.Printf("error generating archive RSS feed: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.errorProcessingRequest"))
+ a.log.Printf("error generating archive RSS feed: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.errorProcessingRequest"))
}
return nil
}
// CampaignArchivesPage renders the public campaign archives page.
-func (h *Handlers) CampaignArchivesPage(c echo.Context) error {
+func (a *App) CampaignArchivesPage(c echo.Context) error {
// Get archives from the DB.
- pg := h.app.paginator.NewFromURL(c.Request().URL.Query())
- out, total, err := h.getCampaignArchives(pg.Offset, pg.Limit, false)
+ pg := a.paginator.NewFromURL(c.Request().URL.Query())
+ out, total, err := a.getCampaignArchives(pg.Offset, pg.Limit, false)
if err != nil {
return err
}
pg.SetTotal(total)
- title := h.app.i18n.T("public.archiveTitle")
+ title := a.i18n.T("public.archiveTitle")
return c.Render(http.StatusOK, "archive", struct {
Title string
Description string
@@ -116,7 +116,7 @@ func (h *Handlers) CampaignArchivesPage(c echo.Context) error {
}
// CampaignArchivePage renders the public campaign archives page.
-func (h *Handlers) CampaignArchivePage(c echo.Context) error {
+func (a *App) CampaignArchivePage(c echo.Context) error {
// ID can be the UUID or slug.
var (
idStr = c.Param("id")
@@ -129,7 +129,7 @@ func (h *Handlers) CampaignArchivePage(c echo.Context) error {
}
// Get the campaign from the DB.
- pubCamp, err := h.app.core.GetArchivedCampaign(0, uuid, slug)
+ pubCamp, err := a.core.GetArchivedCampaign(0, uuid, slug)
if err != nil || pubCamp.Type != models.CampaignTypeRegular {
notFound := false
@@ -146,44 +146,44 @@ func (h *Handlers) CampaignArchivePage(c echo.Context) error {
// 404.
if notFound {
return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.notFoundTitle"), "", h.app.i18n.T("public.campaignNotFound")))
+ makeMsgTpl(a.i18n.T("public.notFoundTitle"), "", a.i18n.T("public.campaignNotFound")))
}
// Some other internal error.
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
// "Compile" the campaign template with appropriate data.
- out, err := h.compileArchiveCampaigns([]models.Campaign{pubCamp})
+ out, err := a.compileArchiveCampaigns([]models.Campaign{pubCamp})
if err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
// Render the campaign body.
camp := out[0].Campaign
- msg, err := h.app.manager.NewCampaignMessage(camp, out[0].Subscriber)
+ msg, err := a.manager.NewCampaignMessage(camp, out[0].Subscriber)
if err != nil {
- h.app.log.Printf("error rendering campaign: %v", err)
+ a.log.Printf("error rendering campaign: %v", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
return c.HTML(http.StatusOK, string(msg.Body()))
}
// CampaignArchivePageLatest renders the latest public campaign.
-func (h *Handlers) CampaignArchivePageLatest(c echo.Context) error {
+func (a *App) CampaignArchivePageLatest(c echo.Context) error {
// Get the latest campaign from the DB.
- camps, _, err := h.getCampaignArchives(0, 1, true)
+ camps, _, err := a.getCampaignArchives(0, 1, true)
if err != nil {
return err
}
if len(camps) == 0 {
return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.notFoundTitle"), "", h.app.i18n.T("public.campaignNotFound")))
+ makeMsgTpl(a.i18n.T("public.notFoundTitle"), "", a.i18n.T("public.campaignNotFound")))
}
camp := camps[0]
@@ -191,13 +191,13 @@ func (h *Handlers) CampaignArchivePageLatest(c echo.Context) error {
}
// getCampaignArchives fetches the public campaign archives from the DB.
-func (h *Handlers) getCampaignArchives(offset, limit int, renderBody bool) ([]campArchive, int, error) {
- pubCamps, total, err := h.app.core.GetArchivedCampaigns(offset, limit)
+func (a *App) getCampaignArchives(offset, limit int, renderBody bool) ([]campArchive, int, error) {
+ pubCamps, total, err := a.core.GetArchivedCampaigns(offset, limit)
if err != nil {
- return []campArchive{}, total, echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("public.errorFetchingCampaign"))
+ return []campArchive{}, total, echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("public.errorFetchingCampaign"))
}
- msgs, err := h.compileArchiveCampaigns(pubCamps)
+ msgs, err := a.compileArchiveCampaigns(pubCamps)
if err != nil {
return []campArchive{}, total, err
}
@@ -215,14 +215,14 @@ func (h *Handlers) getCampaignArchives(offset, limit int, renderBody bool) ([]ca
// The campaign may have a custom slug.
if camp.ArchiveSlug.Valid {
- archive.URL, _ = url.JoinPath(h.app.constants.ArchiveURL, camp.ArchiveSlug.String)
+ archive.URL, _ = url.JoinPath(a.constants.ArchiveURL, camp.ArchiveSlug.String)
} else {
- archive.URL, _ = url.JoinPath(h.app.constants.ArchiveURL, camp.UUID)
+ archive.URL, _ = url.JoinPath(a.constants.ArchiveURL, camp.UUID)
}
// Render the full template body if requested.
if renderBody {
- msg, err := h.app.manager.NewCampaignMessage(camp, m.Subscriber)
+ msg, err := a.manager.NewCampaignMessage(camp, m.Subscriber)
if err != nil {
return []campArchive{}, total, err
}
@@ -236,7 +236,7 @@ func (h *Handlers) getCampaignArchives(offset, limit int, renderBody bool) ([]ca
}
// compileArchiveCampaigns compiles the campaign template with the subscriber data.
-func (h *Handlers) compileArchiveCampaigns(camps []models.Campaign) ([]manager.CampaignMessage, error) {
+func (a *App) compileArchiveCampaigns(camps []models.Campaign) ([]manager.CampaignMessage, error) {
var (
b = bytes.Buffer{}
@@ -244,16 +244,16 @@ func (h *Handlers) compileArchiveCampaigns(camps []models.Campaign) ([]manager.C
)
for _, c := range camps {
camp := c
- if err := camp.CompileTemplate(h.app.manager.TemplateFuncs(&camp)); err != nil {
- h.app.log.Printf("error compiling template: %v", err)
- return nil, echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("public.errorFetchingCampaign"))
+ if err := camp.CompileTemplate(a.manager.TemplateFuncs(&camp)); err != nil {
+ a.log.Printf("error compiling template: %v", err)
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("public.errorFetchingCampaign"))
}
// Load the dummy subscriber meta.
var sub models.Subscriber
if err := json.Unmarshal([]byte(camp.ArchiveMeta), &sub); err != nil {
- h.app.log.Printf("error unmarshalling campaign archive meta: %v", err)
- return nil, echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("public.errorFetchingCampaign"))
+ a.log.Printf("error unmarshalling campaign archive meta: %v", err)
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("public.errorFetchingCampaign"))
}
m := manager.CampaignMessage{
diff --git a/cmd/auth.go b/cmd/auth.go
index f8abe013..580aba36 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -42,49 +42,49 @@ var oidcProviders = map[string]bool{
}
// LoginPage renders the login page and handles the login form.
-func (h *Handlers) LoginPage(c echo.Context) error {
+func (a *App) LoginPage(c echo.Context) error {
// Has the user been setup?
- h.app.Lock()
- needsUserSetup := h.app.needsUserSetup
- h.app.Unlock()
+ a.Lock()
+ needsUserSetup := a.needsUserSetup
+ a.Unlock()
if needsUserSetup {
- return h.LoginSetupPage(c)
+ return a.LoginSetupPage(c)
}
// Process POST login request.
var loginErr error
if c.Request().Method == http.MethodPost {
- loginErr = h.doLogin(c)
+ loginErr = a.doLogin(c)
if loginErr == nil {
return c.Redirect(http.StatusFound, utils.SanitizeURI(c.FormValue("next")))
}
}
// Render the page, with or without POST.
- return h.renderLoginPage(c, loginErr)
+ return a.renderLoginPage(c, loginErr)
}
// LoginSetupPage renders the first time user login page and handles the login form.
-func (h *Handlers) LoginSetupPage(c echo.Context) error {
+func (a *App) LoginSetupPage(c echo.Context) error {
// Process POST login request.
var loginErr error
if c.Request().Method == http.MethodPost {
- loginErr = h.doFirstTimeSetup(c)
+ loginErr = a.doFirstTimeSetup(c)
if loginErr == nil {
- h.app.Lock()
- h.app.needsUserSetup = false
- h.app.Unlock()
+ a.Lock()
+ a.needsUserSetup = false
+ a.Unlock()
return c.Redirect(http.StatusFound, utils.SanitizeURI(c.FormValue("next")))
}
}
// Render the page, with or without POST.
- return h.renderLoginSetupPage(c, loginErr)
+ return a.renderLoginSetupPage(c, loginErr)
}
// Logout logs a user out.
-func (h *Handlers) Logout(c echo.Context) error {
+func (a *App) Logout(c echo.Context) error {
// Delete the session from the DB and cookie.
sess := c.Get(auth.SessionKey).(*simplesessions.Session)
_ = sess.Destroy()
@@ -93,11 +93,11 @@ func (h *Handlers) Logout(c echo.Context) error {
}
// OIDCLogin initializes an OIDC request and redirects to the OIDC provider for login.
-func (h *Handlers) OIDCLogin(c echo.Context) error {
+func (a *App) OIDCLogin(c echo.Context) error {
// Verify that the request came from the login page (CSRF).
nonce, err := c.Cookie("nonce")
if err != nil || nonce.Value == "" || nonce.Value != c.FormValue("nonce") {
- return echo.NewHTTPError(http.StatusUnauthorized, h.app.i18n.T("users.invalidRequest"))
+ return echo.NewHTTPError(http.StatusUnauthorized, a.i18n.T("users.invalidRequest"))
}
// Sanitize the URL and make it relative.
@@ -111,68 +111,68 @@ func (h *Handlers) OIDCLogin(c echo.Context) error {
b, err := json.Marshal(state)
if err != nil {
- h.app.log.Printf("error marshalling OIDC state: %v", err)
- return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("globals.messages.internalError"))
+ a.log.Printf("error marshalling OIDC state: %v", err)
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
}
// Redirect to the external OIDC provider.
- return c.Redirect(http.StatusFound, h.app.auth.GetOIDCAuthURL(base64.URLEncoding.EncodeToString(b), nonce.Value))
+ return c.Redirect(http.StatusFound, a.auth.GetOIDCAuthURL(base64.URLEncoding.EncodeToString(b), nonce.Value))
}
// OIDCFinish receives the redirect callback from the OIDC provider and completes the handshake.
-func (h *Handlers) OIDCFinish(c echo.Context) error {
+func (a *App) OIDCFinish(c echo.Context) error {
// Verify that the request actually originated from the login request (which sets the nonce value).
nonce, err := c.Cookie("nonce")
if err != nil || nonce.Value == "" {
- return h.renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, h.app.i18n.T("users.invalidRequest")))
+ return a.renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, a.i18n.T("users.invalidRequest")))
}
// Validate the OIDC token.
- oidcToken, claims, err := h.app.auth.ExchangeOIDCToken(c.Request().URL.Query().Get("code"), nonce.Value)
+ oidcToken, claims, err := a.auth.ExchangeOIDCToken(c.Request().URL.Query().Get("code"), nonce.Value)
if err != nil {
- return h.renderLoginPage(c, err)
+ return a.renderLoginPage(c, err)
}
// Validate the state.
var state oidcState
stateB, err := base64.URLEncoding.DecodeString(c.QueryParam("state"))
if err != nil {
- h.app.log.Printf("error decoding OIDC state: %v", err)
- return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("globals.messages.internalError"))
+ a.log.Printf("error decoding OIDC state: %v", err)
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
}
if err := json.Unmarshal(stateB, &state); err != nil {
- h.app.log.Printf("error unmarshalling OIDC state: %v", err)
- return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("globals.messages.internalError"))
+ a.log.Printf("error unmarshalling OIDC state: %v", err)
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
}
if state.Nonce != nonce.Value {
- return h.renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, h.app.i18n.T("users.invalidRequest")))
+ return a.renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, a.i18n.T("users.invalidRequest")))
}
// Validate e-mail from the claim.
email := strings.TrimSpace(claims.Email)
if email == "" {
- return h.renderLoginPage(c, errors.New(h.app.i18n.Ts("globals.messages.invalidFields", "name", "email")))
+ return a.renderLoginPage(c, errors.New(a.i18n.Ts("globals.messages.invalidFields", "name", "email")))
}
em, err := mail.ParseAddress(email)
if err != nil {
- return h.renderLoginPage(c, err)
+ return a.renderLoginPage(c, err)
}
email = strings.ToLower(em.Address)
// Get the user by e-mail received from OIDC.
- user, err := h.app.core.GetUser(0, "", email)
+ user, err := a.core.GetUser(0, "", email)
if err != nil {
- return h.renderLoginPage(c, err)
+ return a.renderLoginPage(c, err)
}
// Update the user login state (avatar, logged in date) in the DB.
- if err := h.app.core.UpdateUserLogin(user.ID, claims.Picture); err != nil {
- return h.renderLoginPage(c, err)
+ if err := a.core.UpdateUserLogin(user.ID, claims.Picture); err != nil {
+ return a.renderLoginPage(c, err)
}
// Set the session in the DB and cookie.
- if err := h.app.auth.SaveSession(user, oidcToken, c); err != nil {
- return h.renderLoginPage(c, err)
+ if err := a.auth.SaveSession(user, oidcToken, c); err != nil {
+ return a.renderLoginPage(c, err)
}
// Redirect to the next page.
@@ -180,7 +180,7 @@ func (h *Handlers) OIDCFinish(c echo.Context) error {
}
// renderLoginPage renders the login page and handles the login form.
-func (h *Handlers) renderLoginPage(c echo.Context, loginErr error) error {
+func (a *App) renderLoginPage(c echo.Context, loginErr error) error {
next := utils.SanitizeURI(c.FormValue("next"))
if next == "/" {
next = uriAdmin
@@ -190,9 +190,9 @@ func (h *Handlers) renderLoginPage(c echo.Context, loginErr error) error {
oidcProvider = ""
oidcLogo = ""
)
- if h.app.constants.Security.OIDC.Enabled {
+ if a.constants.Security.OIDC.Enabled {
oidcLogo = "oidc.png"
- u, err := url.Parse(h.app.constants.Security.OIDC.Provider)
+ u, err := url.Parse(a.constants.Security.OIDC.Provider)
if err == nil {
h := strings.Split(u.Hostname(), ".")
@@ -211,7 +211,7 @@ func (h *Handlers) renderLoginPage(c echo.Context, loginErr error) error {
}
out := loginTpl{
- Title: h.app.i18n.T("users.login"),
+ Title: a.i18n.T("users.login"),
PasswordEnabled: true,
OIDCProvider: oidcProvider,
OIDCProviderLogo: oidcLogo,
@@ -230,8 +230,8 @@ func (h *Handlers) renderLoginPage(c echo.Context, loginErr error) error {
// Generate and set a nonce for preventing CSRF requests that will be valided in the subsequent requests.
nonce, err := utils.GenerateRandomString(16)
if err != nil {
- h.app.log.Printf("error generating OIDC nonce: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.internalError"))
+ a.log.Printf("error generating OIDC nonce: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.internalError"))
}
c.SetCookie(&http.Cookie{
Name: "nonce",
@@ -247,14 +247,14 @@ func (h *Handlers) renderLoginPage(c echo.Context, loginErr error) error {
}
// renderLoginSetupPage renders the first time user setup page.
-func (h *Handlers) renderLoginSetupPage(c echo.Context, loginErr error) error {
+func (a *App) renderLoginSetupPage(c echo.Context, loginErr error) error {
next := utils.SanitizeURI(c.FormValue("next"))
if next == "/" {
next = uriAdmin
}
out := loginTpl{
- Title: h.app.i18n.T("users.login"),
+ Title: a.i18n.T("users.login"),
PasswordEnabled: true,
NextURI: next,
}
@@ -272,21 +272,21 @@ func (h *Handlers) renderLoginSetupPage(c echo.Context, loginErr error) error {
}
// doLogin logs a user in with a username and password.
-func (h *Handlers) doLogin(c echo.Context) error {
+func (a *App) doLogin(c echo.Context) error {
var (
username = strings.TrimSpace(c.FormValue("username"))
password = strings.TrimSpace(c.FormValue("password"))
)
if !strHasLen(username, 3, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if !strHasLen(password, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
// Log the user in by fetching and verifying credentials from the DB.
- user, err := h.app.core.LoginUser(username, password)
+ user, err := a.core.LoginUser(username, password)
if err != nil {
return err
}
@@ -297,7 +297,7 @@ func (h *Handlers) doLogin(c echo.Context) error {
}
// Set the session in the DB and cookie.
- if err := h.app.auth.SaveSession(user, "", c); err != nil {
+ if err := a.auth.SaveSession(user, "", c); err != nil {
return err
}
@@ -305,7 +305,7 @@ func (h *Handlers) doLogin(c echo.Context) error {
}
// doFirstTimeSetup sets a user up for the first time.
-func (h *Handlers) doFirstTimeSetup(c echo.Context) error {
+func (a *App) doFirstTimeSetup(c echo.Context) error {
var (
email = strings.TrimSpace(c.FormValue("email"))
username = strings.TrimSpace(c.FormValue("username"))
@@ -313,16 +313,16 @@ func (h *Handlers) doFirstTimeSetup(c echo.Context) error {
password2 = strings.TrimSpace(c.FormValue("password2"))
)
if !utils.ValidateEmail(email) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
if !strHasLen(username, 3, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if !strHasLen(password, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
if password != password2 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("users.passwordMismatch"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("users.passwordMismatch"))
}
// Create the default "Super Admin" with all permission.
@@ -330,12 +330,12 @@ func (h *Handlers) doFirstTimeSetup(c echo.Context) error {
Type: auth.RoleTypeUser,
Name: null.NewString("Super Admin", true),
}
- for p := range h.app.constants.Permissions {
+ for p := range a.constants.Permissions {
r.Permissions = append(r.Permissions, p)
}
// Create the role in the DB.
- role, err := h.app.core.CreateRole(r)
+ role, err := a.core.CreateRole(r)
if err != nil {
return err
}
@@ -352,18 +352,18 @@ func (h *Handlers) doFirstTimeSetup(c echo.Context) error {
UserRoleID: role.ID,
Status: auth.UserStatusEnabled,
}
- if _, err := h.app.core.CreateUser(u); err != nil {
+ if _, err := a.core.CreateUser(u); err != nil {
return err
}
// Log the user in directly.
- user, err := h.app.core.LoginUser(username, password)
+ user, err := a.core.LoginUser(username, password)
if err != nil {
return err
}
// Set the session in the DB and cookie.
- if err := h.app.auth.SaveSession(user, "", c); err != nil {
+ if err := a.auth.SaveSession(user, "", c); err != nil {
return err
}
diff --git a/cmd/bounce.go b/cmd/bounce.go
index dce67455..a69973cf 100644
--- a/cmd/bounce.go
+++ b/cmd/bounce.go
@@ -12,11 +12,11 @@ import (
)
// GetBounces handles retrieval of bounce records.
-func (h *Handlers) GetBounces(c echo.Context) error {
+func (a *App) GetBounces(c echo.Context) error {
// Fetch one bounce from the DB.
id, _ := strconv.Atoi(c.Param("id"))
if id > 0 {
- out, err := h.app.core.GetBounce(id)
+ out, err := a.core.GetBounce(id)
if err != nil {
return err
}
@@ -26,13 +26,13 @@ func (h *Handlers) GetBounces(c echo.Context) error {
// Query and fetch bounces from the DB.
var (
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
campID, _ = strconv.Atoi(c.QueryParam("campaign_id"))
source = c.FormValue("source")
orderBy = c.FormValue("order_by")
order = c.FormValue("order")
)
- res, total, err := h.app.core.QueryBounces(campID, 0, source, orderBy, order, pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryBounces(campID, 0, source, orderBy, order, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -53,14 +53,14 @@ func (h *Handlers) GetBounces(c echo.Context) error {
}
// GetSubscriberBounces retrieves a subscriber's bounce records.
-func (h *Handlers) GetSubscriberBounces(c echo.Context) error {
+func (a *App) GetSubscriberBounces(c echo.Context) error {
subID, _ := strconv.Atoi(c.Param("id"))
if subID < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Query and fetch bounces from the DB.
- out, _, err := h.app.core.QueryBounces(0, subID, "", "", "", 0, 1000)
+ out, _, err := a.core.QueryBounces(0, subID, "", "", "", 0, 1000)
if err != nil {
return err
}
@@ -69,7 +69,7 @@ func (h *Handlers) GetSubscriberBounces(c echo.Context) error {
}
// DeleteBounces handles bounce deletion, either a single one (ID in the URI), or a list.
-func (h *Handlers) DeleteBounces(c echo.Context) error {
+func (a *App) DeleteBounces(c echo.Context) error {
// Is it an /:id call?
var (
all, _ = strconv.ParseBool(c.QueryParam("all"))
@@ -80,24 +80,24 @@ func (h *Handlers) DeleteBounces(c echo.Context) error {
if idStr != "" {
id, _ := strconv.Atoi(idStr)
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
ids = append(ids, id)
} else if !all {
// There are multiple IDs in the query string.
i, err := parseStringIDs(c.Request().URL.Query()["id"])
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidID", "error", err.Error()))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidID", "error", err.Error()))
}
if len(i) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidID"))
}
ids = i
}
// Delete bounces from the DB.
- if err := h.app.core.DeleteBounces(ids); err != nil {
+ if err := a.core.DeleteBounces(ids); err != nil {
return err
}
@@ -105,12 +105,12 @@ func (h *Handlers) DeleteBounces(c echo.Context) error {
}
// BounceWebhook renders the HTML preview of a template.
-func (h *Handlers) BounceWebhook(c echo.Context) error {
+func (a *App) BounceWebhook(c echo.Context) error {
// Read the request body instead of using c.Bind() to read to save the entire raw request as meta.
rawReq, err := io.ReadAll(c.Request().Body)
if err != nil {
- h.app.log.Printf("error reading ses notification body: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.internalError"))
+ a.log.Printf("error reading ses notification body: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.internalError"))
}
var (
@@ -123,10 +123,10 @@ func (h *Handlers) BounceWebhook(c echo.Context) error {
case service == "":
var b models.Bounce
if err := json.Unmarshal(rawReq, &b); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidData")+":"+err.Error())
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidData")+":"+err.Error())
}
- if bv, err := h.validateBounceFields(b); err != nil {
+ if bv, err := a.validateBounceFields(b); err != nil {
return err
} else {
b = bv
@@ -143,99 +143,99 @@ func (h *Handlers) BounceWebhook(c echo.Context) error {
bounces = append(bounces, b)
// Amazon SES.
- case service == "ses" && h.app.constants.BounceSESEnabled:
+ case service == "ses" && a.constants.BounceSESEnabled:
switch c.Request().Header.Get("X-Amz-Sns-Message-Type") {
// SNS webhook registration confirmation. Only after these are processed will the endpoint
// start getting bounce notifications.
case "SubscriptionConfirmation", "UnsubscribeConfirmation":
- if err := h.app.bounce.SES.ProcessSubscription(rawReq); err != nil {
- h.app.log.Printf("error processing SNS (SES) subscription: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ if err := a.bounce.SES.ProcessSubscription(rawReq); err != nil {
+ a.log.Printf("error processing SNS (SES) subscription: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
// Bounce notification.
case "Notification":
- b, err := h.app.bounce.SES.ProcessBounce(rawReq)
+ b, err := a.bounce.SES.ProcessBounce(rawReq)
if err != nil {
- h.app.log.Printf("error processing SES notification: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ a.log.Printf("error processing SES notification: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
bounces = append(bounces, b)
default:
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
// SendGrid.
- case service == "sendgrid" && h.app.constants.BounceSendgridEnabled:
+ case service == "sendgrid" && a.constants.BounceSendgridEnabled:
var (
sig = c.Request().Header.Get("X-Twilio-Email-Event-Webhook-Signature")
ts = c.Request().Header.Get("X-Twilio-Email-Event-Webhook-Timestamp")
)
// Sendgrid sends multiple bounces.
- bs, err := h.app.bounce.Sendgrid.ProcessBounce(sig, ts, rawReq)
+ bs, err := a.bounce.Sendgrid.ProcessBounce(sig, ts, rawReq)
if err != nil {
- h.app.log.Printf("error processing sendgrid notification: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ a.log.Printf("error processing sendgrid notification: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
bounces = append(bounces, bs...)
// Postmark.
- case service == "postmark" && h.app.constants.BouncePostmarkEnabled:
- bs, err := h.app.bounce.Postmark.ProcessBounce(rawReq, c)
+ case service == "postmark" && a.constants.BouncePostmarkEnabled:
+ bs, err := a.bounce.Postmark.ProcessBounce(rawReq, c)
if err != nil {
- h.app.log.Printf("error processing postmark notification: %v", err)
+ a.log.Printf("error processing postmark notification: %v", err)
if _, ok := err.(*echo.HTTPError); ok {
return err
}
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
bounces = append(bounces, bs...)
// ForwardEmail.
- case service == "forwardemail" && h.app.constants.BounceForwardemailEnabled:
+ case service == "forwardemail" && a.constants.BounceForwardemailEnabled:
var (
sig = c.Request().Header.Get("X-Webhook-Signature")
)
- bs, err := h.app.bounce.Forwardemail.ProcessBounce(sig, rawReq)
+ bs, err := a.bounce.Forwardemail.ProcessBounce(sig, rawReq)
if err != nil {
- h.app.log.Printf("error processing forwardemail notification: %v", err)
+ a.log.Printf("error processing forwardemail notification: %v", err)
if _, ok := err.(*echo.HTTPError); ok {
return err
}
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
bounces = append(bounces, bs...)
default:
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("bounces.unknownService"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("bounces.unknownService"))
}
// Insert bounces into the DB.
for _, b := range bounces {
- if err := h.app.bounce.Record(b); err != nil {
- h.app.log.Printf("error recording bounce: %v", err)
+ if err := a.bounce.Record(b); err != nil {
+ a.log.Printf("error recording bounce: %v", err)
}
}
return c.JSON(http.StatusOK, okResp{true})
}
-func (h *Handlers) validateBounceFields(b models.Bounce) (models.Bounce, error) {
+func (a *App) validateBounceFields(b models.Bounce) (models.Bounce, error) {
if b.Email == "" && b.SubscriberUUID == "" {
- return b, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "email / subscriber_uuid"))
+ return b, echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "email / subscriber_uuid"))
}
if b.SubscriberUUID != "" && !reUUID.MatchString(b.SubscriberUUID) {
- return b, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "subscriber_uuid"))
+ return b, echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "subscriber_uuid"))
}
if b.Email != "" {
- em, err := h.app.importer.SanitizeEmail(b.Email)
+ em, err := a.importer.SanitizeEmail(b.Email)
if err != nil {
return b, echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
@@ -243,7 +243,7 @@ func (h *Handlers) validateBounceFields(b models.Bounce) (models.Bounce, error)
}
if b.Type != models.BounceTypeHard && b.Type != models.BounceTypeSoft && b.Type != models.BounceTypeComplaint {
- return b, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "type"))
+ return b, echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "type"))
}
return b, nil
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index 0c011d48..ca9e6d86 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -51,7 +51,7 @@ var (
)
// GetCampaigns handles retrieval of campaigns.
-func (h *Handlers) GetCampaigns(c echo.Context) error {
+func (a *App) GetCampaigns(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -67,7 +67,7 @@ func (h *Handlers) GetCampaigns(c echo.Context) error {
}
var (
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
status = c.QueryParams()["status"]
tags = c.QueryParams()["tag"]
@@ -78,7 +78,7 @@ func (h *Handlers) GetCampaigns(c echo.Context) error {
)
// Query and retrieve campaigns from the DB.
- res, total, err := h.app.core.QueryCampaigns(query, status, tags, orderBy, order, hasAllPerm, permittedLists, pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryCampaigns(query, status, tags, orderBy, order, hasAllPerm, permittedLists, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -107,19 +107,19 @@ func (h *Handlers) GetCampaigns(c echo.Context) error {
}
// GetCampaign handles retrieval of campaigns.
-func (h *Handlers) GetCampaign(c echo.Context) error {
+func (a *App) GetCampaign(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
return err
}
// Get the campaign from the DB.
- out, err := h.app.core.GetCampaign(id, "", "")
+ out, err := a.core.GetCampaign(id, "", "")
if err != nil {
return err
}
@@ -134,20 +134,20 @@ func (h *Handlers) GetCampaign(c echo.Context) error {
}
// PreviewCampaign renders the HTML preview of a campaign body.
-func (h *Handlers) PreviewCampaign(c echo.Context) error {
+func (a *App) PreviewCampaign(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
return err
}
// Fetch the campaign body from the DB.
tplID, _ := strconv.Atoi(c.FormValue("template_id"))
- camp, err := h.app.core.GetCampaignForPreview(id, tplID)
+ camp, err := a.core.GetCampaignForPreview(id, tplID)
if err != nil {
return err
}
@@ -161,18 +161,18 @@ func (h *Handlers) PreviewCampaign(c echo.Context) error {
// Use a dummy campaign ID to prevent views and clicks from {{ TrackView }}
// and {{ TrackLink }} being registered on preview.
camp.UUID = dummySubscriber.UUID
- if err := camp.CompileTemplate(h.app.manager.TemplateFuncs(&camp)); err != nil {
- h.app.log.Printf("error compiling template: %v", err)
+ if err := camp.CompileTemplate(a.manager.TemplateFuncs(&camp)); err != nil {
+ a.log.Printf("error compiling template: %v", err)
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.errorCompiling", "error", err.Error()))
+ a.i18n.Ts("templates.errorCompiling", "error", err.Error()))
}
// Render the message body.
- msg, err := h.app.manager.NewCampaignMessage(&camp, dummySubscriber)
+ msg, err := a.manager.NewCampaignMessage(&camp, dummySubscriber)
if err != nil {
- h.app.log.Printf("error rendering message: %v", err)
+ a.log.Printf("error rendering message: %v", err)
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.errorRendering", "error", err.Error()))
+ a.i18n.Ts("templates.errorRendering", "error", err.Error()))
}
if camp.ContentType == models.CampaignContentTypePlain {
@@ -183,10 +183,10 @@ func (h *Handlers) PreviewCampaign(c echo.Context) error {
}
// CampaignContent handles campaign content (body) format conversions.
-func (h *Handlers) CampaignContent(c echo.Context) error {
+func (a *App) CampaignContent(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
var camp campContentReq
@@ -204,7 +204,7 @@ func (h *Handlers) CampaignContent(c echo.Context) error {
// CreateCampaign handles campaign creation.
// Newly created campaigns are always drafts.
-func (h *Handlers) CreateCampaign(c echo.Context) error {
+func (a *App) CreateCampaign(c echo.Context) error {
var o campReq
if err := c.Bind(&o); err != nil {
return err
@@ -212,7 +212,7 @@ func (h *Handlers) CreateCampaign(c echo.Context) error {
// If the campaign's 'opt-in', prepare a default message.
if o.Type == models.CampaignTypeOptin {
- op, err := h.makeOptinCampaignMessage(o)
+ op, err := a.makeOptinCampaignMessage(o)
if err != nil {
return err
}
@@ -229,7 +229,7 @@ func (h *Handlers) CreateCampaign(c echo.Context) error {
}
// Validate.
- if c, err := h.validateCampaignFields(o); err != nil {
+ if c, err := a.validateCampaignFields(o); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
} else {
o = c
@@ -239,7 +239,7 @@ func (h *Handlers) CreateCampaign(c echo.Context) error {
o.ArchiveTemplateID = o.TemplateID
}
- out, err := h.app.core.CreateCampaign(o.Campaign, o.ListIDs, o.MediaIDs)
+ out, err := a.core.CreateCampaign(o.Campaign, o.ListIDs, o.MediaIDs)
if err != nil {
return err
}
@@ -249,26 +249,26 @@ func (h *Handlers) CreateCampaign(c echo.Context) error {
// UpdateCampaign handles campaign modification.
// Campaigns that are done cannot be modified.
-func (h *Handlers) UpdateCampaign(c echo.Context) error {
+func (a *App) UpdateCampaign(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
// Retrieve the campaign from the DB.
- cm, err := h.app.core.GetCampaign(id, "", "")
+ cm, err := a.core.GetCampaign(id, "", "")
if err != nil {
return err
}
if !canEditCampaign(cm.Status) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("campaigns.cantUpdate"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("campaigns.cantUpdate"))
}
// Read the incoming params into the existing campaign fields from the DB.
@@ -279,13 +279,13 @@ func (h *Handlers) UpdateCampaign(c echo.Context) error {
return err
}
- if c, err := h.validateCampaignFields(o); err != nil {
+ if c, err := a.validateCampaignFields(o); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
} else {
o = c
}
- out, err := h.app.core.UpdateCampaign(id, o.Campaign, o.ListIDs, o.MediaIDs)
+ out, err := a.core.UpdateCampaign(id, o.Campaign, o.ListIDs, o.MediaIDs)
if err != nil {
return err
}
@@ -294,14 +294,14 @@ func (h *Handlers) UpdateCampaign(c echo.Context) error {
}
// UpdateCampaignStatus handles campaign status modification.
-func (h *Handlers) UpdateCampaignStatus(c echo.Context) error {
+func (a *App) UpdateCampaignStatus(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -313,24 +313,24 @@ func (h *Handlers) UpdateCampaignStatus(c echo.Context) error {
}
// Update the campaign status in the DB.
- out, err := h.app.core.UpdateCampaignStatus(id, req.Status)
+ out, err := a.core.UpdateCampaignStatus(id, req.Status)
if err != nil {
return err
}
// If the campaign is being stopped, send the signal to the manager to stop it in flight.
if req.Status == models.CampaignStatusPaused || req.Status == models.CampaignStatusCancelled {
- h.app.manager.StopCampaign(id)
+ a.manager.StopCampaign(id)
}
return c.JSON(http.StatusOK, okResp{out})
}
// UpdateCampaignArchive handles campaign status modification.
-func (h *Handlers) UpdateCampaignArchive(c echo.Context) error {
+func (a *App) UpdateCampaignArchive(c echo.Context) error {
// Check if the user has access to the campaign.
id, _ := strconv.Atoi(c.Param("id"))
- if err := h.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -352,7 +352,7 @@ func (h *Handlers) UpdateCampaignArchive(c echo.Context) error {
req.ArchiveSlug = s
}
- if err := h.app.core.UpdateCampaignArchive(id, req.Archive, req.TemplateID, req.Meta, req.ArchiveSlug); err != nil {
+ if err := a.core.UpdateCampaignArchive(id, req.Archive, req.TemplateID, req.Meta, req.ArchiveSlug); err != nil {
return err
}
@@ -361,19 +361,19 @@ func (h *Handlers) UpdateCampaignArchive(c echo.Context) error {
// DeleteCampaign handles campaign deletion.
// Only scheduled campaigns that have not started yet can be deleted.
-func (h *Handlers) DeleteCampaign(c echo.Context) error {
+func (a *App) DeleteCampaign(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
// Delete the campaign from the DB.
- if err := h.app.core.DeleteCampaign(id); err != nil {
+ if err := a.core.DeleteCampaign(id); err != nil {
return err
}
@@ -381,9 +381,9 @@ func (h *Handlers) DeleteCampaign(c echo.Context) error {
}
// GetRunningCampaignStats returns stats of a given set of campaign IDs.
-func (h *Handlers) GetRunningCampaignStats(c echo.Context) error {
+func (a *App) GetRunningCampaignStats(c echo.Context) error {
// Get the running campaign stats from the DB.
- out, err := h.app.core.GetRunningCampaignStats()
+ out, err := a.core.GetRunningCampaignStats()
if err != nil {
return err
}
@@ -406,7 +406,7 @@ func (h *Handlers) GetRunningCampaignStats(c echo.Context) error {
out[i].NetRate = rate
// Realtime running rate over the last minute.
- out[i].Rate = h.app.manager.GetCampaignStats(c.ID).SendRate
+ out[i].Rate = a.manager.GetCampaignStats(c.ID).SendRate
}
}
@@ -415,14 +415,14 @@ func (h *Handlers) GetRunningCampaignStats(c echo.Context) error {
// TestCampaign handles the sending of a campaign message to
// arbitrary subscribers for testing.
-func (h *Handlers) TestCampaign(c echo.Context) error {
+func (a *App) TestCampaign(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.errorID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.errorID"))
}
// Check if the user has access to the campaign.
- if err := h.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
+ if err := a.checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -433,13 +433,13 @@ func (h *Handlers) TestCampaign(c echo.Context) error {
}
// Validate.
- if c, err := h.validateCampaignFields(req); err != nil {
+ if c, err := a.validateCampaignFields(req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
} else {
req = c
}
if len(req.SubscriberEmails) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("campaigns.noSubsToTest"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("campaigns.noSubsToTest"))
}
// Sanitize subscriber e-mails.
@@ -448,14 +448,14 @@ func (h *Handlers) TestCampaign(c echo.Context) error {
}
// Get the subscribers from the DB by their e-mails.
- subs, err := h.app.core.GetSubscribersByEmail(req.SubscriberEmails)
+ subs, err := a.core.GetSubscribersByEmail(req.SubscriberEmails)
if err != nil {
return err
}
// Get the campaign from the DB for previewing.
tplID, _ := strconv.Atoi(c.FormValue("template_id"))
- camp, err := h.app.core.GetCampaignForPreview(id, tplID)
+ camp, err := a.core.GetCampaignForPreview(id, tplID)
if err != nil {
return err
}
@@ -480,10 +480,10 @@ func (h *Handlers) TestCampaign(c echo.Context) error {
for _, s := range subs {
sub := s
- if err := h.sendTestMessage(sub, &camp); err != nil {
- h.app.log.Printf("error sending test message: %v", err)
+ if err := a.sendTestMessage(sub, &camp); err != nil {
+ a.log.Printf("error sending test message: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("campaigns.errorSendTest", "error", err.Error()))
+ a.i18n.Ts("campaigns.errorSendTest", "error", err.Error()))
}
}
@@ -491,16 +491,16 @@ func (h *Handlers) TestCampaign(c echo.Context) error {
}
// GetCampaignViewAnalytics retrieves view counts for a campaign.
-func (h *Handlers) GetCampaignViewAnalytics(c echo.Context) error {
+func (a *App) GetCampaignViewAnalytics(c echo.Context) error {
ids, err := parseStringIDs(c.Request().URL.Query()["id"])
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
}
if len(ids) == 0 {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.missingFields", "name", "`id`"))
+ a.i18n.Ts("globals.messages.missingFields", "name", "`id`"))
}
var (
@@ -509,12 +509,12 @@ func (h *Handlers) GetCampaignViewAnalytics(c echo.Context) error {
to = c.QueryParams().Get("to")
)
if !strHasLen(from, 10, 30) || !strHasLen(to, 10, 30) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("analytics.invalidDates"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("analytics.invalidDates"))
}
// Campaign link stats.
if typ == "links" {
- out, err := h.app.core.GetCampaignAnalyticsLinks(ids, typ, from, to)
+ out, err := a.core.GetCampaignAnalyticsLinks(ids, typ, from, to)
if err != nil {
return err
}
@@ -523,7 +523,7 @@ func (h *Handlers) GetCampaignViewAnalytics(c echo.Context) error {
}
// Get the analytics numbers from the DB for the campaigns.
- out, err := h.app.core.GetCampaignAnalyticsCounts(ids, typ, from, to)
+ out, err := a.core.GetCampaignAnalyticsCounts(ids, typ, from, to)
if err != nil {
return err
}
@@ -532,60 +532,60 @@ func (h *Handlers) GetCampaignViewAnalytics(c echo.Context) error {
}
// sendTestMessage takes a campaign and a subscriber and sends out a sample campaign message.
-func (h *Handlers) sendTestMessage(sub models.Subscriber, camp *models.Campaign) error {
- if err := camp.CompileTemplate(h.app.manager.TemplateFuncs(camp)); err != nil {
- h.app.log.Printf("error compiling template: %v", err)
+func (a *App) sendTestMessage(sub models.Subscriber, camp *models.Campaign) error {
+ if err := camp.CompileTemplate(a.manager.TemplateFuncs(camp)); err != nil {
+ a.log.Printf("error compiling template: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("templates.errorCompiling", "error", err.Error()))
+ a.i18n.Ts("templates.errorCompiling", "error", err.Error()))
}
// Create a sample campaign message.
- msg, err := h.app.manager.NewCampaignMessage(camp, sub)
+ msg, err := a.manager.NewCampaignMessage(camp, sub)
if err != nil {
- h.app.log.Printf("error rendering message: %v", err)
- return echo.NewHTTPError(http.StatusNotFound, h.app.i18n.Ts("templates.errorRendering", "error", err.Error()))
+ a.log.Printf("error rendering message: %v", err)
+ return echo.NewHTTPError(http.StatusNotFound, a.i18n.Ts("templates.errorRendering", "error", err.Error()))
}
- return h.app.manager.PushCampaignMessage(msg)
+ return a.manager.PushCampaignMessage(msg)
}
// validateCampaignFields validates incoming campaign field values.
-func (h *Handlers) validateCampaignFields(c campReq) (campReq, error) {
+func (a *App) validateCampaignFields(c campReq) (campReq, error) {
if c.FromEmail == "" {
- c.FromEmail = h.app.constants.FromEmail
+ c.FromEmail = a.constants.FromEmail
} else if !reFromAddress.Match([]byte(c.FromEmail)) {
- if _, err := h.app.importer.SanitizeEmail(c.FromEmail); err != nil {
- return c, errors.New(h.app.i18n.T("campaigns.fieldInvalidFromEmail"))
+ if _, err := a.importer.SanitizeEmail(c.FromEmail); err != nil {
+ return c, errors.New(a.i18n.T("campaigns.fieldInvalidFromEmail"))
}
}
if !strHasLen(c.Name, 1, stdInputMaxLen) {
- return c, errors.New(h.app.i18n.T("campaigns.fieldInvalidName"))
+ return c, errors.New(a.i18n.T("campaigns.fieldInvalidName"))
}
// Larger char limit for subject as it can contain {{ go templating }} logic.
if !strHasLen(c.Subject, 1, 5000) {
- return c, errors.New(h.app.i18n.T("campaigns.fieldInvalidSubject"))
+ return c, errors.New(a.i18n.T("campaigns.fieldInvalidSubject"))
}
// If there's a "send_at" date, it should be in the future.
if c.SendAt.Valid {
if c.SendAt.Time.Before(time.Now()) {
- return c, errors.New(h.app.i18n.T("campaigns.fieldInvalidSendAt"))
+ return c, errors.New(a.i18n.T("campaigns.fieldInvalidSendAt"))
}
}
if len(c.ListIDs) == 0 {
- return c, errors.New(h.app.i18n.T("campaigns.fieldInvalidListIDs"))
+ return c, errors.New(a.i18n.T("campaigns.fieldInvalidListIDs"))
}
- if !h.app.manager.HasMessenger(c.Messenger) {
- return c, errors.New(h.app.i18n.Ts("campaigns.fieldInvalidMessenger", "name", c.Messenger))
+ if !a.manager.HasMessenger(c.Messenger) {
+ return c, errors.New(a.i18n.Ts("campaigns.fieldInvalidMessenger", "name", c.Messenger))
}
camp := models.Campaign{Body: c.Body, TemplateBody: tplTag}
- if err := c.CompileTemplate(h.app.manager.TemplateFuncs(&camp)); err != nil {
- return c, errors.New(h.app.i18n.Ts("campaigns.fieldInvalidBody", "error", err.Error()))
+ if err := c.CompileTemplate(a.manager.TemplateFuncs(&camp)); err != nil {
+ return c, errors.New(a.i18n.Ts("campaigns.fieldInvalidBody", "error", err.Error()))
}
if len(c.Headers) == 0 {
@@ -612,20 +612,20 @@ func (h *Handlers) validateCampaignFields(c campReq) (campReq, error) {
}
// makeOptinCampaignMessage makes a default opt-in campaign message body.
-func (h *Handlers) makeOptinCampaignMessage(o campReq) (campReq, error) {
+func (a *App) makeOptinCampaignMessage(o campReq) (campReq, error) {
if len(o.ListIDs) == 0 {
- return o, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("campaigns.fieldInvalidListIDs"))
+ return o, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("campaigns.fieldInvalidListIDs"))
}
// Fetch double opt-in lists from the given list IDs from the DB.
- lists, err := h.app.core.GetListsByOptin(o.ListIDs, models.ListOptinDouble)
+ lists, err := a.core.GetListsByOptin(o.ListIDs, models.ListOptinDouble)
if err != nil {
return o, err
}
// There are no double opt-in lists.
if len(lists) == 0 {
- return o, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("campaigns.noOptinLists"))
+ return o, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("campaigns.noOptinLists"))
}
// Construct the opt-in URL with list IDs.
@@ -639,13 +639,13 @@ func (h *Handlers) makeOptinCampaignMessage(o campReq) (campReq, error) {
// Prepare sample opt-in message for the campaign.
var b bytes.Buffer
- if err := h.app.notifs.Tpls.ExecuteTemplate(&b, "optin-campaign", struct {
+ if err := a.notifs.Tpls.ExecuteTemplate(&b, "optin-campaign", struct {
Lists []models.List
OptinURLAttr template.HTMLAttr
}{lists, optinURLAttr}); err != nil {
- h.app.log.Printf("error compiling 'optin-campaign' template: %v", err)
+ a.log.Printf("error compiling 'optin-campaign' template: %v", err)
return o, echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.errorCompiling", "error", err.Error()))
+ a.i18n.Ts("templates.errorCompiling", "error", err.Error()))
}
o.Body = b.String()
@@ -653,7 +653,7 @@ func (h *Handlers) makeOptinCampaignMessage(o campReq) (campReq, error) {
}
// checkCampaignPerm checks if the user has get or manage access to the given campaign.
-func (h *Handlers) checkCampaignPerm(types auth.PermType, id int, c echo.Context) error {
+func (a *App) checkCampaignPerm(types auth.PermType, id int, c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -677,11 +677,11 @@ func (h *Handlers) checkCampaignPerm(types auth.PermType, id int, c echo.Context
// all campaigns. If there are no *_all permissions, then ensure that the
// campaign belongs to the lists that the user has access to.
if hasAllPerm, permittedListIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage); !hasAllPerm {
- if ok, err := h.app.core.CampaignHasLists(id, permittedListIDs); err != nil {
+ if ok, err := a.core.CampaignHasLists(id, permittedListIDs); err != nil {
return err
} else if !ok {
return echo.NewHTTPError(http.StatusForbidden,
- h.app.i18n.Ts("globals.messages.permissionDenied", "name", perm))
+ a.i18n.Ts("globals.messages.permissionDenied", "name", perm))
}
}
diff --git a/cmd/events.go b/cmd/events.go
index 2a3085c8..97e19bd8 100644
--- a/cmd/events.go
+++ b/cmd/events.go
@@ -11,7 +11,7 @@ import (
// EventStream serves an endpoint that never closes and pushes a
// live event stream (text/event-stream) such as a error messages.
-func (h *Handlers) EventStream(c echo.Context) error {
+func (a *App) EventStream(c echo.Context) error {
hdr := c.Response().Header()
hdr.Set(echo.HeaderContentType, "text/event-stream")
hdr.Set(echo.HeaderCacheControl, "no-store")
@@ -19,7 +19,7 @@ func (h *Handlers) EventStream(c echo.Context) error {
// Subscribe to the event stream with a random ID.
id := fmt.Sprintf("api:%v", time.Now().UnixNano())
- sub, err := h.app.events.Subscribe(id)
+ sub, err := a.events.Subscribe(id)
if err != nil {
log.Fatalf("error subscribing to events: %v", err)
}
@@ -30,7 +30,7 @@ func (h *Handlers) EventStream(c echo.Context) error {
case e := <-sub:
b, err := json.Marshal(e)
if err != nil {
- h.app.log.Printf("error marshalling event: %v", err)
+ a.log.Printf("error marshalling event: %v", err)
continue
}
@@ -39,7 +39,7 @@ func (h *Handlers) EventStream(c echo.Context) error {
case <-ctx.Done():
// On HTTP connection close, unsubscribe.
- h.app.events.Unsubscribe(id)
+ a.events.Unsubscribe(id)
return nil
}
}
diff --git a/cmd/handlers.go b/cmd/handlers.go
index 5aa50d77..d50a2d68 100644
--- a/cmd/handlers.go
+++ b/cmd/handlers.go
@@ -24,48 +24,32 @@ type okResp struct {
Data any `json:"data"`
}
-type Handlers struct {
- app *App
-}
-
var (
reUUID = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
)
// registerHandlers registers HTTP handlers.
-func initHTTPHandlers(e *echo.Echo, app *App) {
+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 {
- app.log.Println(err.Error())
+ a.log.Println(err.Error())
}
e.DefaultHTTPErrorHandler(err, c)
}
- var (
- // Authenticated /api/* handlers.
- api = e.Group("", app.auth.Middleware, func(next echo.HandlerFunc) echo.HandlerFunc {
- return func(c echo.Context) error {
- u := c.Get(auth.UserHTTPCtxKey)
-
- // On no-auth, respond with a JSON error.
- if err, ok := u.(*echo.HTTPError); ok {
- return err
- }
-
- return next(c)
- }
- })
-
- // Authenticated non /api handlers.
- a = e.Group("", app.auth.Middleware, func(next echo.HandlerFunc) echo.HandlerFunc {
+ // =================================================================
+ // Authenticated non /api handlers.
+ {
+ // Attach a middleware to the group that checks for auth.
+ g := e.Group("", a.auth.Middleware, func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
u := c.Get(auth.UserHTTPCtxKey)
// On no-auth, redirect to login page
if _, ok := u.(*echo.HTTPError); ok {
- u, _ := url.Parse(app.constants.LoginURL)
+ u, _ := url.Parse(a.constants.LoginURL)
q := url.Values{}
q.Set("next", c.Request().RequestURI)
u.RawQuery = q.Encode()
@@ -76,223 +60,236 @@ func initHTTPHandlers(e *echo.Echo, app *App) {
}
})
- // Public unauthenticated endpoints.
- p = e.Group("")
+ // Authenticated endpoints.
+ g.GET(path.Join(uriAdmin, ""), a.AdminPage)
+ g.GET(path.Join(uriAdmin, "/custom.css"), serveCustomAppearance("admin.custom_css"))
+ g.GET(path.Join(uriAdmin, "/custom.js"), serveCustomAppearance("admin.custom_js"))
+ g.GET(path.Join(uriAdmin, "/*"), a.AdminPage)
+ }
+
+ // =================================================================
+ // Authenticated /api/* handlers.
+ {
+ var (
+ // Permission check middleware.
+ pm = a.auth.Perm
+
+ // Attach a middleware to the group that checks for auth.
+ g = e.Group("", a.auth.Middleware, func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ u := c.Get(auth.UserHTTPCtxKey)
+
+ // On no-auth, respond with a JSON error.
+ if err, ok := u.(*echo.HTTPError); ok {
+ return err
+ }
- h = &Handlers{
- app: app,
+ return next(c)
+ }
+ })
+ )
+
+ // API endpoints.
+ g.GET("/api/health", a.HealthCheck)
+ g.GET("/api/config", a.GetServerConfig)
+ g.GET("/api/lang/:lang", a.GetI18nLang)
+ g.GET("/api/dashboard/charts", a.GetDashboardCharts)
+ g.GET("/api/dashboard/counts", a.GetDashboardCounts)
+
+ g.GET("/api/settings", pm(a.GetSettings, "settings:get"))
+ g.PUT("/api/settings", pm(a.UpdateSettings, "settings:manage"))
+ g.POST("/api/settings/smtp/test", pm(a.TestSMTPSettings, "settings:manage"))
+ g.POST("/api/admin/reload", pm(a.ReloadApp, "settings:manage"))
+ g.GET("/api/logs", pm(a.GetLogs, "settings:get"))
+ g.GET("/api/events", pm(a.EventStream, "settings:get"))
+ g.GET("/api/about", a.GetAboutInfo)
+
+ g.GET("/api/subscribers", pm(a.QuerySubscribers, "subscribers:get_all", "subscribers:get"))
+ g.GET("/api/subscribers/:id", pm(a.GetSubscriber, "subscribers:get_all", "subscribers:get"))
+ g.GET("/api/subscribers/:id/export", pm(a.ExportSubscriberData, "subscribers:get_all", "subscribers:get"))
+ g.GET("/api/subscribers/:id/bounces", pm(a.GetSubscriberBounces, "bounces:get"))
+ g.DELETE("/api/subscribers/:id/bounces", pm(a.DeleteSubscriberBounces, "bounces:manage"))
+ g.POST("/api/subscribers", pm(a.CreateSubscriber, "subscribers:manage"))
+ g.PUT("/api/subscribers/:id", pm(a.UpdateSubscriber, "subscribers:manage"))
+ g.POST("/api/subscribers/:id/optin", pm(a.SubscriberSendOptin, "subscribers:manage"))
+ g.PUT("/api/subscribers/blocklist", pm(a.BlocklistSubscribers, "subscribers:manage"))
+ g.PUT("/api/subscribers/:id/blocklist", pm(a.BlocklistSubscribers, "subscribers:manage"))
+ g.PUT("/api/subscribers/lists/:id", pm(a.ManageSubscriberLists, "subscribers:manage"))
+ g.PUT("/api/subscribers/lists", pm(a.ManageSubscriberLists, "subscribers:manage"))
+ g.DELETE("/api/subscribers/:id", pm(a.DeleteSubscribers, "subscribers:manage"))
+ g.DELETE("/api/subscribers", pm(a.DeleteSubscribers, "subscribers:manage"))
+
+ g.GET("/api/bounces", pm(a.GetBounces, "bounces:get"))
+ g.GET("/api/bounces/:id", pm(a.GetBounces, "bounces:get"))
+ g.DELETE("/api/bounces", pm(a.DeleteBounces, "bounces:manage"))
+ g.DELETE("/api/bounces/:id", pm(a.DeleteBounces, "bounces:manage"))
+
+ // Subscriber operations based on arbitrary SQL queries.
+ // These aren't very REST-like.
+ g.POST("/api/subscribers/query/delete", pm(a.DeleteSubscribersByQuery, "subscribers:manage"))
+ g.PUT("/api/subscribers/query/blocklist", pm(a.BlocklistSubscribersByQuery, "subscribers:manage"))
+ g.PUT("/api/subscribers/query/lists", pm(a.ManageSubscriberListsByQuery, "subscribers:manage"))
+ g.GET("/api/subscribers/export",
+ pm(middleware.GzipWithConfig(middleware.GzipConfig{Level: 9})(a.ExportSubscribers), "subscribers:get_all", "subscribers:get"))
+
+ g.GET("/api/import/subscribers", pm(a.GetImportSubscribers, "subscribers:import"))
+ g.GET("/api/import/subscribers/logs", pm(a.GetImportSubscriberStats, "subscribers:import"))
+ g.POST("/api/import/subscribers", pm(a.ImportSubscribers, "subscribers:import"))
+ g.DELETE("/api/import/subscribers", pm(a.StopImportSubscribers, "subscribers:import"))
+
+ // Individual list permissions are applied directly within handleGetLists.
+ g.GET("/api/lists", a.GetLists)
+ g.GET("/api/lists/:id", a.GetList)
+ g.POST("/api/lists", pm(a.CreateList, "lists:manage_all"))
+ g.PUT("/api/lists/:id", a.UpdateList)
+ g.DELETE("/api/lists/:id", a.DeleteLists)
+
+ g.GET("/api/campaigns", pm(a.GetCampaigns, "campaigns:get_all", "campaigns:get"))
+ g.GET("/api/campaigns/running/stats", pm(a.GetRunningCampaignStats, "campaigns:get_all", "campaigns:get"))
+ g.GET("/api/campaigns/:id", pm(a.GetCampaign, "campaigns:get_all", "campaigns:get"))
+ g.GET("/api/campaigns/analytics/:type", pm(a.GetCampaignViewAnalytics, "campaigns:get_analytics"))
+ g.GET("/api/campaigns/:id/preview", pm(a.PreviewCampaign, "campaigns:get_all", "campaigns:get"))
+ g.POST("/api/campaigns/:id/preview", pm(a.PreviewCampaign, "campaigns:get_all", "campaigns:get"))
+ g.POST("/api/campaigns/:id/content", pm(a.CampaignContent, "campaigns:manage_all", "campaigns:manage"))
+ g.POST("/api/campaigns/:id/text", pm(a.PreviewCampaign, "campaigns:get"))
+ g.POST("/api/campaigns/:id/test", pm(a.TestCampaign, "campaigns:manage_all", "campaigns:manage"))
+ g.POST("/api/campaigns", pm(a.CreateCampaign, "campaigns:manage_all", "campaigns:manage"))
+ g.PUT("/api/campaigns/:id", pm(a.UpdateCampaign, "campaigns:manage_all", "campaigns:manage"))
+ g.PUT("/api/campaigns/:id/status", pm(a.UpdateCampaignStatus, "campaigns:manage_all", "campaigns:manage"))
+ g.PUT("/api/campaigns/:id/archive", pm(a.UpdateCampaignArchive, "campaigns:manage_all", "campaigns:manage"))
+ g.DELETE("/api/campaigns/:id", pm(a.DeleteCampaign, "campaigns:manage_all", "campaigns:manage"))
+
+ g.GET("/api/media", pm(a.GetMedia, "media:get"))
+ g.GET("/api/media/:id", pm(a.GetMedia, "media:get"))
+ g.POST("/api/media", pm(a.UploadMedia, "media:manage"))
+ g.DELETE("/api/media/:id", pm(a.DeleteMedia, "media:manage"))
+
+ g.GET("/api/templates", pm(a.GetTemplates, "templates:get"))
+ g.GET("/api/templates/:id", pm(a.GetTemplates, "templates:get"))
+ g.GET("/api/templates/:id/preview", pm(a.PreviewTemplate, "templates:get"))
+ g.POST("/api/templates/preview", pm(a.PreviewTemplate, "templates:get"))
+ g.POST("/api/templates", pm(a.CreateTemplate, "templates:manage"))
+ g.PUT("/api/templates/:id", pm(a.UpdateTemplate, "templates:manage"))
+ g.PUT("/api/templates/:id/default", pm(a.TemplateSetDefault, "templates:manage"))
+ g.DELETE("/api/templates/:id", pm(a.DeleteTemplate, "templates:manage"))
+
+ g.DELETE("/api/maintenance/subscribers/:type", pm(a.GCSubscribers, "settings:maintain"))
+ g.DELETE("/api/maintenance/analytics/:type", pm(a.GCCampaignAnalytics, "settings:maintain"))
+ g.DELETE("/api/maintenance/subscriptions/unconfirmed", pm(a.GCSubscriptions, "settings:maintain"))
+
+ g.POST("/api/tx", pm(a.SendTxMessage, "tx:send"))
+
+ g.GET("/api/profile", a.GetUserProfile)
+ g.PUT("/api/profile", a.UpdateUserProfile)
+ g.GET("/api/users", pm(a.GetUsers, "users:get"))
+ g.GET("/api/users/:id", pm(a.GetUsers, "users:get"))
+ g.POST("/api/users", pm(a.CreateUser, "users:manage"))
+ g.PUT("/api/users/:id", pm(a.UpdateUser, "users:manage"))
+ g.DELETE("/api/users", pm(a.DeleteUsers, "users:manage"))
+ g.DELETE("/api/users/:id", pm(a.DeleteUsers, "users:manage"))
+ g.POST("/api/logout", a.Logout)
+
+ g.GET("/api/roles/users", pm(a.GetUserRoles, "roles:get"))
+ g.GET("/api/roles/lists", pm(a.GeListRoles, "roles:get"))
+ g.POST("/api/roles/users", pm(a.CreateUserRole, "roles:manage"))
+ g.POST("/api/roles/lists", pm(a.CreateListRole, "roles:manage"))
+ g.PUT("/api/roles/users/:id", pm(a.UpdateUserRole, "roles:manage"))
+ g.PUT("/api/roles/lists/:id", pm(a.UpdateListRole, "roles:manage"))
+ g.DELETE("/api/roles/:id", pm(a.DeleteRole, "roles:manage"))
+
+ if a.constants.BounceWebhooksEnabled {
+ // Private authenticated bounce endpoint.
+ g.POST("/webhooks/bounce", pm(a.BounceWebhook, "webhooks:post_bounce"))
}
- )
-
- // Authenticated endpoints.
- a.GET(path.Join(uriAdmin, ""), h.AdminPage)
- a.GET(path.Join(uriAdmin, "/custom.css"), serveCustomAppearance("admin.custom_css"))
- a.GET(path.Join(uriAdmin, "/custom.js"), serveCustomAppearance("admin.custom_js"))
- a.GET(path.Join(uriAdmin, "/*"), h.AdminPage)
-
- pm := app.auth.Perm
-
- // API endpoints.
- api.GET("/api/health", h.HealthCheck)
- api.GET("/api/config", h.GetServerConfig)
- api.GET("/api/lang/:lang", h.GetI18nLang)
- api.GET("/api/dashboard/charts", h.GetDashboardCharts)
- api.GET("/api/dashboard/counts", h.GetDashboardCounts)
-
- api.GET("/api/settings", pm(h.GetSettings, "settings:get"))
- api.PUT("/api/settings", pm(h.UpdateSettings, "settings:manage"))
- api.POST("/api/settings/smtp/test", pm(h.TestSMTPSettings, "settings:manage"))
- api.POST("/api/admin/reload", pm(h.ReloadApp, "settings:manage"))
- api.GET("/api/logs", pm(h.GetLogs, "settings:get"))
- api.GET("/api/events", pm(h.EventStream, "settings:get"))
- api.GET("/api/about", h.GetAboutInfo)
-
- api.GET("/api/subscribers", pm(h.QuerySubscribers, "subscribers:get_all", "subscribers:get"))
- api.GET("/api/subscribers/:id", pm(h.GetSubscriber, "subscribers:get_all", "subscribers:get"))
- api.GET("/api/subscribers/:id/export", pm(h.ExportSubscriberData, "subscribers:get_all", "subscribers:get"))
- api.GET("/api/subscribers/:id/bounces", pm(h.GetSubscriberBounces, "bounces:get"))
- api.DELETE("/api/subscribers/:id/bounces", pm(h.DeleteSubscriberBounces, "bounces:manage"))
- api.POST("/api/subscribers", pm(h.CreateSubscriber, "subscribers:manage"))
- api.PUT("/api/subscribers/:id", pm(h.UpdateSubscriber, "subscribers:manage"))
- api.POST("/api/subscribers/:id/optin", pm(h.SubscriberSendOptin, "subscribers:manage"))
- api.PUT("/api/subscribers/blocklist", pm(h.BlocklistSubscribers, "subscribers:manage"))
- api.PUT("/api/subscribers/:id/blocklist", pm(h.BlocklistSubscribers, "subscribers:manage"))
- api.PUT("/api/subscribers/lists/:id", pm(h.ManageSubscriberLists, "subscribers:manage"))
- api.PUT("/api/subscribers/lists", pm(h.ManageSubscriberLists, "subscribers:manage"))
- api.DELETE("/api/subscribers/:id", pm(h.DeleteSubscribers, "subscribers:manage"))
- api.DELETE("/api/subscribers", pm(h.DeleteSubscribers, "subscribers:manage"))
-
- api.GET("/api/bounces", pm(h.GetBounces, "bounces:get"))
- api.GET("/api/bounces/:id", pm(h.GetBounces, "bounces:get"))
- api.DELETE("/api/bounces", pm(h.DeleteBounces, "bounces:manage"))
- api.DELETE("/api/bounces/:id", pm(h.DeleteBounces, "bounces:manage"))
-
- // Subscriber operations based on arbitrary SQL queries.
- // These aren't very REST-like.
- api.POST("/api/subscribers/query/delete", pm(h.DeleteSubscribersByQuery, "subscribers:manage"))
- api.PUT("/api/subscribers/query/blocklist", pm(h.BlocklistSubscribersByQuery, "subscribers:manage"))
- api.PUT("/api/subscribers/query/lists", pm(h.ManageSubscriberListsByQuery, "subscribers:manage"))
- api.GET("/api/subscribers/export",
- pm(middleware.GzipWithConfig(middleware.GzipConfig{Level: 9})(h.ExportSubscribers), "subscribers:get_all", "subscribers:get"))
-
- api.GET("/api/import/subscribers", pm(h.GetImportSubscribers, "subscribers:import"))
- api.GET("/api/import/subscribers/logs", pm(h.GetImportSubscriberStats, "subscribers:import"))
- api.POST("/api/import/subscribers", pm(h.ImportSubscribers, "subscribers:import"))
- api.DELETE("/api/import/subscribers", pm(h.StopImportSubscribers, "subscribers:import"))
-
- // Individual list permissions are applied directly within handleGetLists.
- api.GET("/api/lists", h.GetLists)
- api.GET("/api/lists/:id", h.GetList)
- api.POST("/api/lists", pm(h.CreateList, "lists:manage_all"))
- api.PUT("/api/lists/:id", h.UpdateList)
- api.DELETE("/api/lists/:id", h.DeleteLists)
-
- api.GET("/api/campaigns", pm(h.GetCampaigns, "campaigns:get_all", "campaigns:get"))
- api.GET("/api/campaigns/running/stats", pm(h.GetRunningCampaignStats, "campaigns:get_all", "campaigns:get"))
- api.GET("/api/campaigns/:id", pm(h.GetCampaign, "campaigns:get_all", "campaigns:get"))
- api.GET("/api/campaigns/analytics/:type", pm(h.GetCampaignViewAnalytics, "campaigns:get_analytics"))
- api.GET("/api/campaigns/:id/preview", pm(h.PreviewCampaign, "campaigns:get_all", "campaigns:get"))
- api.POST("/api/campaigns/:id/preview", pm(h.PreviewCampaign, "campaigns:get_all", "campaigns:get"))
- api.POST("/api/campaigns/:id/content", pm(h.CampaignContent, "campaigns:manage_all", "campaigns:manage"))
- api.POST("/api/campaigns/:id/text", pm(h.PreviewCampaign, "campaigns:get"))
- api.POST("/api/campaigns/:id/test", pm(h.TestCampaign, "campaigns:manage_all", "campaigns:manage"))
- api.POST("/api/campaigns", pm(h.CreateCampaign, "campaigns:manage_all", "campaigns:manage"))
- api.PUT("/api/campaigns/:id", pm(h.UpdateCampaign, "campaigns:manage_all", "campaigns:manage"))
- api.PUT("/api/campaigns/:id/status", pm(h.UpdateCampaignStatus, "campaigns:manage_all", "campaigns:manage"))
- api.PUT("/api/campaigns/:id/archive", pm(h.UpdateCampaignArchive, "campaigns:manage_all", "campaigns:manage"))
- api.DELETE("/api/campaigns/:id", pm(h.DeleteCampaign, "campaigns:manage_all", "campaigns:manage"))
-
- api.GET("/api/media", pm(h.GetMedia, "media:get"))
- api.GET("/api/media/:id", pm(h.GetMedia, "media:get"))
- api.POST("/api/media", pm(h.UploadMedia, "media:manage"))
- api.DELETE("/api/media/:id", pm(h.DeleteMedia, "media:manage"))
-
- api.GET("/api/templates", pm(h.GetTemplates, "templates:get"))
- api.GET("/api/templates/:id", pm(h.GetTemplates, "templates:get"))
- api.GET("/api/templates/:id/preview", pm(h.PreviewTemplate, "templates:get"))
- api.POST("/api/templates/preview", pm(h.PreviewTemplate, "templates:get"))
- api.POST("/api/templates", pm(h.CreateTemplate, "templates:manage"))
- api.PUT("/api/templates/:id", pm(h.UpdateTemplate, "templates:manage"))
- api.PUT("/api/templates/:id/default", pm(h.TemplateSetDefault, "templates:manage"))
- api.DELETE("/api/templates/:id", pm(h.DeleteTemplate, "templates:manage"))
-
- api.DELETE("/api/maintenance/subscribers/:type", pm(h.GCSubscribers, "settings:maintain"))
- api.DELETE("/api/maintenance/analytics/:type", pm(h.GCCampaignAnalytics, "settings:maintain"))
- api.DELETE("/api/maintenance/subscriptions/unconfirmed", pm(h.GCSubscriptions, "settings:maintain"))
-
- api.POST("/api/tx", pm(h.SendTxMessage, "tx:send"))
-
- api.GET("/api/profile", h.GetUserProfile)
- api.PUT("/api/profile", h.UpdateUserProfile)
- api.GET("/api/users", pm(h.GetUsers, "users:get"))
- api.GET("/api/users/:id", pm(h.GetUsers, "users:get"))
- api.POST("/api/users", pm(h.CreateUser, "users:manage"))
- api.PUT("/api/users/:id", pm(h.UpdateUser, "users:manage"))
- api.DELETE("/api/users", pm(h.DeleteUsers, "users:manage"))
- api.DELETE("/api/users/:id", pm(h.DeleteUsers, "users:manage"))
- api.POST("/api/logout", h.Logout)
-
- api.GET("/api/roles/users", pm(h.GetUserRoles, "roles:get"))
- api.GET("/api/roles/lists", pm(h.GeListRoles, "roles:get"))
- api.POST("/api/roles/users", pm(h.CreateUserRole, "roles:manage"))
- api.POST("/api/roles/lists", pm(h.CreateListRole, "roles:manage"))
- api.PUT("/api/roles/users/:id", pm(h.UpdateUserRole, "roles:manage"))
- api.PUT("/api/roles/lists/:id", pm(h.UpdateListRole, "roles:manage"))
- api.DELETE("/api/roles/:id", pm(h.DeleteRole, "roles:manage"))
-
- if app.constants.BounceWebhooksEnabled {
- // Private authenticated bounce endpoint.
- api.POST("/webhooks/bounce", pm(h.BounceWebhook, "webhooks:post_bounce"))
-
- // Public bounce endpoints for webservices like SES.
- p.POST("/webhooks/service/:service", h.BounceWebhook)
}
// =================================================================
// Public API endpoints.
+ {
+ // Public unauthenticated endpoints.
+ g := e.Group("")
- // Landing page.
- p.GET("/", func(c echo.Context) error {
- return c.Render(http.StatusOK, "home", publicTpl{Title: "listmonk"})
- })
+ if a.constants.BounceWebhooksEnabled {
+ // Public bounce endpoints for webservices like SES.
+ g.POST("/webhooks/service/:service", a.BounceWebhook)
+ }
- // Public admin endpoints (login page, OIDC endpoints).
- p.GET(path.Join(uriAdmin, "/login"), h.LoginPage)
- p.POST(path.Join(uriAdmin, "/login"), h.LoginPage)
+ // Landing page.
+ g.GET("/", func(c echo.Context) error {
+ return c.Render(http.StatusOK, "home", publicTpl{Title: "listmonk"})
+ })
- if app.constants.Security.OIDC.Enabled {
- p.POST("/auth/oidc", h.OIDCLogin)
- p.GET("/auth/oidc", h.OIDCFinish)
- }
+ // Public admin endpoints (login page, OIDC endpoints).
+ g.GET(path.Join(uriAdmin, "/login"), a.LoginPage)
+ g.POST(path.Join(uriAdmin, "/login"), a.LoginPage)
- // Public APIs.
- p.GET("/api/public/lists", h.GetPublicLists)
- p.POST("/api/public/subscription", h.PublicSubscription)
- if app.constants.EnablePublicArchive {
- p.GET("/api/public/archive", h.GetCampaignArchives)
- }
+ if a.constants.Security.OIDC.Enabled {
+ g.POST("/auth/oidc", a.OIDCLogin)
+ g.GET("/auth/oidc", a.OIDCFinish)
+ }
- // /public/static/* file server is registered in initHTTPServer().
- // Public subscriber facing views.
- p.GET("/subscription/form", h.SubscriptionFormPage)
- p.POST("/subscription/form", h.SubscriptionForm)
- p.GET("/subscription/:campUUID/:subUUID", noIndex(validateUUID(subscriberExists(h.SubscriptionPage),
- "campUUID", "subUUID")))
- p.POST("/subscription/:campUUID/:subUUID", validateUUID(subscriberExists(h.SubscriptionPrefs),
- "campUUID", "subUUID"))
- p.GET("/subscription/optin/:subUUID", noIndex(validateUUID(subscriberExists(h.OptinPage), "subUUID")))
- p.POST("/subscription/optin/:subUUID", validateUUID(subscriberExists(h.OptinPage), "subUUID"))
- p.POST("/subscription/export/:subUUID", validateUUID(subscriberExists(h.SelfExportSubscriberData),
- "subUUID"))
- p.POST("/subscription/wipe/:subUUID", validateUUID(subscriberExists(h.WipeSubscriberData),
- "subUUID"))
- p.GET("/link/:linkUUID/:campUUID/:subUUID", noIndex(validateUUID(h.LinkRedirect,
- "linkUUID", "campUUID", "subUUID")))
- p.GET("/campaign/:campUUID/:subUUID", noIndex(validateUUID(h.ViewCampaignMessage,
- "campUUID", "subUUID")))
- p.GET("/campaign/:campUUID/:subUUID/px.png", noIndex(validateUUID(h.RegisterCampaignView,
- "campUUID", "subUUID")))
-
- if app.constants.EnablePublicArchive {
- p.GET("/archive", h.CampaignArchivesPage)
- p.GET("/archive.xml", h.GetCampaignArchivesFeed)
- p.GET("/archive/:id", h.CampaignArchivePage)
- p.GET("/archive/latest", h.CampaignArchivePageLatest)
- }
+ // Public APIs.
+ g.GET("/api/public/lists", a.GetPublicLists)
+ g.POST("/api/public/subscription", a.PublicSubscription)
+ if a.constants.EnablePublicArchive {
+ g.GET("/api/public/archive", a.GetCampaignArchives)
+ }
+
+ // /public/static/* file server is registered in initHTTPServer().
+ // Public subscriber facing views.
+ g.GET("/subscription/form", a.SubscriptionFormPage)
+ g.POST("/subscription/form", a.SubscriptionForm)
+ g.GET("/subscription/:campUUID/:subUUID", noIndex(validateUUID(subscriberExists(a.SubscriptionPage), "campUUID", "subUUID")))
+ g.POST("/subscription/:campUUID/:subUUID", validateUUID(subscriberExists(a.SubscriptionPrefs), "campUUID", "subUUID"))
+ g.GET("/subscription/optin/:subUUID", noIndex(validateUUID(subscriberExists(a.OptinPage), "subUUID")))
+ g.POST("/subscription/optin/:subUUID", validateUUID(subscriberExists(a.OptinPage), "subUUID"))
+ g.POST("/subscription/export/:subUUID", validateUUID(subscriberExists(a.SelfExportSubscriberData), "subUUID"))
+ g.POST("/subscription/wipe/:subUUID", validateUUID(subscriberExists(a.WipeSubscriberData), "subUUID"))
+ g.GET("/link/:linkUUID/:campUUID/:subUUID", noIndex(validateUUID(a.LinkRedirect, "linkUUID", "campUUID", "subUUID")))
+ g.GET("/campaign/:campUUID/:subUUID", noIndex(validateUUID(a.ViewCampaignMessage, "campUUID", "subUUID")))
+ g.GET("/campaign/:campUUID/:subUUID/px.png", noIndex(validateUUID(a.RegisterCampaignView, "campUUID", "subUUID")))
+
+ if a.constants.EnablePublicArchive {
+ g.GET("/archive", a.CampaignArchivesPage)
+ g.GET("/archive.xml", a.GetCampaignArchivesFeed)
+ g.GET("/archive/:id", a.CampaignArchivePage)
+ g.GET("/archive/latest", a.CampaignArchivePageLatest)
+ }
+
+ g.GET("/public/custom.css", serveCustomAppearance("public.custom_css"))
+ g.GET("/public/custom.js", serveCustomAppearance("public.custom_js"))
+
+ // Public health API endpoint.
+ g.GET("/health", a.HealthCheck)
- p.GET("/public/custom.css", serveCustomAppearance("public.custom_css"))
- p.GET("/public/custom.js", serveCustomAppearance("public.custom_js"))
-
- // Public health API endpoint.
- p.GET("/health", h.HealthCheck)
-
- // 404 pages.
- p.RouteNotFound("/*", func(c echo.Context) error {
- return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl("404 - "+app.i18n.T("public.notFoundTitle"), "", ""))
- })
- p.RouteNotFound("/api/*", func(c echo.Context) error {
- return echo.NewHTTPError(http.StatusNotFound, "404 unknown endpoint")
- })
- p.RouteNotFound("/admin/*", func(c echo.Context) error {
- return echo.NewHTTPError(http.StatusNotFound, "404 page not found")
- })
+ // 404 pages.
+ g.RouteNotFound("/*", func(c echo.Context) error {
+ return c.Render(http.StatusNotFound, tplMessage,
+ makeMsgTpl("404 - "+a.i18n.T("public.notFoundTitle"), "", ""))
+ })
+ g.RouteNotFound("/api/*", func(c echo.Context) error {
+ return echo.NewHTTPError(http.StatusNotFound, "404 unknown endpoint")
+ })
+ g.RouteNotFound("/admin/*", func(c echo.Context) error {
+ return echo.NewHTTPError(http.StatusNotFound, "404 page not found")
+ })
+ }
}
// AdminPage is the root handler that renders the Javascript admin frontend.
-func (h *Handlers) AdminPage(c echo.Context) error {
- b, err := h.app.fs.Read(path.Join(uriAdmin, "/index.html"))
+func (a *App) AdminPage(c echo.Context) error {
+ b, err := a.fs.Read(path.Join(uriAdmin, "/index.html"))
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
- b = bytes.ReplaceAll(b, []byte("asset_version"), []byte(h.app.constants.AssetVersion))
+ b = bytes.ReplaceAll(b, []byte("asset_version"), []byte(a.constants.AssetVersion))
return c.HTMLBlob(http.StatusOK, b)
}
// HealthCheck is a healthcheck endpoint that returns a 200 response.
-func (h *Handlers) HealthCheck(c echo.Context) error {
+func (a *App) HealthCheck(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
}
diff --git a/cmd/i18n.go b/cmd/i18n.go
index 1a28b838..f3254017 100644
--- a/cmd/i18n.go
+++ b/cmd/i18n.go
@@ -25,13 +25,13 @@ type i18nLangRaw struct {
var reLangCode = regexp.MustCompile(`[^a-zA-Z_0-9\\-]`)
// GetI18nLang returns the JSON language pack given the language code.
-func (h *Handlers) GetI18nLang(c echo.Context) error {
+func (a *App) GetI18nLang(c echo.Context) error {
lang := c.Param("lang")
if len(lang) > 6 || reLangCode.MatchString(lang) {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid language code.")
}
- i, ok, err := getI18nLang(lang, h.app.fs)
+ i, ok, err := getI18nLang(lang, a.fs)
if err != nil && !ok {
return echo.NewHTTPError(http.StatusBadRequest, "Unknown language.")
}
@@ -40,8 +40,8 @@ func (h *Handlers) GetI18nLang(c echo.Context) error {
}
// getI18nLangList returns the list of available i18n languages.
-func getI18nLangList(app *App) ([]i18nLang, error) {
- list, err := app.fs.Glob("/i18n/*.json")
+func getI18nLangList(fs stuffbin.FileSystem) ([]i18nLang, error) {
+ list, err := fs.Glob("/i18n/*.json")
if err != nil {
return nil, err
}
@@ -49,7 +49,7 @@ func getI18nLangList(app *App) ([]i18nLang, error) {
// Read language JSON files from the fs.
var out []i18nLang
for _, l := range list {
- b, err := app.fs.Get(l)
+ b, err := fs.Get(l)
if err != nil {
return out, fmt.Errorf("error reading lang file: %s: %v", l, err)
}
diff --git a/cmd/import.go b/cmd/import.go
index 4b801566..8d7a0c68 100644
--- a/cmd/import.go
+++ b/cmd/import.go
@@ -14,22 +14,22 @@ import (
// ImportSubscribers handles the uploading and bulk importing of
// a ZIP file of one or more CSV files.
-func (h *Handlers) ImportSubscribers(c echo.Context) error {
+func (a *App) ImportSubscribers(c echo.Context) error {
// Is an import already running?
- if h.app.importer.GetStats().Status == subimporter.StatusImporting {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("import.alreadyRunning"))
+ if a.importer.GetStats().Status == subimporter.StatusImporting {
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("import.alreadyRunning"))
}
// Unmarshal the JSON params.
var opt subimporter.SessionOpt
if err := json.Unmarshal([]byte(c.FormValue("params")), &opt); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("import.invalidParams", "error", err.Error()))
+ a.i18n.Ts("import.invalidParams", "error", err.Error()))
}
// Validate mode.
if opt.Mode != subimporter.ModeSubscribe && opt.Mode != subimporter.ModeBlocklist {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("import.invalidMode"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("import.invalidMode"))
}
// If no status is specified, pick a default one.
@@ -45,18 +45,18 @@ func (h *Handlers) ImportSubscribers(c echo.Context) error {
if opt.SubStatus != models.SubscriptionStatusUnconfirmed &&
opt.SubStatus != models.SubscriptionStatusConfirmed &&
opt.SubStatus != models.SubscriptionStatusUnsubscribed {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("import.invalidSubStatus"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("import.invalidSubStatus"))
}
if len(opt.Delim) != 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("import.invalidDelim"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("import.invalidDelim"))
}
// Open the HTTP file.
file, err := c.FormFile("file")
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("import.invalidFile", "error", err.Error()))
+ a.i18n.Ts("import.invalidFile", "error", err.Error()))
}
src, err := file.Open()
@@ -69,21 +69,21 @@ func (h *Handlers) ImportSubscribers(c echo.Context) error {
out, err := os.CreateTemp("", "listmonk")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("import.errorCopyingFile", "error", err.Error()))
+ a.i18n.Ts("import.errorCopyingFile", "error", err.Error()))
}
defer out.Close()
if _, err = io.Copy(out, src); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("import.errorCopyingFile", "error", err.Error()))
+ a.i18n.Ts("import.errorCopyingFile", "error", err.Error()))
}
// Start the importer session.
opt.Filename = file.Filename
- sess, err := h.app.importer.NewSession(opt)
+ sess, err := a.importer.NewSession(opt)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("import.errorStarting", "error", err.Error()))
+ a.i18n.Ts("import.errorStarting", "error", err.Error()))
}
go sess.Start()
@@ -99,30 +99,30 @@ func (h *Handlers) ImportSubscribers(c echo.Context) error {
dir, files, err := sess.ExtractZIP(out.Name(), 1)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("import.errorProcessingZIP", "error", err.Error()))
+ a.i18n.Ts("import.errorProcessingZIP", "error", err.Error()))
}
go sess.LoadCSV(dir+"/"+files[0], rune(opt.Delim[0]))
}
- return c.JSON(http.StatusOK, okResp{h.app.importer.GetStats()})
+ return c.JSON(http.StatusOK, okResp{a.importer.GetStats()})
}
// GetImportSubscribers returns import statistics.
-func (h *Handlers) GetImportSubscribers(c echo.Context) error {
- s := h.app.importer.GetStats()
+func (a *App) GetImportSubscribers(c echo.Context) error {
+ s := a.importer.GetStats()
return c.JSON(http.StatusOK, okResp{s})
}
// GetImportSubscriberStats returns import statistics.
-func (h *Handlers) GetImportSubscriberStats(c echo.Context) error {
- return c.JSON(http.StatusOK, okResp{string(h.app.importer.GetLogs())})
+func (a *App) GetImportSubscriberStats(c echo.Context) error {
+ return c.JSON(http.StatusOK, okResp{string(a.importer.GetLogs())})
}
// StopImportSubscribers sends a stop signal to the importer.
// If there's an ongoing import, it'll be stopped, and if an import
// is finished, it's state is cleared.
-func (h *Handlers) StopImportSubscribers(c echo.Context) error {
- h.app.importer.Stop()
- return c.JSON(http.StatusOK, okResp{h.app.importer.GetStats()})
+func (a *App) StopImportSubscribers(c echo.Context) error {
+ a.importer.Stop()
+ return c.JSON(http.StatusOK, okResp{a.importer.GetStats()})
}
diff --git a/cmd/lists.go b/cmd/lists.go
index 08af5f05..594863d8 100644
--- a/cmd/lists.go
+++ b/cmd/lists.go
@@ -11,10 +11,10 @@ import (
)
// GetLists retrieves lists with additional metadata like subscriber counts.
-func (h *Handlers) GetLists(c echo.Context) error {
+func (a *App) GetLists(c echo.Context) error {
var (
user = auth.GetUser(c)
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
)
// Get the list IDs (or blanket permission) the user has access to.
@@ -23,7 +23,7 @@ func (h *Handlers) GetLists(c echo.Context) error {
// Minimal query simply returns the list of all lists without JOIN subscriber counts. This is fast.
minimal, _ := strconv.ParseBool(c.FormValue("minimal"))
if minimal {
- res, err := h.app.core.GetLists("", hasAllPerm, permittedIDs)
+ res, err := a.core.GetLists("", hasAllPerm, permittedIDs)
if err != nil {
return err
}
@@ -52,7 +52,7 @@ func (h *Handlers) GetLists(c echo.Context) error {
optin = c.FormValue("optin")
order = c.FormValue("order")
)
- res, total, err := h.app.core.QueryLists(query, typ, optin, tags, orderBy, order, hasAllPerm, permittedIDs, pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryLists(query, typ, optin, tags, orderBy, order, hasAllPerm, permittedIDs, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -70,13 +70,13 @@ func (h *Handlers) GetLists(c echo.Context) error {
// GetList retrieves a single list by id.
// It's permission checked by the listPerm middleware.
-func (h *Handlers) GetList(c echo.Context) error {
+func (a *App) GetList(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the list.
@@ -85,7 +85,7 @@ func (h *Handlers) GetList(c echo.Context) error {
}
// Get the list from the DB.
- out, err := h.app.core.GetList(id, "")
+ out, err := a.core.GetList(id, "")
if err != nil {
return err
}
@@ -94,7 +94,7 @@ func (h *Handlers) GetList(c echo.Context) error {
}
// CreateList handles list creation.
-func (h *Handlers) CreateList(c echo.Context) error {
+func (a *App) CreateList(c echo.Context) error {
l := models.List{}
if err := c.Bind(&l); err != nil {
return err
@@ -102,10 +102,10 @@ func (h *Handlers) CreateList(c echo.Context) error {
// Validate.
if !strHasLen(l.Name, 1, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("lists.invalidName"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("lists.invalidName"))
}
- out, err := h.app.core.CreateList(l)
+ out, err := a.core.CreateList(l)
if err != nil {
return err
}
@@ -115,13 +115,13 @@ func (h *Handlers) CreateList(c echo.Context) error {
// UpdateList handles list modification.
// It's permission checked by the listPerm middleware.
-func (h *Handlers) UpdateList(c echo.Context) error {
+func (a *App) UpdateList(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to the list.
@@ -137,11 +137,11 @@ func (h *Handlers) UpdateList(c echo.Context) error {
// Validate.
if !strHasLen(l.Name, 1, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("lists.invalidName"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("lists.invalidName"))
}
// Update the list in the DB.
- out, err := h.app.core.UpdateList(id, l)
+ out, err := a.core.UpdateList(id, l)
if err != nil {
return err
}
@@ -151,7 +151,7 @@ func (h *Handlers) UpdateList(c echo.Context) error {
// DeleteLists handles list deletion, either a single one (ID in the URI), or a list.
// It's permission checked by the listPerm middleware.
-func (h *Handlers) DeleteLists(c echo.Context) error {
+func (a *App) DeleteLists(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -160,7 +160,7 @@ func (h *Handlers) DeleteLists(c echo.Context) error {
ids []int
)
if id < 1 && len(ids) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
if id > 0 {
@@ -173,7 +173,7 @@ func (h *Handlers) DeleteLists(c echo.Context) error {
}
// Delete the lists from the DB.
- if err := h.app.core.DeleteLists(ids); err != nil {
+ if err := a.core.DeleteLists(ids); err != nil {
return err
}
diff --git a/cmd/maintenance.go b/cmd/maintenance.go
index aaac9d20..5bdac8c0 100644
--- a/cmd/maintenance.go
+++ b/cmd/maintenance.go
@@ -8,7 +8,7 @@ import (
)
// GCSubscribers garbage collects (deletes) orphaned or blocklisted subscribers.
-func (h *Handlers) GCSubscribers(c echo.Context) error {
+func (a *App) GCSubscribers(c echo.Context) error {
var (
typ = c.Param("type")
@@ -18,11 +18,11 @@ func (h *Handlers) GCSubscribers(c echo.Context) error {
switch typ {
case "blocklisted":
- n, err = h.app.core.DeleteBlocklistedSubscribers()
+ n, err = a.core.DeleteBlocklistedSubscribers()
case "orphan":
- n, err = h.app.core.DeleteOrphanSubscribers()
+ n, err = a.core.DeleteOrphanSubscribers()
default:
- err = echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ err = echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
if err != nil {
@@ -35,15 +35,15 @@ func (h *Handlers) GCSubscribers(c echo.Context) error {
}
// GCSubscriptions garbage collects (deletes) orphaned or blocklisted subscribers.
-func (h *Handlers) GCSubscriptions(c echo.Context) error {
+func (a *App) GCSubscriptions(c echo.Context) error {
// Validate the date.
t, err := time.Parse(time.RFC3339, c.FormValue("before_date"))
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
// Delete unconfirmed subscriptions from the DB in bulk.
- n, err := h.app.core.DeleteUnconfirmedSubscriptions(t)
+ n, err := a.core.DeleteUnconfirmedSubscriptions(t)
if err != nil {
return err
}
@@ -54,25 +54,25 @@ func (h *Handlers) GCSubscriptions(c echo.Context) error {
}
// GCCampaignAnalytics garbage collects (deletes) campaign analytics.
-func (h *Handlers) GCCampaignAnalytics(c echo.Context) error {
+func (a *App) GCCampaignAnalytics(c echo.Context) error {
t, err := time.Parse(time.RFC3339, c.FormValue("before_date"))
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
switch c.Param("type") {
case "all":
- if err := h.app.core.DeleteCampaignViews(t); err != nil {
+ if err := a.core.DeleteCampaignViews(t); err != nil {
return err
}
- err = h.app.core.DeleteCampaignLinkClicks(t)
+ err = a.core.DeleteCampaignLinkClicks(t)
case "views":
- err = h.app.core.DeleteCampaignViews(t)
+ err = a.core.DeleteCampaignViews(t)
case "clicks":
- err = h.app.core.DeleteCampaignLinkClicks(t)
+ err = a.core.DeleteCampaignLinkClicks(t)
default:
- err = echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidData"))
+ err = echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
}
if err != nil {
diff --git a/cmd/media.go b/cmd/media.go
index 34796f1c..a9cc7bec 100644
--- a/cmd/media.go
+++ b/cmd/media.go
@@ -24,18 +24,18 @@ var (
)
// UploadMedia handles media file uploads.
-func (h *Handlers) UploadMedia(c echo.Context) error {
+func (a *App) UploadMedia(c echo.Context) error {
file, err := c.FormFile("file")
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("media.invalidFile", "error", err.Error()))
+ a.i18n.Ts("media.invalidFile", "error", err.Error()))
}
// Read the file from the HTTP form.
src, err := file.Open()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("media.errorReadingFile", "error", err.Error()))
+ a.i18n.Ts("media.errorReadingFile", "error", err.Error()))
}
defer src.Close()
@@ -46,10 +46,10 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
)
// Validate file extension.
- if !inArray("*", h.app.constants.MediaUpload.Extensions) {
- if ok := inArray(ext, h.app.constants.MediaUpload.Extensions); !ok {
+ if !inArray("*", a.constants.MediaUpload.Extensions) {
+ if ok := inArray(ext, a.constants.MediaUpload.Extensions); !ok {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("media.unsupportedFileType", "type", ext))
+ a.i18n.Ts("media.unsupportedFileType", "type", ext))
}
}
@@ -57,22 +57,22 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
fName := makeFilename(file.Filename)
// If the filename already exists in the DB, make it unique by adding a random suffix.
- if _, err := h.app.core.GetMedia(0, "", fName, h.app.media); err == nil {
+ if _, err := a.core.GetMedia(0, "", fName, a.media); err == nil {
suffix, err := generateRandomString(6)
if err != nil {
- h.app.log.Printf("error generating random string: %v", err)
- return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("globals.messages.internalError"))
+ a.log.Printf("error generating random string: %v", err)
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
}
fName = appendSuffixToFilename(fName, suffix)
}
// Upload the file to the media store.
- fName, err = h.app.media.Put(fName, contentType, src)
+ fName, err = a.media.Put(fName, contentType, src)
if err != nil {
- h.app.log.Printf("error uploading file: %v", err)
+ a.log.Printf("error uploading file: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("media.errorUploading", "error", err.Error()))
+ a.i18n.Ts("media.errorUploading", "error", err.Error()))
}
// This keeps track of whether the file has to be deleted from the DB and the store
@@ -83,10 +83,10 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
)
defer func() {
if cleanUp {
- h.app.media.Delete(fName)
+ a.media.Delete(fName)
if thumbfName != "" {
- h.app.media.Delete(thumbfName)
+ a.media.Delete(thumbfName)
}
}
}()
@@ -100,20 +100,20 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
thumbFile, wi, he, err := processImage(file)
if err != nil {
cleanUp = true
- h.app.log.Printf("error resizing image: %v", err)
+ a.log.Printf("error resizing image: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("media.errorResizing", "error", err.Error()))
+ a.i18n.Ts("media.errorResizing", "error", err.Error()))
}
width = wi
height = he
// Upload thumbnail.
- tf, err := h.app.media.Put(thumbPrefix+fName, contentType, thumbFile)
+ tf, err := a.media.Put(thumbPrefix+fName, contentType, thumbFile)
if err != nil {
cleanUp = true
- h.app.log.Printf("error saving thumbnail: %v", err)
+ a.log.Printf("error saving thumbnail: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("media.errorSavingThumbnail", "error", err.Error()))
+ a.i18n.Ts("media.errorSavingThumbnail", "error", err.Error()))
}
thumbfName = tf
}
@@ -131,7 +131,7 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
}
// Insert the media into the DB.
- m, err := h.app.core.InsertMedia(fName, thumbfName, contentType, meta, h.app.constants.MediaUpload.Provider, h.app.media)
+ m, err := a.core.InsertMedia(fName, thumbfName, contentType, meta, a.constants.MediaUpload.Provider, a.media)
if err != nil {
cleanUp = true
return err
@@ -141,11 +141,11 @@ func (h *Handlers) UploadMedia(c echo.Context) error {
}
// GetMedia handles retrieval of uploaded media.
-func (h *Handlers) GetMedia(c echo.Context) error {
+func (a *App) GetMedia(c echo.Context) error {
// Fetch one media item from the DB.
id, _ := strconv.Atoi(c.Param("id"))
if id > 0 {
- out, err := h.app.core.GetMedia(id, "", "", h.app.media)
+ out, err := a.core.GetMedia(id, "", "", a.media)
if err != nil {
return err
}
@@ -155,10 +155,10 @@ func (h *Handlers) GetMedia(c echo.Context) error {
// Get the media from the DB.
var (
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
query = c.FormValue("query")
)
- res, total, err := h.app.core.QueryMedia(h.app.constants.MediaUpload.Provider, h.app.media, query, pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryMedia(a.constants.MediaUpload.Provider, a.media, query, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -174,21 +174,21 @@ func (h *Handlers) GetMedia(c echo.Context) error {
}
// DeleteMedia handles deletion of uploaded media.
-func (h *Handlers) DeleteMedia(c echo.Context) error {
+func (a *App) DeleteMedia(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Delete the media from the DB. The query returns the filename.
- fname, err := h.app.core.DeleteMedia(id)
+ fname, err := a.core.DeleteMedia(id)
if err != nil {
return err
}
// Delete the files from the media store.
- h.app.media.Delete(fname)
- h.app.media.Delete(thumbPrefix + fname)
+ a.media.Delete(fname)
+ a.media.Delete(thumbPrefix + fname)
return c.JSON(http.StatusOK, okResp{true})
}
diff --git a/cmd/public.go b/cmd/public.go
index ba43aa06..0863184e 100644
--- a/cmd/public.go
+++ b/cmd/public.go
@@ -113,11 +113,11 @@ func (t *tplRenderer) Render(w io.Writer, name string, data any, c echo.Context)
// GetPublicLists returns the list of public lists with minimal fields
// required to submit a subscription.
-func (h *Handlers) GetPublicLists(c echo.Context) error {
+func (a *App) GetPublicLists(c echo.Context) error {
// Get all public lists.
- lists, err := h.app.core.GetLists(models.ListTypePublic, true, nil)
+ lists, err := a.core.GetLists(models.ListTypePublic, true, nil)
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.errorFetchingLists"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.errorFetchingLists"))
}
type list struct {
@@ -138,48 +138,48 @@ func (h *Handlers) GetPublicLists(c echo.Context) error {
// ViewCampaignMessage renders the HTML view of a campaign message.
// This is the view the {{ MessageURL }} template tag links to in e-mail campaigns.
-func (h *Handlers) ViewCampaignMessage(c echo.Context) error {
+func (a *App) ViewCampaignMessage(c echo.Context) error {
// Get the campaign.
campUUID := c.Param("campUUID")
- camp, err := h.app.core.GetCampaign(0, campUUID, "")
+ camp, err := a.core.GetCampaign(0, campUUID, "")
if err != nil {
if er, ok := err.(*echo.HTTPError); ok {
if er.Code == http.StatusBadRequest {
return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.notFoundTitle"), "", h.app.i18n.T("public.campaignNotFound")))
+ makeMsgTpl(a.i18n.T("public.notFoundTitle"), "", a.i18n.T("public.campaignNotFound")))
}
}
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
// Get the subscriber.
subUUID := c.Param("subUUID")
- sub, err := h.app.core.GetSubscriber(0, subUUID, "")
+ sub, err := a.core.GetSubscriber(0, subUUID, "")
if err != nil {
if err == sql.ErrNoRows {
return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.notFoundTitle"), "", h.app.i18n.T("public.errorFetchingEmail")))
+ makeMsgTpl(a.i18n.T("public.notFoundTitle"), "", a.i18n.T("public.errorFetchingEmail")))
}
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
// Compile the template.
- if err := camp.CompileTemplate(h.app.manager.TemplateFuncs(&camp)); err != nil {
- h.app.log.Printf("error compiling template: %v", err)
+ if err := camp.CompileTemplate(a.manager.TemplateFuncs(&camp)); err != nil {
+ a.log.Printf("error compiling template: %v", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
// Render the message body.
- msg, err := h.app.manager.NewCampaignMessage(&camp, sub)
+ msg, err := a.manager.NewCampaignMessage(&camp, sub)
if err != nil {
- h.app.log.Printf("error rendering message: %v", err)
+ a.log.Printf("error rendering message: %v", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingCampaign")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
return c.HTML(http.StatusOK, string(msg.Body()))
@@ -187,43 +187,43 @@ func (h *Handlers) ViewCampaignMessage(c echo.Context) error {
// SubscriptionPage renders the subscription management page and handles unsubscriptions.
// This is the view that {{ UnsubscribeURL }} in campaigns link to.
-func (h *Handlers) SubscriptionPage(c echo.Context) error {
+func (a *App) SubscriptionPage(c echo.Context) error {
var (
subUUID = c.Param("subUUID")
showManage, _ = strconv.ParseBool(c.FormValue("manage"))
)
// Get the subscriber from the DB.
- s, err := h.app.core.GetSubscriber(0, subUUID, "")
+ s, err := a.core.GetSubscriber(0, subUUID, "")
if err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
// Prepare the public template.
out := unsubTpl{
Subscriber: s,
SubUUID: subUUID,
- publicTpl: publicTpl{Title: h.app.i18n.T("public.unsubscribeTitle")},
- AllowBlocklist: h.app.constants.Privacy.AllowBlocklist,
- AllowExport: h.app.constants.Privacy.AllowExport,
- AllowWipe: h.app.constants.Privacy.AllowWipe,
- AllowPreferences: h.app.constants.Privacy.AllowPreferences,
+ publicTpl: publicTpl{Title: a.i18n.T("public.unsubscribeTitle")},
+ AllowBlocklist: a.constants.Privacy.AllowBlocklist,
+ AllowExport: a.constants.Privacy.AllowExport,
+ AllowWipe: a.constants.Privacy.AllowWipe,
+ AllowPreferences: a.constants.Privacy.AllowPreferences,
}
// If the subscriber is blocklisted, throw an error.
if s.Status == models.SubscriberStatusBlockListed {
- return c.Render(http.StatusOK, tplMessage, makeMsgTpl(h.app.i18n.T("public.noSubTitle"), "", h.app.i18n.Ts("public.blocklisted")))
+ return c.Render(http.StatusOK, tplMessage, makeMsgTpl(a.i18n.T("public.noSubTitle"), "", a.i18n.Ts("public.blocklisted")))
}
// Only show preference management if it's enabled in settings.
- if h.app.constants.Privacy.AllowPreferences {
+ if a.constants.Privacy.AllowPreferences {
out.ShowManage = showManage
// Get the subscriber's lists from the DB to render in the template.
- subs, err := h.app.core.GetSubscriptions(0, subUUID, false)
+ subs, err := a.core.GetSubscriptions(0, subUUID, false)
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.errorFetchingLists"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.errorFetchingLists"))
}
out.Subscriptions = make([]models.Subscription, 0, len(subs))
@@ -243,7 +243,7 @@ func (h *Handlers) SubscriptionPage(c echo.Context) error {
// SubscriptionPrefs renders the subscription management page and
// s unsubscriptions. This is the view that {{ UnsubscribeURL }} in
// campaigns link to.
-func (h *Handlers) SubscriptionPrefs(c echo.Context) error {
+func (a *App) SubscriptionPrefs(c echo.Context) error {
// Read the form.
var req struct {
Name string `form:"name" json:"name"`
@@ -253,51 +253,51 @@ func (h *Handlers) SubscriptionPrefs(c echo.Context) error {
}
if err := c.Bind(&req); err != nil {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("globals.messages.invalidData")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("globals.messages.invalidData")))
}
// Simple unsubscribe.
var (
campUUID = c.Param("campUUID")
subUUID = c.Param("subUUID")
- blocklist = h.app.constants.Privacy.AllowBlocklist && req.Blocklist
+ blocklist = a.constants.Privacy.AllowBlocklist && req.Blocklist
)
if !req.Manage || blocklist {
- if err := h.app.core.UnsubscribeByCampaign(subUUID, campUUID, blocklist); err != nil {
+ if err := a.core.UnsubscribeByCampaign(subUUID, campUUID, blocklist); err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("public.errorProcessingRequest")))
}
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.unsubbedTitle"), "", h.app.i18n.T("public.unsubbedInfo")))
+ makeMsgTpl(a.i18n.T("public.unsubbedTitle"), "", a.i18n.T("public.unsubbedInfo")))
}
// Is preference management enabled?
- if !h.app.constants.Privacy.AllowPreferences {
+ if !a.constants.Privacy.AllowPreferences {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("public.invalidFeature")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("public.invalidFeature")))
}
// Manage preferences.
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" || len(req.Name) > 256 {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("subscribers.invalidName")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("subscribers.invalidName")))
}
// Get the subscriber from the DB.
- sub, err := h.app.core.GetSubscriber(0, subUUID, "")
+ sub, err := a.core.GetSubscriber(0, subUUID, "")
if err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("globals.messages.pFound",
- "name", h.app.i18n.T("globals.terms.subscriber"))))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("globals.messages.pFound",
+ "name", a.i18n.T("globals.terms.subscriber"))))
}
sub.Name = req.Name
// Update the subscriber properties in the DB.
- if _, err := h.app.core.UpdateSubscriber(sub.ID, sub); err != nil {
+ if _, err := a.core.UpdateSubscriber(sub.ID, sub); err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("public.errorProcessingRequest")))
}
// Get the subscriber's lists and whatever is not sent in the request (unchecked),
@@ -308,9 +308,9 @@ func (h *Handlers) SubscriptionPrefs(c echo.Context) error {
}
// Get subscription from teh DB.
- subs, err := h.app.core.GetSubscriptions(0, subUUID, false)
+ subs, err := a.core.GetSubscriptions(0, subUUID, false)
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.errorFetchingLists"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.errorFetchingLists"))
}
// Filter the lists in the request against the subscriptions in the DB.
@@ -325,20 +325,20 @@ func (h *Handlers) SubscriptionPrefs(c echo.Context) error {
}
// Unsubscribe from lists.
- if err := h.app.core.UnsubscribeLists([]int{sub.ID}, nil, unsubUUIDs); err != nil {
+ if err := a.core.UnsubscribeLists([]int{sub.ID}, nil, unsubUUIDs); err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("public.errorProcessingRequest")))
}
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("globals.messages.done"), "", h.app.i18n.T("public.prefsSaved")))
+ makeMsgTpl(a.i18n.T("globals.messages.done"), "", a.i18n.T("public.prefsSaved")))
}
// OptinPage renders the double opt-in confirmation page that subscribers
// see when they click on the "Confirm subscription" button in double-optin
// notifications.
-func (h *Handlers) OptinPage(c echo.Context) error {
+func (a *App) OptinPage(c echo.Context) error {
var (
subUUID = c.Param("subUUID")
confirm, _ = strconv.ParseBool(c.FormValue("confirm"))
@@ -353,28 +353,28 @@ func (h *Handlers) OptinPage(c echo.Context) error {
for _, l := range req.ListUUIDs {
if !reUUID.MatchString(l) {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("globals.messages.invalidUUID")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("globals.messages.invalidUUID")))
}
}
}
// Get the list of subscription lists where the subscriber hasn't confirmed.
- lists, err := h.app.core.GetSubscriberLists(0, subUUID, nil, req.ListUUIDs, models.SubscriptionStatusUnconfirmed, "")
+ lists, err := a.core.GetSubscriberLists(0, subUUID, nil, req.ListUUIDs, models.SubscriptionStatusUnconfirmed, "")
if err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingLists")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingLists")))
}
// There are no lists to confirm.
if len(lists) == 0 {
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.noSubTitle"), "", h.app.i18n.Ts("public.noSubInfo")))
+ makeMsgTpl(a.i18n.T("public.noSubTitle"), "", a.i18n.Ts("public.noSubInfo")))
}
// Confirm.
if confirm {
meta := models.JSON{}
- if h.app.constants.Privacy.RecordOptinIP {
+ if a.constants.Privacy.RecordOptinIP {
if h := c.Request().Header.Get("X-Forwarded-For"); h != "" {
meta["optin_ip"] = h
} else if h := c.Request().RemoteAddr; h != "" {
@@ -383,52 +383,52 @@ func (h *Handlers) OptinPage(c echo.Context) error {
}
// Confirm subscriptions in the DB.
- if err := h.app.core.ConfirmOptionSubscription(subUUID, req.ListUUIDs, meta); err != nil {
- h.app.log.Printf("error unsubscribing: %v", err)
+ if err := a.core.ConfirmOptionSubscription(subUUID, req.ListUUIDs, meta); err != nil {
+ a.log.Printf("error unsubscribing: %v", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.subConfirmedTitle"), "", h.app.i18n.Ts("public.subConfirmed")))
+ makeMsgTpl(a.i18n.T("public.subConfirmedTitle"), "", a.i18n.Ts("public.subConfirmed")))
}
var out optinTpl
out.Lists = lists
out.SubUUID = subUUID
- out.Title = h.app.i18n.T("public.confirmOptinSubTitle")
+ out.Title = a.i18n.T("public.confirmOptinSubTitle")
return c.Render(http.StatusOK, "optin", out)
}
// SubscriptionFormPage handles subscription requests coming from public
// HTML subscription forms.
-func (h *Handlers) SubscriptionFormPage(c echo.Context) error {
- if !h.app.constants.EnablePublicSubPage {
+func (a *App) SubscriptionFormPage(c echo.Context) error {
+ if !a.constants.EnablePublicSubPage {
return c.Render(http.StatusNotFound, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.invalidFeature")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.invalidFeature")))
}
// Get all public lists from the DB.
- lists, err := h.app.core.GetLists(models.ListTypePublic, true, nil)
+ lists, err := a.core.GetLists(models.ListTypePublic, true, nil)
if err != nil {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorFetchingLists")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingLists")))
}
// There are no public lists available for subscription.
if len(lists) == 0 {
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.noListsAvailable")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.noListsAvailable")))
}
out := subFormTpl{}
- out.Title = h.app.i18n.T("public.sub")
+ out.Title = a.i18n.T("public.sub")
out.Lists = lists
// Captcha is enabled. Set the key for the template to render.
- if h.app.constants.Security.EnableCaptcha {
- out.CaptchaKey = h.app.constants.Security.CaptchaKey
+ if a.constants.Security.EnableCaptcha {
+ out.CaptchaKey = a.constants.Security.CaptchaKey
}
return c.Render(http.StatusOK, "subscription-form", out)
@@ -436,33 +436,33 @@ func (h *Handlers) SubscriptionFormPage(c echo.Context) error {
// SubscriptionForm handles subscription requests coming from public
// HTML subscription forms.
-func (h *Handlers) SubscriptionForm(c echo.Context) error {
+func (a *App) SubscriptionForm(c echo.Context) error {
// If there's a nonce value, a bot could've filled the form.
if c.FormValue("nonce") != "" {
- return echo.NewHTTPError(http.StatusBadGateway, h.app.i18n.T("public.invalidFeature"))
+ return echo.NewHTTPError(http.StatusBadGateway, a.i18n.T("public.invalidFeature"))
}
// Process CAPTCHA.
- if h.app.constants.Security.EnableCaptcha {
- err, ok := h.app.captcha.Verify(c.FormValue("h-captcha-response"))
+ if a.constants.Security.EnableCaptcha {
+ err, ok := a.captcha.Verify(c.FormValue("h-captcha-response"))
if err != nil {
- h.app.log.Printf("Captcha request failed: %v", err)
+ a.log.Printf("Captcha request failed: %v", err)
}
if !ok {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.T("public.invalidCaptcha")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.T("public.invalidCaptcha")))
}
}
- hasOptin, err := h.processSubForm(c)
+ hasOptin, err := a.processSubForm(c)
if err != nil {
e, ok := err.(*echo.HTTPError)
if !ok {
return e
}
- return c.Render(e.Code, tplMessage, makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", fmt.Sprintf("%s", e.Message)))
+ return c.Render(e.Code, tplMessage, makeMsgTpl(a.i18n.T("public.errorTitle"), "", fmt.Sprintf("%s", e.Message)))
}
// If there were double optin lists, show the opt-in pending message instead of
@@ -472,17 +472,17 @@ func (h *Handlers) SubscriptionForm(c echo.Context) error {
msg = "public.subOptinPending"
}
- return c.Render(http.StatusOK, tplMessage, makeMsgTpl(h.app.i18n.T("public.subTitle"), "", h.app.i18n.Ts(msg)))
+ return c.Render(http.StatusOK, tplMessage, makeMsgTpl(a.i18n.T("public.subTitle"), "", a.i18n.Ts(msg)))
}
// PublicSubscription handles subscription requests coming from public
// API calls.
-func (h *Handlers) PublicSubscription(c echo.Context) error {
- if !h.app.constants.EnablePublicSubPage {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.invalidFeature"))
+func (a *App) PublicSubscription(c echo.Context) error {
+ if !a.constants.EnablePublicSubPage {
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.invalidFeature"))
}
- hasOptin, err := h.processSubForm(c)
+ hasOptin, err := a.processSubForm(c)
if err != nil {
return err
}
@@ -495,10 +495,10 @@ func (h *Handlers) PublicSubscription(c echo.Context) error {
// LinkRedirect redirects a link UUID to its original underlying link
// after recording the link click for a particular subscriber in the particular
// campaign. These links are generated by {{ TrackLink }} tags in campaigns.
-func (h *Handlers) LinkRedirect(c echo.Context) error {
+func (a *App) LinkRedirect(c echo.Context) error {
// If individual tracking is disabled, do not record the subscriber ID.
subUUID := c.Param("subUUID")
- if !h.app.constants.Privacy.IndividualTracking {
+ if !a.constants.Privacy.IndividualTracking {
subUUID = ""
}
@@ -507,10 +507,10 @@ func (h *Handlers) LinkRedirect(c echo.Context) error {
linkUUID = c.Param("linkUUID")
campUUID = c.Param("campUUID")
)
- url, err := h.app.core.RegisterCampaignLinkClick(linkUUID, campUUID, subUUID)
+ url, err := a.core.RegisterCampaignLinkClick(linkUUID, campUUID, subUUID)
if err != nil {
e := err.(*echo.HTTPError)
- return c.Render(e.Code, tplMessage, makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", e.Error()))
+ return c.Render(e.Code, tplMessage, makeMsgTpl(a.i18n.T("public.errorTitle"), "", e.Error()))
}
return c.Redirect(http.StatusTemporaryRedirect, url)
@@ -520,18 +520,18 @@ func (h *Handlers) LinkRedirect(c echo.Context) error {
// the form of an pixel image request. Regardless of errors, this handler
// should always render the pixel image bytes. The pixel URL is generated by
// the {{ TrackView }} template tag in campaigns.
-func (h *Handlers) RegisterCampaignView(c echo.Context) error {
+func (a *App) RegisterCampaignView(c echo.Context) error {
// If individual tracking is disabled, do not record the subscriber ID.
subUUID := c.Param("subUUID")
- if !h.app.constants.Privacy.IndividualTracking {
+ if !a.constants.Privacy.IndividualTracking {
subUUID = ""
}
// Exclude dummy hits from template previews.
campUUID := c.Param("campUUID")
if campUUID != dummyUUID && subUUID != dummyUUID {
- if err := h.app.core.RegisterCampaignView(campUUID, subUUID); err != nil {
- h.app.log.Printf("error registering campaign view: %s", err)
+ if err := a.core.RegisterCampaignView(campUUID, subUUID); err != nil {
+ a.log.Printf("error registering campaign view: %s", err)
}
}
@@ -543,38 +543,38 @@ func (h *Handlers) RegisterCampaignView(c echo.Context) error {
// campaign views and clicks and produces a JSON report that is then e-mailed
// to the subscriber. This is a privacy feature and the data that's exported
// is dependent on the configuration.
-func (h *Handlers) SelfExportSubscriberData(c echo.Context) error {
+func (a *App) SelfExportSubscriberData(c echo.Context) error {
// Is export allowed?
- if !h.app.constants.Privacy.AllowExport {
+ if !a.constants.Privacy.AllowExport {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.invalidFeature")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.invalidFeature")))
}
// Get the subscriber's data. A single query that gets the profile,
// list subscriptions, campaign views, and link clicks. Names of
// private lists are replaced with "Private list".
subUUID := c.Param("subUUID")
- data, b, err := h.exportSubscriberData(0, subUUID, h.app.constants.Privacy.Exportable)
+ data, b, err := a.exportSubscriberData(0, subUUID, a.constants.Privacy.Exportable)
if err != nil {
- h.app.log.Printf("error exporting subscriber data: %s", err)
+ a.log.Printf("error exporting subscriber data: %s", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
// Prepare the attachment e-mail.
var msg bytes.Buffer
- if err := h.app.notifs.Tpls.ExecuteTemplate(&msg, notifSubscriberData, data); err != nil {
- h.app.log.Printf("error compiling notification template '%s': %v", notifSubscriberData, err)
+ if err := a.notifs.Tpls.ExecuteTemplate(&msg, notifSubscriberData, data); err != nil {
+ a.log.Printf("error compiling notification template '%s': %v", notifSubscriberData, err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
- subject, body := getTplSubject(h.app.i18n.Ts("email.data.title"), msg.Bytes())
+ subject, body := getTplSubject(a.i18n.Ts("email.data.title"), msg.Bytes())
// E-mail the data as a JSON attachment to the subscriber.
const fname = "data.json"
- if err := h.app.emailMessenger.Push(models.Message{
- From: h.app.constants.FromEmail,
+ if err := a.emailMessenger.Push(models.Message{
+ From: a.constants.FromEmail,
To: []string{data.Email},
Subject: subject,
Body: body,
@@ -586,34 +586,34 @@ func (h *Handlers) SelfExportSubscriberData(c echo.Context) error {
},
},
}); err != nil {
- h.app.log.Printf("error e-mailing subscriber profile: %s", err)
+ a.log.Printf("error e-mailing subscriber profile: %s", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.dataSentTitle"), "", h.app.i18n.T("public.dataSent")))
+ makeMsgTpl(a.i18n.T("public.dataSentTitle"), "", a.i18n.T("public.dataSent")))
}
// WipeSubscriberData allows a subscriber to delete their data. The
// profile and subscriptions are deleted, while the campaign_views and link
// clicks remain as orphan data unconnected to any subscriber.
-func (h *Handlers) WipeSubscriberData(c echo.Context) error {
+func (a *App) WipeSubscriberData(c echo.Context) error {
// Is wiping allowed?
- if !h.app.constants.Privacy.AllowWipe {
+ if !a.constants.Privacy.AllowWipe {
return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.invalidFeature")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.invalidFeature")))
}
subUUID := c.Param("subUUID")
- if err := h.app.core.DeleteSubscribers(nil, []string{subUUID}); err != nil {
- h.app.log.Printf("error wiping subscriber data: %s", err)
+ if err := a.core.DeleteSubscribers(nil, []string{subUUID}); err != nil {
+ a.log.Printf("error wiping subscriber data: %s", err)
return c.Render(http.StatusInternalServerError, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))
+ makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorProcessingRequest")))
}
return c.Render(http.StatusOK, tplMessage,
- makeMsgTpl(h.app.i18n.T("public.dataRemovedTitle"), "", h.app.i18n.T("public.dataRemoved")))
+ makeMsgTpl(a.i18n.T("public.dataRemovedTitle"), "", a.i18n.T("public.dataRemoved")))
}
// drawTransparentImage draws a transparent PNG of given dimensions
@@ -631,7 +631,7 @@ func drawTransparentImage(h, w int) []byte {
// processSubForm processes an incoming form/public API subscription request.
// The bool indicates whether there was subscription to an optin list so that
// an appropriate message can be shown.
-func (h *Handlers) processSubForm(c echo.Context) (bool, error) {
+func (a *App) processSubForm(c echo.Context) (bool, error) {
// Get and validate fields.
var req struct {
Name string `form:"name" json:"name"`
@@ -643,7 +643,7 @@ func (h *Handlers) processSubForm(c echo.Context) (bool, error) {
}
if len(req.FormListUUIDs) == 0 {
- return false, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("public.noListsSelected"))
+ return false, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("public.noListsSelected"))
}
// If there's no name, use the name bit from the e-mail.
@@ -654,10 +654,10 @@ func (h *Handlers) processSubForm(c echo.Context) (bool, error) {
// Validate fields.
if len(req.Email) > 1000 {
- return false, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.invalidEmail"))
+ return false, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.invalidEmail"))
}
- em, err := h.app.importer.SanitizeEmail(req.Email)
+ em, err := a.importer.SanitizeEmail(req.Email)
if err != nil {
return false, echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
@@ -665,25 +665,25 @@ func (h *Handlers) processSubForm(c echo.Context) (bool, error) {
req.Name = strings.TrimSpace(req.Name)
if len(req.Name) == 0 || len(req.Name) > stdInputMaxLen {
- return false, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.invalidName"))
+ return false, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.invalidName"))
}
listUUIDs := pq.StringArray(req.FormListUUIDs)
// Fetch the list types and ensure that they are not private.
- listTypes, err := h.app.core.GetListTypes(nil, req.FormListUUIDs)
+ listTypes, err := a.core.GetListTypes(nil, req.FormListUUIDs)
if err != nil {
return false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("%s", err.(*echo.HTTPError).Message))
}
for _, t := range listTypes {
if t == models.ListTypePrivate {
- return false, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidUUID"))
+ return false, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidUUID"))
}
}
// Insert the subscriber into the DB.
- _, hasOptin, err := h.app.core.InsertSubscriber(models.Subscriber{
+ _, hasOptin, err := a.core.InsertSubscriber(models.Subscriber{
Name: req.Name,
Email: req.Email,
Status: models.SubscriberStatusEnabled,
@@ -692,13 +692,13 @@ func (h *Handlers) processSubForm(c echo.Context) (bool, error) {
// Subscriber already exists. Update subscriptions in the DB.
if e, ok := err.(*echo.HTTPError); ok && e.Code == http.StatusConflict {
// Get the subscriber from the DB by their email.
- sub, err := h.app.core.GetSubscriber(0, "", req.Email)
+ sub, err := a.core.GetSubscriber(0, "", req.Email)
if err != nil {
return false, err
}
// Update the subscriber's subscriptions in the DB.
- _, hasOptin, err := h.app.core.UpdateSubscriberWithLists(sub.ID, sub, nil, listUUIDs, false, false)
+ _, hasOptin, err := a.core.UpdateSubscriberWithLists(sub.ID, sub, nil, listUUIDs, false, false)
if err != nil {
return false, err
}
diff --git a/cmd/roles.go b/cmd/roles.go
index 3812620d..6e191866 100644
--- a/cmd/roles.go
+++ b/cmd/roles.go
@@ -11,9 +11,9 @@ import (
)
// GetUserRoles retrieves roles.
-func (h *Handlers) GetUserRoles(c echo.Context) error {
+func (a *App) GetUserRoles(c echo.Context) error {
// Get all roles.
- out, err := h.app.core.GetRoles()
+ out, err := a.core.GetRoles()
if err != nil {
return err
}
@@ -22,9 +22,9 @@ func (h *Handlers) GetUserRoles(c echo.Context) error {
}
// GeListRoles retrieves roles.
-func (h *Handlers) GeListRoles(c echo.Context) error {
+func (a *App) GeListRoles(c echo.Context) error {
// Get all roles.
- out, err := h.app.core.GetListRoles()
+ out, err := a.core.GetListRoles()
if err != nil {
return err
}
@@ -33,17 +33,17 @@ func (h *Handlers) GeListRoles(c echo.Context) error {
}
// CreateUserRole handles role creation.
-func (h *Handlers) CreateUserRole(c echo.Context) error {
+func (a *App) CreateUserRole(c echo.Context) error {
var r auth.Role
if err := c.Bind(&r); err != nil {
return err
}
- if err := h.validateUserRole(r); err != nil {
+ if err := a.validateUserRole(r); err != nil {
return err
}
// Create the role in the DB.
- out, err := h.app.core.CreateRole(r)
+ out, err := a.core.CreateRole(r)
if err != nil {
return err
}
@@ -52,17 +52,17 @@ func (h *Handlers) CreateUserRole(c echo.Context) error {
}
// CreateListRole handles role creation.
-func (h *Handlers) CreateListRole(c echo.Context) error {
+func (a *App) CreateListRole(c echo.Context) error {
var r auth.ListRole
if err := c.Bind(&r); err != nil {
return err
}
- if err := h.validateListRole(r); err != nil {
+ if err := a.validateListRole(r); err != nil {
return err
}
// Create the role in the DB.
- out, err := h.app.core.CreateListRole(r)
+ out, err := a.core.CreateListRole(r)
if err != nil {
return err
}
@@ -71,11 +71,11 @@ func (h *Handlers) CreateListRole(c echo.Context) error {
}
// UpdateUserRole handles role modification.
-func (h *Handlers) UpdateUserRole(c echo.Context) error {
+func (a *App) UpdateUserRole(c echo.Context) error {
// ID 1 is reserved for the Super Admin role and anything below that is invalid.
id, _ := strconv.Atoi(c.Param("id"))
if id < 2 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Incoming params.
@@ -83,7 +83,7 @@ func (h *Handlers) UpdateUserRole(c echo.Context) error {
if err := c.Bind(&r); err != nil {
return err
}
- if err := h.validateUserRole(r); err != nil {
+ if err := a.validateUserRole(r); err != nil {
return err
}
@@ -91,13 +91,13 @@ func (h *Handlers) UpdateUserRole(c echo.Context) error {
r.Name.String = strings.TrimSpace(r.Name.String)
// Update the role in the DB.
- out, err := h.app.core.UpdateUserRole(id, r)
+ out, err := a.core.UpdateUserRole(id, r)
if err != nil {
return err
}
// Cache API tokens for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
@@ -105,11 +105,11 @@ func (h *Handlers) UpdateUserRole(c echo.Context) error {
}
// UpdateListRole handles role modification.
-func (h *Handlers) UpdateListRole(c echo.Context) error {
+func (a *App) UpdateListRole(c echo.Context) error {
// ID 1 is reserved for the Super Admin role and anything below that is invalid.
id, _ := strconv.Atoi(c.Param("id"))
if id < 2 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Incoming params.
@@ -118,7 +118,7 @@ func (h *Handlers) UpdateListRole(c echo.Context) error {
return err
}
- if err := h.validateListRole(r); err != nil {
+ if err := a.validateListRole(r); err != nil {
return err
}
@@ -126,13 +126,13 @@ func (h *Handlers) UpdateListRole(c echo.Context) error {
r.Name.String = strings.TrimSpace(r.Name.String)
// Update the role in the DB.
- out, err := h.app.core.UpdateListRole(id, r)
+ out, err := a.core.UpdateListRole(id, r)
if err != nil {
return err
}
// Cache API tokens for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
@@ -140,48 +140,48 @@ func (h *Handlers) UpdateListRole(c echo.Context) error {
}
// DeleteRole handles role deletion.
-func (h *Handlers) DeleteRole(c echo.Context) error {
+func (a *App) DeleteRole(c echo.Context) error {
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
if id < 2 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Delete the role from the DB.
- if err := h.app.core.DeleteRole(int(id)); err != nil {
+ if err := a.core.DeleteRole(int(id)); err != nil {
return err
}
// Cache API tokens for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
return c.JSON(http.StatusOK, okResp{true})
}
-func (h *Handlers) validateUserRole(r auth.Role) error {
+func (a *App) validateUserRole(r auth.Role) error {
if !strHasLen(r.Name.String, 1, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "name"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "name"))
}
for _, p := range r.Permissions {
- if _, ok := h.app.constants.Permissions[p]; !ok {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("permission: %s", p)))
+ if _, ok := a.constants.Permissions[p]; !ok {
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("permission: %s", p)))
}
}
return nil
}
-func (h *Handlers) validateListRole(r auth.ListRole) error {
+func (a *App) validateListRole(r auth.ListRole) error {
if !strHasLen(r.Name.String, 1, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "name"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "name"))
}
for _, l := range r.Lists {
for _, p := range l.Permissions {
if p != auth.PermListGet && p != auth.PermListManage {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("list permission: %s", p)))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("list permission: %s", p)))
}
}
}
diff --git a/cmd/settings.go b/cmd/settings.go
index 62741111..66823a59 100644
--- a/cmd/settings.go
+++ b/cmd/settings.go
@@ -51,8 +51,8 @@ var (
)
// GetSettings returns settings from the DB.
-func (h *Handlers) GetSettings(c echo.Context) error {
- s, err := h.app.core.GetSettings()
+func (a *App) GetSettings(c echo.Context) error {
+ s, err := a.core.GetSettings()
if err != nil {
return err
}
@@ -79,7 +79,7 @@ func (h *Handlers) GetSettings(c echo.Context) error {
}
// UpdateSettings returns settings from the DB.
-func (h *Handlers) UpdateSettings(c echo.Context) error {
+func (a *App) UpdateSettings(c echo.Context) error {
// Unmarshal and marshal the fields once to sanitize the settings blob.
var set models.Settings
if err := c.Bind(&set); err != nil {
@@ -87,7 +87,7 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
}
// Get the existing settings.
- cur, err := h.app.core.GetSettings()
+ cur, err := a.core.GetSettings()
if err != nil {
return err
}
@@ -113,7 +113,7 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
if _, ok := names[name]; ok {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("settings.duplicateMessengerName", "name", name))
+ a.i18n.Ts("settings.duplicateMessengerName", "name", name))
}
names[name] = true
@@ -143,7 +143,7 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
}
}
if !has {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("settings.errorNoSMTP"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("settings.errorNoSMTP"))
}
// Always remove the trailing slash from the app root URL.
@@ -164,7 +164,7 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
set.BounceBoxes[i].Host = strings.TrimSpace(s.Host)
if d, _ := time.ParseDuration(s.ScanInterval); d.Minutes() < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("settings.bounces.invalidScanInterval"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("settings.bounces.invalidScanInterval"))
}
// If there's no password coming in from the frontend, copy the existing
@@ -195,10 +195,10 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
name := reAlphaNum.ReplaceAllString(strings.ToLower(m.Name), "")
if _, ok := names[name]; ok {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("settings.duplicateMessengerName", "name", name))
+ a.i18n.Ts("settings.duplicateMessengerName", "name", name))
}
if len(name) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("settings.invalidMessengerName"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("settings.invalidMessengerName"))
}
set.Messengers[i].Name = name
@@ -249,66 +249,66 @@ func (h *Handlers) UpdateSettings(c echo.Context) error {
// Validate slow query caching cron.
if set.CacheSlowQueries {
if _, err := cron.ParseStandard(set.CacheSlowQueriesInterval); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidData")+": slow query cron: "+err.Error())
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidData")+": slow query cron: "+err.Error())
}
}
// Update the settings in the DB.
- if err := h.app.core.UpdateSettings(set); err != nil {
+ if err := a.core.UpdateSettings(set); err != nil {
return err
}
// If there are any active campaigns, don't do an auto reload and
// warn the user on the frontend.
- if h.app.manager.HasRunningCampaigns() {
- h.app.Lock()
- h.app.needsRestart = true
- h.app.Unlock()
+ if a.manager.HasRunningCampaigns() {
+ a.Lock()
+ a.needsRestart = true
+ a.Unlock()
return c.JSON(http.StatusOK, okResp{struct {
NeedsRestart bool `json:"needs_restart"`
}{true}})
}
- // No running campaigns. Reload the h.app.
+ // No running campaigns. Reload the a.
go func() {
<-time.After(time.Millisecond * 500)
- h.app.chReload <- syscall.SIGHUP
+ a.chReload <- syscall.SIGHUP
}()
return c.JSON(http.StatusOK, okResp{true})
}
// GetLogs returns the log entries stored in the log buffer.
-func (h *Handlers) GetLogs(c echo.Context) error {
- return c.JSON(http.StatusOK, okResp{h.app.bufLog.Lines()})
+func (a *App) GetLogs(c echo.Context) error {
+ return c.JSON(http.StatusOK, okResp{a.bufLog.Lines()})
}
// TestSMTPSettings returns the log entries stored in the log buffer.
-func (h *Handlers) TestSMTPSettings(c echo.Context) error {
+func (a *App) TestSMTPSettings(c echo.Context) error {
// Copy the raw JSON post body.
reqBody, err := io.ReadAll(c.Request().Body)
if err != nil {
- h.app.log.Printf("error reading SMTP test: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.internalError"))
+ a.log.Printf("error reading SMTP test: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.internalError"))
}
// Load the JSON into koanf to parse SMTP settings properly including timestrings.
ko := koanf.New(".")
if err := ko.Load(rawbytes.Provider(reqBody), json.Parser()); err != nil {
- h.app.log.Printf("error unmarshalling SMTP test request: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.internalError"))
+ a.log.Printf("error unmarshalling SMTP test request: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.internalError"))
}
req := email.Server{}
if err := ko.UnmarshalWithConf("", &req, koanf.UnmarshalConf{Tag: "json"}); err != nil {
- h.app.log.Printf("error scanning SMTP test request: %v", err)
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.internalError"))
+ a.log.Printf("error scanning SMTP test request: %v", err)
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.internalError"))
}
to := ko.String("email")
if to == "" {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.missingFields", "name", "email"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.missingFields", "name", "email"))
}
// Initialize a new SMTP pool.
@@ -318,33 +318,33 @@ func (h *Handlers) TestSMTPSettings(c echo.Context) error {
msgr, err := email.New("", req)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorCreating", "name", "SMTP", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorCreating", "name", "SMTP", "error", err.Error()))
}
// Render the test email template body.
var b bytes.Buffer
- if err := h.app.notifs.Tpls.ExecuteTemplate(&b, "smtp-test", nil); err != nil {
- h.app.log.Printf("error compiling notification template '%s': %v", "smtp-test", err)
+ if err := a.notifs.Tpls.ExecuteTemplate(&b, "smtp-test", nil); err != nil {
+ a.log.Printf("error compiling notification template '%s': %v", "smtp-test", err)
return err
}
m := models.Message{}
- m.From = h.app.constants.FromEmail
+ m.From = a.constants.FromEmail
m.To = []string{to}
- m.Subject = h.app.i18n.T("settings.smtp.testConnection")
+ m.Subject = a.i18n.T("settings.smtp.testConnection")
m.Body = b.Bytes()
if err := msgr.Push(m); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
- return c.JSON(http.StatusOK, okResp{h.app.bufLog.Lines()})
+ return c.JSON(http.StatusOK, okResp{a.bufLog.Lines()})
}
-func (h *Handlers) GetAboutInfo(c echo.Context) error {
+func (a *App) GetAboutInfo(c echo.Context) error {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
- out := h.app.about
+ out := a.about
out.System.AllocMB = mem.Alloc / 1024 / 1024
out.System.OSMB = mem.Sys / 1024 / 1024
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index a5d78ae2..7ddd4ea9 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -52,22 +52,22 @@ var (
)
// GetSubscriber handles the retrieval of a single subscriber by ID.
-func (h *Handlers) GetSubscriber(c echo.Context) error {
+func (a *App) GetSubscriber(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Check if the user has access to at least one of the lists on the subscriber.
- if err := h.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, []int{id}); err != nil {
return err
}
// Fetch the subscriber from the DB.
- out, err := h.app.core.GetSubscriber(id, "", "")
+ out, err := a.core.GetSubscriber(id, "", "")
if err != nil {
return err
}
@@ -76,12 +76,12 @@ func (h *Handlers) GetSubscriber(c echo.Context) error {
}
// QuerySubscribers handles querying subscribers based on an arbitrary SQL expression.
-func (h *Handlers) QuerySubscribers(c echo.Context) error {
+func (a *App) QuerySubscribers(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
// Filter list IDs by permission.
- listIDs, err := h.filterListQueryByPerm("list_id", c.QueryParams(), user)
+ listIDs, err := a.filterListQueryByPerm("list_id", c.QueryParams(), user)
if err != nil {
return err
}
@@ -92,9 +92,9 @@ func (h *Handlers) QuerySubscribers(c echo.Context) error {
subStatus = c.FormValue("subscription_status")
orderBy = c.FormValue("order_by")
order = c.FormValue("order")
- pg = h.app.paginator.NewFromURL(c.Request().URL.Query())
+ pg = a.paginator.NewFromURL(c.Request().URL.Query())
)
- res, total, err := h.app.core.QuerySubscribers(query, listIDs, subStatus, order, orderBy, pg.Offset, pg.Limit)
+ res, total, err := a.core.QuerySubscribers(query, listIDs, subStatus, order, orderBy, pg.Offset, pg.Limit)
if err != nil {
return err
}
@@ -111,12 +111,12 @@ func (h *Handlers) QuerySubscribers(c echo.Context) error {
}
// ExportSubscribers handles querying subscribers based on an arbitrary SQL expression.
-func (h *Handlers) ExportSubscribers(c echo.Context) error {
+func (a *App) ExportSubscribers(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
// Filter list IDs by permission.
- listIDs, err := h.filterListQueryByPerm("list_id", c.QueryParams(), user)
+ listIDs, err := a.filterListQueryByPerm("list_id", c.QueryParams(), user)
if err != nil {
return err
}
@@ -124,7 +124,7 @@ func (h *Handlers) ExportSubscribers(c echo.Context) error {
// Export only specific subscriber IDs?
subIDs, err := getQueryInts("id", c.QueryParams())
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Filter by subscription status
@@ -132,7 +132,7 @@ func (h *Handlers) ExportSubscribers(c echo.Context) error {
// Get the batched export iterator.
query := sanitizeSQLExp(c.FormValue("query"))
- exp, err := h.app.core.ExportSubscribers(query, subIDs, listIDs, subStatus, h.app.constants.DBBatchSize)
+ exp, err := a.core.ExportSubscribers(query, subIDs, listIDs, subStatus, a.constants.DBBatchSize)
if err != nil {
return err
}
@@ -163,7 +163,7 @@ loop:
for _, r := range out {
if err = wr.Write([]string{r.UUID, r.Email, r.Name, r.Attribs, r.Status,
r.CreatedAt.Time.String(), r.UpdatedAt.Time.String()}); err != nil {
- h.app.log.Printf("error streaming CSV export: %v", err)
+ a.log.Printf("error streaming CSV export: %v", err)
break loop
}
}
@@ -176,7 +176,7 @@ loop:
}
// CreateSubscriber handles the creation of a new subscriber.
-func (h *Handlers) CreateSubscriber(c echo.Context) error {
+func (a *App) CreateSubscriber(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -187,7 +187,7 @@ func (h *Handlers) CreateSubscriber(c echo.Context) error {
}
// Validate fields.
- req, err := h.app.importer.ValidateFields(req)
+ req, err := a.importer.ValidateFields(req)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
@@ -196,7 +196,7 @@ func (h *Handlers) CreateSubscriber(c echo.Context) error {
listIDs := user.FilterListsByPerm(auth.PermTypeManage, req.Lists)
// Insert the subscriber into the DB.
- sub, _, err := h.app.core.InsertSubscriber(req.Subscriber, listIDs, nil, req.PreconfirmSubs)
+ sub, _, err := a.core.InsertSubscriber(req.Subscriber, listIDs, nil, req.PreconfirmSubs)
if err != nil {
return err
}
@@ -205,13 +205,13 @@ func (h *Handlers) CreateSubscriber(c echo.Context) error {
}
// UpdateSubscriber handles modification of a subscriber.
-func (h *Handlers) UpdateSubscriber(c echo.Context) error {
+func (a *App) UpdateSubscriber(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Get and validate fields.
@@ -225,21 +225,21 @@ func (h *Handlers) UpdateSubscriber(c echo.Context) error {
}
// Sanitize and validate the email field.
- if em, err := h.app.importer.SanitizeEmail(req.Email); err != nil {
+ if em, err := a.importer.SanitizeEmail(req.Email); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
} else {
req.Email = em
}
if req.Name != "" && !strHasLen(req.Name, 1, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.invalidName"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.invalidName"))
}
// Filter lists against the current user's permitted lists.
listIDs := user.FilterListsByPerm(auth.PermTypeManage, req.Lists)
// Update the subscriber in the DB.
- out, _, err := h.app.core.UpdateSubscriberWithLists(id, req.Subscriber, listIDs, nil, req.PreconfirmSubs, true)
+ out, _, err := a.core.UpdateSubscriberWithLists(id, req.Subscriber, listIDs, nil, req.PreconfirmSubs, true)
if err != nil {
return err
}
@@ -248,21 +248,21 @@ func (h *Handlers) UpdateSubscriber(c echo.Context) error {
}
// SubscriberSendOptin sends an optin confirmation e-mail to a subscriber.
-func (h *Handlers) SubscriberSendOptin(c echo.Context) error {
+func (a *App) SubscriberSendOptin(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Fetch the subscriber.
- out, err := h.app.core.GetSubscriber(id, "", "")
+ out, err := a.core.GetSubscriber(id, "", "")
if err != nil {
return err
}
// Trigger the opt-in confirmation e-mail hook.
- if _, err := h.app.optinConfirmNotify()(out, nil); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("subscribers.errorSendingOptin"))
+ if _, err := a.optinConfirmNotify()(out, nil); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("subscribers.errorSendingOptin"))
}
return c.JSON(http.StatusOK, okResp{true})
@@ -270,7 +270,7 @@ func (h *Handlers) SubscriberSendOptin(c echo.Context) error {
// BlocklistSubscribers handles the blocklisting of one or more subscribers.
// It takes either an ID in the URI, or a list of IDs in the request body.
-func (h *Handlers) BlocklistSubscribers(c echo.Context) error {
+func (a *App) BlocklistSubscribers(c echo.Context) error {
// Is it a /:id call?
var (
subIDs []int
@@ -279,7 +279,7 @@ func (h *Handlers) BlocklistSubscribers(c echo.Context) error {
if pID != "" {
id, _ := strconv.Atoi(pID)
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
subIDs = append(subIDs, id)
@@ -288,7 +288,7 @@ func (h *Handlers) BlocklistSubscribers(c echo.Context) error {
var req subQueryReq
if err := c.Bind(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
}
if len(req.SubscriberIDs) == 0 {
return echo.NewHTTPError(http.StatusBadRequest,
@@ -299,7 +299,7 @@ func (h *Handlers) BlocklistSubscribers(c echo.Context) error {
}
// Update the subscribers in the DB.
- if err := h.app.core.BlocklistSubscribers(subIDs); err != nil {
+ if err := a.core.BlocklistSubscribers(subIDs); err != nil {
return err
}
@@ -309,7 +309,7 @@ func (h *Handlers) BlocklistSubscribers(c echo.Context) error {
// ManageSubscriberLists handles bulk addition or removal of subscribers
// from or to one or more target lists.
// It takes either an ID in the URI, or a list of IDs in the request body.
-func (h *Handlers) ManageSubscriberLists(c echo.Context) error {
+func (a *App) ManageSubscriberLists(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -321,7 +321,7 @@ func (h *Handlers) ManageSubscriberLists(c echo.Context) error {
if pID != "" {
id, _ := strconv.Atoi(pID)
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
subIDs = append(subIDs, id)
}
@@ -329,16 +329,16 @@ func (h *Handlers) ManageSubscriberLists(c echo.Context) error {
var req subQueryReq
if err := c.Bind(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
}
if len(req.SubscriberIDs) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.errorNoIDs"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.errorNoIDs"))
}
if len(subIDs) == 0 {
subIDs = req.SubscriberIDs
}
if len(req.TargetListIDs) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.errorNoListsGiven"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.errorNoListsGiven"))
}
// Filter lists against the current user's permitted lists.
@@ -348,13 +348,13 @@ func (h *Handlers) ManageSubscriberLists(c echo.Context) error {
var err error
switch req.Action {
case "add":
- err = h.app.core.AddSubscriptions(subIDs, listIDs, req.Status)
+ err = a.core.AddSubscriptions(subIDs, listIDs, req.Status)
case "remove":
- err = h.app.core.DeleteSubscriptions(subIDs, listIDs)
+ err = a.core.DeleteSubscriptions(subIDs, listIDs)
case "unsubscribe":
- err = h.app.core.UnsubscribeLists(subIDs, listIDs, nil)
+ err = a.core.UnsubscribeLists(subIDs, listIDs, nil)
default:
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.invalidAction"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.invalidAction"))
}
if err != nil {
@@ -366,7 +366,7 @@ func (h *Handlers) ManageSubscriberLists(c echo.Context) error {
// DeleteSubscribers handles subscriber deletion.
// It takes either an ID in the URI, or a list of IDs in the request body.
-func (h *Handlers) DeleteSubscribers(c echo.Context) error {
+func (a *App) DeleteSubscribers(c echo.Context) error {
// Is it an /:id call?
var (
pID = c.Param("id")
@@ -375,7 +375,7 @@ func (h *Handlers) DeleteSubscribers(c echo.Context) error {
if pID != "" {
id, _ := strconv.Atoi(pID)
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
subIDs = append(subIDs, id)
} else {
@@ -383,16 +383,16 @@ func (h *Handlers) DeleteSubscribers(c echo.Context) error {
i, err := parseStringIDs(c.Request().URL.Query()["id"])
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
}
if len(i) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.errorNoIDs"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.errorNoIDs"))
}
subIDs = i
}
// Delete the subscribers from the DB.
- if err := h.app.core.DeleteSubscribers(subIDs, nil); err != nil {
+ if err := a.core.DeleteSubscribers(subIDs, nil); err != nil {
return err
}
@@ -401,7 +401,7 @@ func (h *Handlers) DeleteSubscribers(c echo.Context) error {
// DeleteSubscribersByQuery bulk deletes based on an
// arbitrary SQL expression.
-func (h *Handlers) DeleteSubscribersByQuery(c echo.Context) error {
+func (a *App) DeleteSubscribersByQuery(c echo.Context) error {
var req subQueryReq
if err := c.Bind(&req); err != nil {
return err
@@ -411,11 +411,11 @@ func (h *Handlers) DeleteSubscribersByQuery(c echo.Context) error {
// If the "all" flag is set, ignore any subquery that may be present.
req.Query = ""
} else if req.Query == "" {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "query"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "query"))
}
// Delete the subscribers from the DB.
- if err := h.app.core.DeleteSubscribersByQuery(req.Query, req.ListIDs, req.SubscriptionStatus); err != nil {
+ if err := a.core.DeleteSubscribersByQuery(req.Query, req.ListIDs, req.SubscriptionStatus); err != nil {
return err
}
@@ -424,18 +424,18 @@ func (h *Handlers) DeleteSubscribersByQuery(c echo.Context) error {
// BlocklistSubscribersByQuery bulk blocklists subscribers
// based on an arbitrary SQL expression.
-func (h *Handlers) BlocklistSubscribersByQuery(c echo.Context) error {
+func (a *App) BlocklistSubscribersByQuery(c echo.Context) error {
var req subQueryReq
if err := c.Bind(&req); err != nil {
return err
}
if req.Query == "" {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "query"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "query"))
}
// Update the subscribers in the DB.
- if err := h.app.core.BlocklistSubscribersByQuery(req.Query, req.ListIDs, req.SubscriptionStatus); err != nil {
+ if err := a.core.BlocklistSubscribersByQuery(req.Query, req.ListIDs, req.SubscriptionStatus); err != nil {
return err
}
@@ -444,7 +444,7 @@ func (h *Handlers) BlocklistSubscribersByQuery(c echo.Context) error {
// ManageSubscriberListsByQuery bulk adds/removes/unsubscribes subscribers
// from one or more lists based on an arbitrary SQL expression.
-func (h *Handlers) ManageSubscriberListsByQuery(c echo.Context) error {
+func (a *App) ManageSubscriberListsByQuery(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -454,7 +454,7 @@ func (h *Handlers) ManageSubscriberListsByQuery(c echo.Context) error {
}
if len(req.TargetListIDs) == 0 {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.T("subscribers.errorNoListsGiven"))
+ a.i18n.T("subscribers.errorNoListsGiven"))
}
// Filter lists against the current user's permitted lists.
@@ -465,13 +465,13 @@ func (h *Handlers) ManageSubscriberListsByQuery(c echo.Context) error {
var err error
switch req.Action {
case "add":
- err = h.app.core.AddSubscriptionsByQuery(req.Query, sourceListIDs, targetListIDs, req.Status, req.SubscriptionStatus)
+ err = a.core.AddSubscriptionsByQuery(req.Query, sourceListIDs, targetListIDs, req.Status, req.SubscriptionStatus)
case "remove":
- err = h.app.core.DeleteSubscriptionsByQuery(req.Query, sourceListIDs, targetListIDs, req.SubscriptionStatus)
+ err = a.core.DeleteSubscriptionsByQuery(req.Query, sourceListIDs, targetListIDs, req.SubscriptionStatus)
case "unsubscribe":
- err = h.app.core.UnsubscribeListsByQuery(req.Query, sourceListIDs, targetListIDs, req.SubscriptionStatus)
+ err = a.core.UnsubscribeListsByQuery(req.Query, sourceListIDs, targetListIDs, req.SubscriptionStatus)
default:
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("subscribers.invalidAction"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.invalidAction"))
}
if err != nil {
@@ -482,14 +482,14 @@ func (h *Handlers) ManageSubscriberListsByQuery(c echo.Context) error {
}
// DeleteSubscriberBounces deletes all the bounces on a subscriber.
-func (h *Handlers) DeleteSubscriberBounces(c echo.Context) error {
+func (a *App) DeleteSubscriberBounces(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Delete the bounces from the DB.
- if err := h.app.core.DeleteSubscriberBounces(id, ""); err != nil {
+ if err := a.core.DeleteSubscriberBounces(id, ""); err != nil {
return err
}
@@ -499,21 +499,21 @@ func (h *Handlers) DeleteSubscriberBounces(c echo.Context) error {
// ExportSubscriberData pulls the subscriber's profile,
// list subscriptions, campaign views and clicks and produces
// a JSON report. This is a privacy feature and depends on the
-// configuration in h.app.Constants.Privacy.
-func (h *Handlers) ExportSubscriberData(c echo.Context) error {
+// configuration in a.Constants.Privacy.
+func (a *App) ExportSubscriberData(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Get the subscriber's data. A single query that gets the profile,
// list subscriptions, campaign views, and link clicks. Names of
// private lists are replaced with "Private list".
- _, b, err := h.exportSubscriberData(id, "", h.app.constants.Privacy.Exportable)
+ _, b, err := a.exportSubscriberData(id, "", a.constants.Privacy.Exportable)
if err != nil {
- h.app.log.Printf("error exporting subscriber data: %s", err)
+ a.log.Printf("error exporting subscriber data: %s", err)
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.subscribers}", "error", err.Error()))
+ a.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.subscribers}", "error", err.Error()))
}
// Set headers to force the browser to prompt for download.
@@ -526,8 +526,8 @@ func (h *Handlers) ExportSubscriberData(c echo.Context) error {
// subscriptions, campaign_views, link_clicks (if they're enabled in the config)
// and returns a formatted, indented JSON payload. Either takes a numeric id
// and an empty subUUID or takes 0 and a string subUUID.
-func (h *Handlers) exportSubscriberData(id int, subUUID string, exportables map[string]bool) (models.SubscriberExportProfile, []byte, error) {
- data, err := h.app.core.GetSubscriberProfileForExport(id, subUUID)
+func (a *App) exportSubscriberData(id int, subUUID string, exportables map[string]bool) (models.SubscriberExportProfile, []byte, error) {
+ data, err := a.core.GetSubscriberProfileForExport(id, subUUID)
if err != nil {
return data, nil, err
}
@@ -549,7 +549,7 @@ func (h *Handlers) exportSubscriberData(id int, subUUID string, exportables map[
// Marshal the data into an indented payload.
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
- h.app.log.Printf("error marshalling subscriber export data: %v", err)
+ a.log.Printf("error marshalling subscriber export data: %v", err)
return data, nil, err
}
@@ -606,7 +606,7 @@ func (app *App) optinConfirmNotify() func(sub models.Subscriber, listIDs []int)
// hasSubPerm checks whether the current user has permission to access the given list
// of subscriber IDs.
-func (h *Handlers) hasSubPerm(u auth.User, subIDs []int) error {
+func (a *App) hasSubPerm(u auth.User, subIDs []int) error {
allPerm, listIDs := u.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
// User has blanket get_all|manage_all permission.
@@ -615,14 +615,14 @@ func (h *Handlers) hasSubPerm(u auth.User, subIDs []int) error {
}
// Check whether the subscribers have the list IDs permitted to the user.
- res, err := h.app.core.HasSubscriberLists(subIDs, listIDs)
+ res, err := a.core.HasSubscriberLists(subIDs, listIDs)
if err != nil {
return err
}
for id, has := range res {
if !has {
- return echo.NewHTTPError(http.StatusForbidden, h.app.i18n.Ts("globals.messages.permissionDenied", "name", fmt.Sprintf("subscriber: %d", id)))
+ return echo.NewHTTPError(http.StatusForbidden, a.i18n.Ts("globals.messages.permissionDenied", "name", fmt.Sprintf("subscriber: %d", id)))
}
}
@@ -630,14 +630,14 @@ func (h *Handlers) hasSubPerm(u auth.User, subIDs []int) error {
}
// filterListQueryByPerm filters the list IDs in the query params and returns the list IDs to which the user has access.
-func (h *Handlers) filterListQueryByPerm(param string, qp url.Values, user auth.User) ([]int, error) {
+func (a *App) filterListQueryByPerm(param string, qp url.Values, user auth.User) ([]int, error) {
var listIDs []int
// If there are incoming list query params, filter them by permission.
if qp.Has(param) {
ids, err := getQueryInts(param, qp)
if err != nil {
- return nil, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return nil, echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
listIDs = user.FilterListsByPerm(auth.PermTypeGet|auth.PermTypeManage, ids)
diff --git a/cmd/templates.go b/cmd/templates.go
index 8115f1e7..0dc847f5 100644
--- a/cmd/templates.go
+++ b/cmd/templates.go
@@ -32,14 +32,14 @@ var (
)
// GetTemplates handles retrieval of templates.
-func (h *Handlers) GetTemplates(c echo.Context) error {
+func (a *App) GetTemplates(c echo.Context) error {
// Fetch one list.
var (
id, _ = strconv.Atoi(c.Param("id"))
noBody, _ = strconv.ParseBool(c.QueryParam("no_body"))
)
if id > 0 {
- out, err := h.app.core.GetTemplate(id, noBody)
+ out, err := a.core.GetTemplate(id, noBody)
if err != nil {
return err
}
@@ -48,7 +48,7 @@ func (h *Handlers) GetTemplates(c echo.Context) error {
}
// Fetch templates from the DB (with or without body).
- out, err := h.app.core.GetTemplates("", noBody)
+ out, err := a.core.GetTemplates("", noBody)
if err != nil {
return err
}
@@ -57,7 +57,7 @@ func (h *Handlers) GetTemplates(c echo.Context) error {
}
// PreviewTemplate renders the HTML preview of a template.
-func (h *Handlers) PreviewTemplate(c echo.Context) error {
+func (a *App) PreviewTemplate(c echo.Context) error {
tpl := models.Template{
Type: c.FormValue("template_type"),
Body: c.FormValue("body"),
@@ -71,16 +71,16 @@ func (h *Handlers) PreviewTemplate(c echo.Context) error {
if tpl.Type == models.TemplateTypeCampaign && !regexpTplTag.MatchString(tpl.Body) {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
+ a.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
}
} else {
// There is no body. Fetch the template from the DB.
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
- t, err := h.app.core.GetTemplate(id, false)
+ t, err := a.core.GetTemplate(id, false)
if err != nil {
return err
}
@@ -93,28 +93,28 @@ func (h *Handlers) PreviewTemplate(c echo.Context) error {
if tpl.Type == models.TemplateTypeCampaign {
camp := models.Campaign{
UUID: dummyUUID,
- Name: h.app.i18n.T("templates.dummyName"),
- Subject: h.app.i18n.T("templates.dummySubject"),
+ Name: a.i18n.T("templates.dummyName"),
+ Subject: a.i18n.T("templates.dummySubject"),
FromEmail: "[email protected]",
TemplateBody: tpl.Body,
Body: dummyTpl,
}
- if err := camp.CompileTemplate(h.app.manager.TemplateFuncs(&camp)); err != nil {
+ if err := camp.CompileTemplate(a.manager.TemplateFuncs(&camp)); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.errorCompiling", "error", err.Error()))
+ a.i18n.Ts("templates.errorCompiling", "error", err.Error()))
}
// Render the message body.
- msg, err := h.app.manager.NewCampaignMessage(&camp, dummySubscriber)
+ msg, err := a.manager.NewCampaignMessage(&camp, dummySubscriber)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.errorRendering", "error", err.Error()))
+ a.i18n.Ts("templates.errorRendering", "error", err.Error()))
}
out = msg.Body()
} else {
// Compile transactional template.
- if err := tpl.Compile(h.app.manager.GenericTemplateFuncs()); err != nil {
+ if err := tpl.Compile(a.manager.GenericTemplateFuncs()); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
@@ -133,12 +133,12 @@ func (h *Handlers) PreviewTemplate(c echo.Context) error {
}
// CreateTemplate handles template creation.
-func (h *Handlers) CreateTemplate(c echo.Context) error {
+func (a *App) CreateTemplate(c echo.Context) error {
var o models.Template
if err := c.Bind(&o); err != nil {
return err
}
- if err := h.validateTemplate(o); err != nil {
+ if err := a.validateTemplate(o); err != nil {
return err
}
@@ -147,9 +147,9 @@ func (h *Handlers) CreateTemplate(c echo.Context) error {
var funcs template.FuncMap
if o.Type == models.TemplateTypeCampaign {
o.Subject = ""
- funcs = h.app.manager.TemplateFuncs(nil)
+ funcs = a.manager.TemplateFuncs(nil)
} else {
- funcs = h.app.manager.GenericTemplateFuncs()
+ funcs = a.manager.GenericTemplateFuncs()
}
// Compile the template and validate.
@@ -158,7 +158,7 @@ func (h *Handlers) CreateTemplate(c echo.Context) error {
}
// Create the template the in the DB.
- out, err := h.app.core.CreateTemplate(o.Name, o.Type, o.Subject, []byte(o.Body))
+ out, err := a.core.CreateTemplate(o.Name, o.Type, o.Subject, []byte(o.Body))
if err != nil {
return err
}
@@ -166,24 +166,24 @@ func (h *Handlers) CreateTemplate(c echo.Context) error {
// If it's a transactional template, cache it in the manager
// to be used for arbitrary incoming tx message pushes.
if o.Type == models.TemplateTypeTx {
- h.app.manager.CacheTpl(out.ID, &o)
+ a.manager.CacheTpl(out.ID, &o)
}
return c.JSON(http.StatusOK, okResp{out})
}
// UpdateTemplate handles template modification.
-func (h *Handlers) UpdateTemplate(c echo.Context) error {
+func (a *App) UpdateTemplate(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
var o models.Template
if err := c.Bind(&o); err != nil {
return err
}
- if err := h.validateTemplate(o); err != nil {
+ if err := a.validateTemplate(o); err != nil {
return err
}
@@ -192,9 +192,9 @@ func (h *Handlers) UpdateTemplate(c echo.Context) error {
var funcs template.FuncMap
if o.Type == models.TemplateTypeCampaign {
o.Subject = ""
- funcs = h.app.manager.TemplateFuncs(nil)
+ funcs = a.manager.TemplateFuncs(nil)
} else {
- funcs = h.app.manager.GenericTemplateFuncs()
+ funcs = a.manager.GenericTemplateFuncs()
}
// Compile the template and validate.
@@ -203,14 +203,14 @@ func (h *Handlers) UpdateTemplate(c echo.Context) error {
}
// Update the template in the DB.
- out, err := h.app.core.UpdateTemplate(id, o.Name, o.Subject, []byte(o.Body))
+ out, err := a.core.UpdateTemplate(id, o.Name, o.Subject, []byte(o.Body))
if err != nil {
return err
}
// If it's a transactional template, cache it.
if out.Type == models.TemplateTypeTx {
- h.app.manager.CacheTpl(out.ID, &o)
+ a.manager.CacheTpl(out.ID, &o)
}
return c.JSON(http.StatusOK, okResp{out})
@@ -218,52 +218,52 @@ func (h *Handlers) UpdateTemplate(c echo.Context) error {
}
// TemplateSetDefault handles template modification.
-func (h *Handlers) TemplateSetDefault(c echo.Context) error {
+func (a *App) TemplateSetDefault(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Update the template in the DB.
- if err := h.app.core.SetDefaultTemplate(id); err != nil {
+ if err := a.core.SetDefaultTemplate(id); err != nil {
return err
}
- return h.GetTemplates(c)
+ return a.GetTemplates(c)
}
// DeleteTemplate handles template deletion.
-func (h *Handlers) DeleteTemplate(c echo.Context) error {
+func (a *App) DeleteTemplate(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Delete the template from the DB.
- if err := h.app.core.DeleteTemplate(id); err != nil {
+ if err := a.core.DeleteTemplate(id); err != nil {
return err
}
// Delete cached template.
- h.app.manager.DeleteTpl(id)
+ a.manager.DeleteTpl(id)
return c.JSON(http.StatusOK, okResp{true})
}
// compileTemplate validates template fields.
-func (h *Handlers) validateTemplate(o models.Template) error {
+func (a *App) validateTemplate(o models.Template) error {
if !strHasLen(o.Name, 1, stdInputMaxLen) {
- return errors.New(h.app.i18n.T("campaigns.fieldInvalidName"))
+ return errors.New(a.i18n.T("campaigns.fieldInvalidName"))
}
if o.Type == models.TemplateTypeCampaign && !regexpTplTag.MatchString(o.Body) {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
+ a.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
}
if o.Type == models.TemplateTypeTx && strings.TrimSpace(o.Subject) == "" {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.missingFields", "name", "subject"))
+ a.i18n.Ts("globals.messages.missingFields", "name", "subject"))
}
return nil
diff --git a/cmd/tx.go b/cmd/tx.go
index 1052d7d2..9b7360c8 100644
--- a/cmd/tx.go
+++ b/cmd/tx.go
@@ -14,7 +14,7 @@ import (
)
// SendTxMessage handles the sending of a transactional message.
-func (h *Handlers) SendTxMessage(c echo.Context) error {
+func (a *App) SendTxMessage(c echo.Context) error {
var m models.TxMessage
// If it's a multipart form, there may be file attachments.
@@ -22,18 +22,18 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
form, err := c.MultipartForm()
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", err.Error()))
+ a.i18n.Ts("globals.messages.invalidFields", "name", err.Error()))
}
data, ok := form.Value["data"]
if !ok || len(data) != 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "data"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "data"))
}
// Parse the JSON data.
if err := json.Unmarshal([]byte(data[0]), &m); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("data: %s", err.Error())))
+ a.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("data: %s", err.Error())))
}
// Attach files.
@@ -41,14 +41,14 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
file, err := f.Open()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("file: %s", err.Error())))
+ a.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("file: %s", err.Error())))
}
defer file.Close()
b, err := io.ReadAll(file)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("file: %s", err.Error())))
+ a.i18n.Ts("globals.messages.invalidFields", "name", fmt.Sprintf("file: %s", err.Error())))
}
m.Attachments = append(m.Attachments, models.Attachment{
@@ -63,17 +63,17 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
}
// Validate fields.
- if r, err := h.validateTxMessage(m); err != nil {
+ if r, err := a.validateTxMessage(m); err != nil {
return err
} else {
m = r
}
// Get the cached tx template.
- tpl, err := h.app.manager.GetTpl(m.TemplateID)
+ tpl, err := a.manager.GetTpl(m.TemplateID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.notFound", "name", fmt.Sprintf("template %d", m.TemplateID)))
+ a.i18n.Ts("globals.messages.notFound", "name", fmt.Sprintf("template %d", m.TemplateID)))
}
var (
@@ -99,7 +99,7 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
}
// Get the subscriber.
- sub, err := h.app.core.GetSubscriber(subID, "", subEmail)
+ sub, err := a.core.GetSubscriber(subID, "", subEmail)
if err != nil {
// If the subscriber is not found, log that error and move on without halting on the list.
if er, ok := err.(*echo.HTTPError); ok && er.Code == http.StatusBadRequest {
@@ -113,7 +113,7 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
// Render the message.
if err := m.Render(sub, tpl); err != nil {
return echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.errorFetching", "name"))
+ a.i18n.Ts("globals.messages.errorFetching", "name"))
}
// Prepare the final message.
@@ -143,8 +143,8 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
}
}
- if err := h.app.manager.PushMessage(msg); err != nil {
- h.app.log.Printf("error sending message (%s): %v", msg.Subject, err)
+ if err := a.manager.PushMessage(msg); err != nil {
+ a.log.Printf("error sending message (%s): %v", msg.Subject, err)
return err
}
}
@@ -157,14 +157,14 @@ func (h *Handlers) SendTxMessage(c echo.Context) error {
}
// validateTxMessage validates the tx message fields.
-func (h *Handlers) validateTxMessage(m models.TxMessage) (models.TxMessage, error) {
+func (a *App) validateTxMessage(m models.TxMessage) (models.TxMessage, error) {
if len(m.SubscriberEmails) > 0 && m.SubscriberEmail != "" {
return m, echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", "do not send `subscriber_email`"))
+ a.i18n.Ts("globals.messages.invalidFields", "name", "do not send `subscriber_email`"))
}
if len(m.SubscriberIDs) > 0 && m.SubscriberID != 0 {
return m, echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", "do not send `subscriber_id`"))
+ a.i18n.Ts("globals.messages.invalidFields", "name", "do not send `subscriber_id`"))
}
if m.SubscriberEmail != "" {
@@ -177,12 +177,12 @@ func (h *Handlers) validateTxMessage(m models.TxMessage) (models.TxMessage, erro
if (len(m.SubscriberEmails) == 0 && len(m.SubscriberIDs) == 0) || (len(m.SubscriberEmails) > 0 && len(m.SubscriberIDs) > 0) {
return m, echo.NewHTTPError(http.StatusBadRequest,
- h.app.i18n.Ts("globals.messages.invalidFields", "name", "send subscriber_emails OR subscriber_ids"))
+ a.i18n.Ts("globals.messages.invalidFields", "name", "send subscriber_emails OR subscriber_ids"))
}
for n, email := range m.SubscriberEmails {
if m.SubscriberEmail != "" {
- em, err := h.app.importer.SanitizeEmail(email)
+ em, err := a.importer.SanitizeEmail(email)
if err != nil {
return m, echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
@@ -191,13 +191,13 @@ func (h *Handlers) validateTxMessage(m models.TxMessage) (models.TxMessage, erro
}
if m.FromEmail == "" {
- m.FromEmail = h.app.constants.FromEmail
+ m.FromEmail = a.constants.FromEmail
}
if m.Messenger == "" {
m.Messenger = emailMsgr
- } else if !h.app.manager.HasMessenger(m.Messenger) {
- return m, echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("campaigns.fieldInvalidMessenger", "name", m.Messenger))
+ } else if !a.manager.HasMessenger(m.Messenger) {
+ return m, echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("campaigns.fieldInvalidMessenger", "name", m.Messenger))
}
return m, nil
diff --git a/cmd/users.go b/cmd/users.go
index 44ee9def..360689f6 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -18,7 +18,7 @@ var (
)
// GetUsers retrieves users.
-func (h *Handlers) GetUsers(c echo.Context) error {
+func (a *App) GetUsers(c echo.Context) error {
var (
single = false
userID, _ = strconv.Atoi(c.Param("id"))
@@ -29,7 +29,7 @@ func (h *Handlers) GetUsers(c echo.Context) error {
if single {
// Get the user from the DB.
- out, err := h.app.core.GetUser(userID, "", "")
+ out, err := a.core.GetUser(userID, "", "")
if err != nil {
return err
}
@@ -41,7 +41,7 @@ func (h *Handlers) GetUsers(c echo.Context) error {
}
// Get all users from the DB.
- out, err := h.app.core.GetUsers()
+ out, err := a.core.GetUsers()
if err != nil {
return err
}
@@ -55,7 +55,7 @@ func (h *Handlers) GetUsers(c echo.Context) error {
}
// CreateUser handles user creation.
-func (h *Handlers) CreateUser(c echo.Context) error {
+func (a *App) CreateUser(c echo.Context) error {
var u = auth.User{}
if err := c.Bind(&u); err != nil {
return err
@@ -67,18 +67,18 @@ func (h *Handlers) CreateUser(c echo.Context) error {
// Validate fields.
if !strHasLen(u.Username, 3, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if !reUsername.MatchString(u.Username) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if u.Type != auth.UserTypeAPI {
if !utils.ValidateEmail(email) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
if u.PasswordLogin {
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
}
@@ -90,7 +90,7 @@ func (h *Handlers) CreateUser(c echo.Context) error {
}
// Create the user in the DB.
- user, err := h.app.core.CreateUser(u)
+ user, err := a.core.CreateUser(u)
if err != nil {
return err
}
@@ -101,7 +101,7 @@ func (h *Handlers) CreateUser(c echo.Context) error {
}
// Cache the API token for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
@@ -109,10 +109,10 @@ func (h *Handlers) CreateUser(c echo.Context) error {
}
// UpdateUser handles user modification.
-func (h *Handlers) UpdateUser(c echo.Context) error {
+func (a *App) UpdateUser(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
if id < 1 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
// Incoming params.
@@ -127,31 +127,31 @@ func (h *Handlers) UpdateUser(c echo.Context) error {
// Validate fields.
if !strHasLen(u.Username, 3, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if !reUsername.MatchString(u.Username) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
if u.Type != auth.UserTypeAPI {
if !utils.ValidateEmail(email) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
// Validate password if password login is enabled.
if u.PasswordLogin && u.Password.String != "" {
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
if u.Password.String != "" {
// If a password is sent, validate it before updating in the DB. If it's not set, leave the password in the DB untouched.
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
} else {
// Get the user from the DB.
- user, err := h.app.core.GetUser(id, "", "")
+ user, err := a.core.GetUser(id, "", "")
if err != nil {
return err
}
@@ -159,7 +159,7 @@ func (h *Handlers) UpdateUser(c echo.Context) error {
// If password login is enabled, but there's no password in the DB and there's no incoming
// password, throw an error.
if !user.HasPassword {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
}
}
@@ -173,7 +173,7 @@ func (h *Handlers) UpdateUser(c echo.Context) error {
}
// Update the user in the DB.
- user, err := h.app.core.UpdateUser(id, u)
+ user, err := a.core.UpdateUser(id, u)
if err != nil {
return err
}
@@ -182,7 +182,7 @@ func (h *Handlers) UpdateUser(c echo.Context) error {
user.Password = null.String{}
// Cache the API token for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
@@ -190,25 +190,25 @@ func (h *Handlers) UpdateUser(c echo.Context) error {
}
// DeleteUsers handles user deletion, either a single one (ID in the URI), or a list.
-func (h *Handlers) DeleteUsers(c echo.Context) error {
+func (a *App) DeleteUsers(c echo.Context) error {
var (
id, _ = strconv.ParseInt(c.Param("id"), 10, 64)
ids []int
)
if id < 1 && len(ids) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.T("globals.messages.invalidID"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
if id > 0 {
ids = append(ids, int(id))
}
// Delete the user(s) from the DB.
- if err := h.app.core.DeleteUsers(ids); err != nil {
+ if err := a.core.DeleteUsers(ids); err != nil {
return err
}
// Cache the API token for in-memory, off-DB /api/* request auth.
- if _, err := cacheUsers(h.app.core, h.app.auth); err != nil {
+ if _, err := cacheUsers(a.core, a.auth); err != nil {
return err
}
@@ -216,7 +216,7 @@ func (h *Handlers) DeleteUsers(c echo.Context) error {
}
// GetUserProfile fetches the uesr profile for the currently logged in user.
-func (h *Handlers) GetUserProfile(c echo.Context) error {
+func (a *App) GetUserProfile(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -228,7 +228,7 @@ func (h *Handlers) GetUserProfile(c echo.Context) error {
}
// UpdateUserProfile update's the current user's profile.
-func (h *Handlers) UpdateUserProfile(c echo.Context) error {
+func (a *App) UpdateUserProfile(c echo.Context) error {
// Get the authenticated user.
user := auth.GetUser(c)
@@ -244,19 +244,19 @@ func (h *Handlers) UpdateUserProfile(c echo.Context) error {
// Validate fields.
if user.PasswordLogin {
if !utils.ValidateEmail(email) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
u.Email = null.String{String: email, Valid: true}
}
if u.PasswordLogin && u.Password.String != "" {
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, h.app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
}
}
// Update the user in the DB.
- out, err := h.app.core.UpdateUserProfile(user.ID, u)
+ out, err := a.core.UpdateUserProfile(user.ID, u)
if err != nil {
return err
}