Skip to content

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

Fix several list permission check issues.

Kailash Nadh4233047ee0b9
diff --git a/cmd/bounce.go b/cmd/bounce.go
index 07cf38cb..79086f44 100644
--- a/cmd/bounce.go
+++ b/cmd/bounce.go
@@ -33,13 +33,18 @@ type bouncesView struct {
// ViewBounces renders the HTML view for bounces.
func (a *App) ViewBounces(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+
q := makeQuery(c.Request().URL.Query(), bouncesQueryDefaults)
campID, _ := strconv.Atoi(q.Get("campaign_id"))
// Query and fetch bounces from the DB.
pg := a.pg.NewFromURL(q)
- res, total, err := a.core.QueryBounces(campID, 0, q.Get("source"), q.Get("type"), q.Get("order_by"), q.Get("order"), pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryBounces(campID, 0, q.Get("source"), q.Get("type"), q.Get("order_by"), q.Get("order"), pg.Offset, pg.Limit, allLists, listIDs)
if err != nil {
return err
}
@@ -55,9 +60,14 @@ func (a *App) ViewBounces(c *echo.Context) error {
// GetBounce handles retrieval of a specific bounce record by ID.
func (a *App) GetBounce(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+
// Fetch one bounce from the DB.
id := getID(c)
- out, err := a.core.GetBounce(id)
+ out, err := a.core.GetBounce(id, allLists, listIDs)
if err != nil {
return err
}
@@ -67,6 +77,11 @@ func (a *App) GetBounce(c *echo.Context) error {
// GetBounces handles retrieval of bounce records.
func (a *App) GetBounces(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+
var (
campID, _ = strconv.Atoi(c.QueryParam("campaign_id"))
source = c.FormValue("source")
@@ -78,7 +93,7 @@ func (a *App) GetBounces(c *echo.Context) error {
)
// Query and fetch bounces from the DB.
- res, total, err := a.core.QueryBounces(campID, 0, source, typ, orderBy, order, pg.Offset, pg.Limit)
+ res, total, err := a.core.QueryBounces(campID, 0, source, typ, orderBy, order, pg.Offset, pg.Limit, allLists, listIDs)
if err != nil {
return err
}
@@ -102,15 +117,20 @@ func (a *App) GetBounces(c *echo.Context) error {
// GetSubscriberBounces retrieves a subscriber's bounce records.
func (a *App) GetSubscriberBounces(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+
subID := getID(c)
- // Check if the user has access to at least one of the lists on the subscriber.
- if err := a.hasSubPerm(auth.GetUser(c), auth.PermTypeGet|auth.PermTypeManage, []int{subID}); err != nil {
+ // Verify list permissions.
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{subID}); err != nil {
return err
}
// Query and fetch bounces from the DB.
- out, _, err := a.core.QueryBounces(0, subID, "", "", "", "", 0, 1000)
+ out, _, err := a.core.QueryBounces(0, subID, "", "", "", "", 0, 1000, allLists, listIDs)
if err != nil {
return err
}
@@ -120,6 +140,11 @@ func (a *App) GetSubscriberBounces(c *echo.Context) error {
// DeleteBounces handles bounce deletion of a list.
func (a *App) DeleteBounces(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeManage)
+
all, _ := strconv.ParseBool(c.QueryParam("all"))
var ids []int
@@ -143,7 +168,7 @@ func (a *App) DeleteBounces(c *echo.Context) error {
}
// Delete bounces from the DB.
- if err := a.core.DeleteBounces(ids, all, campID, c.QueryParam("source"), c.QueryParam("type")); err != nil {
+ if err := a.core.DeleteBounces(ids, all, campID, c.QueryParam("source"), c.QueryParam("type"), allLists, listIDs); err != nil {
return err
}
@@ -152,9 +177,14 @@ func (a *App) DeleteBounces(c *echo.Context) error {
// DeleteBounce handles bounce deletion of a single bounce record.
func (a *App) DeleteBounce(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeManage)
+
// Delete bounces from the DB.
id := getID(c)
- if err := a.core.DeleteBounces([]int{id}, false, 0, "", ""); err != nil {
+ if err := a.core.DeleteBounces([]int{id}, false, 0, "", "", allLists, listIDs); err != nil {
return err
}
@@ -163,6 +193,11 @@ func (a *App) DeleteBounce(c *echo.Context) error {
// BlocklistBouncedSubscribers blocklists subscribers matching bounce IDs or filters.
func (a *App) BlocklistBouncedSubscribers(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ // Get the permitted lists for the user to filter bounces by.
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeManage)
+
ids, err := parseStringIDs(c.QueryParams()["id"])
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
@@ -173,7 +208,7 @@ func (a *App) BlocklistBouncedSubscribers(c *echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidID"))
}
- if err := a.core.BlocklistBouncedSubscribers(ids, campID, c.QueryParam("source"), c.QueryParam("type")); err != nil {
+ if err := a.core.BlocklistBouncedSubscribers(ids, campID, c.QueryParam("source"), c.QueryParam("type"), allLists, listIDs); err != nil {
return err
}
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index 428ecca9..c63797c2 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -684,10 +684,18 @@ func (a *App) DeleteCampaigns(c *echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
}
-// GetRunningCampaignStats returns stats of a given set of campaign IDs.
+// GetRunningCampaignStats returns stats of permitted running campaigns.
func (a *App) GetRunningCampaignStats(c *echo.Context) error {
+ user := auth.GetUser(c)
+
+ var permittedLists []int
+ hasAllPerm := user.HasPerm(auth.PermCampaignsGetAll)
+ if !hasAllPerm {
+ hasAllPerm, permittedLists = user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+ }
+
// Get the running campaign stats from the DB.
- out, err := a.core.GetRunningCampaignStats()
+ out, err := a.core.GetRunningCampaignStats(hasAllPerm, permittedLists)
if err != nil {
return err
}
diff --git a/cmd/import.go b/cmd/import.go
index 4049cae7..4fadc213 100644
--- a/cmd/import.go
+++ b/cmd/import.go
@@ -74,6 +74,14 @@ func (a *App) ImportSubscribers(c *echo.Context) error {
// Filter list IDs against the current user's permitted lists.
// Blocklist mode doesn't require list subscriptions.
user := auth.GetUser(c)
+
+ // Because blocklisting is a global subscriber-level action that supercedes all lists,
+ // mandate the full list management permission.
+ if opt.Mode == subimporter.ModeBlocklist && !user.HasPerm(auth.PermListManageAll) {
+ return echo.NewHTTPError(http.StatusForbidden,
+ a.i18n.Ts("globals.messages.permissionDenied", "name", auth.PermListManageAll))
+ }
+
opt.ListIDs = user.FilterListsByPerm(auth.PermTypeManage, opt.ListIDs)
if len(opt.ListIDs) == 0 && opt.Mode != subimporter.ModeBlocklist {
return echo.NewHTTPError(http.StatusForbidden,
diff --git a/cmd/public.go b/cmd/public.go
index ff6df366..b280690a 100644
--- a/cmd/public.go
+++ b/cmd/public.go
@@ -717,7 +717,7 @@ func (a *App) SelfExportSubscriberData(c *echo.Context) error {
// list subscriptions, campaign views, and link clicks. Names of
// private lists are replaced with "Private list".
subUUID := c.Param("subUUID")
- data, b, err := a.exportSubscriberData(0, subUUID, a.cfg.Privacy.Exportable)
+ data, b, err := a.exportSubscriberData(0, subUUID, a.cfg.Privacy.Exportable, true, nil)
if err != nil {
a.log.Printf("error exporting subscriber data: %s", err)
return c.Render(http.StatusInternalServerError, tplMessage,
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index fd59d5ed..0f43bb5f 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -201,12 +201,23 @@ func (a *App) ViewSubscriber(c *echo.Context) error {
// ViewSubscriberBounces renders the bounces tab of a subscriber.
func (a *App) ViewSubscriberBounces(c *echo.Context) error {
- out, err := a.getViewSubscriber(c)
+ user := auth.GetUser(c)
+ allLists, bounceListIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+
+ // Verify list perms.
+ id := getID(c)
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{id}); err != nil {
+ return err
+ }
+
+ out, err := a.core.GetSubscriber(id, "", "")
if err != nil {
return err
}
+ maskRestrictedSubLists(user, &out)
- bounces, _, err := a.core.QueryBounces(0, out.ID, "", "", "", "", 0, 1000)
+ // Get bounces from the DB.
+ bounces, _, err := a.core.QueryBounces(0, out.ID, "", "", "", "", 0, 1000, allLists, bounceListIDs)
if err != nil {
return err
}
@@ -228,7 +239,9 @@ func (a *App) ViewSubscriberInfo(c *echo.Context) error {
return err
}
- act, err := a.core.GetSubscriberActivity(out.ID)
+ user := auth.GetUser(c)
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+ act, err := a.core.GetSubscriberActivity(out.ID, allLists, listIDs)
if err != nil {
return err
}
@@ -239,7 +252,7 @@ func (a *App) ViewSubscriberInfo(c *echo.Context) error {
Subscriber: out,
}
- data.Charts, err = a.core.GetSubscriberCharts(out.ID)
+ data.Charts, err = a.core.GetSubscriberCharts(out.ID, allLists, listIDs)
if err != nil {
return err
}
@@ -372,7 +385,8 @@ func (a *App) GetSubscriberActivity(c *echo.Context) error {
}
// Fetch the subscriber activity from the DB.
- out, err := a.core.GetSubscriberActivity(id)
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+ out, err := a.core.GetSubscriberActivity(id, allLists, listIDs)
if err != nil {
return err
}
@@ -1033,7 +1047,9 @@ func (a *App) ExportSubscriberData(c *echo.Context) error {
return err
}
- _, b, err := a.exportSubscriberData(id, "", a.cfg.Privacy.Exportable)
+ user := auth.GetUser(c)
+ allLists, listIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+ _, b, err := a.exportSubscriberData(id, "", a.cfg.Privacy.Exportable, allLists, listIDs)
if err != nil {
a.log.Printf("error exporting subscriber data: %s", err)
return echo.NewHTTPError(http.StatusInternalServerError,
@@ -1050,8 +1066,8 @@ func (a *App) 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 (a *App) exportSubscriberData(id int, subUUID string, exportables map[string]bool) (models.SubscriberExportProfile, []byte, error) {
- data, err := a.core.GetSubscriberProfileForExport(id, subUUID)
+func (a *App) exportSubscriberData(id int, subUUID string, exportables map[string]bool, allLists bool, listIDs []int) (models.SubscriberExportProfile, []byte, error) {
+ data, err := a.core.GetSubscriberProfileForExport(id, subUUID, allLists, listIDs)
if err != nil {
return data, nil, err
}
diff --git a/cmd/tx.go b/cmd/tx.go
index 8b6d699d..5f507fc3 100644
--- a/cmd/tx.go
+++ b/cmd/tx.go
@@ -8,6 +8,7 @@ import (
"net/textproto"
"strings"
+ "github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/internal/manager"
"github.com/knadh/listmonk/internal/messenger/email"
"github.com/knadh/listmonk/models"
@@ -70,6 +71,14 @@ func (a *App) SendTxMessage(c *echo.Context) error {
m = r
}
+ // Enforce subscriber read permission.
+ user := auth.GetUser(c)
+ if m.SubscriberMode != models.TxSubModeExternal &&
+ !user.HasPerm(auth.PermSubscribersGet) && !user.HasPerm(auth.PermSubscribersGetAll) {
+ return echo.NewHTTPError(http.StatusForbidden,
+ a.i18n.Ts("globals.messages.permissionDenied", "name", auth.PermSubscribersGet))
+ }
+
// Get the cached tx template.
tpl, err := a.manager.GetTpl(m.TemplateID)
if err != nil {
@@ -126,6 +135,13 @@ func (a *App) SendTxMessage(c *echo.Context) error {
} else {
return err
}
+ } else {
+ // Make sure the user has permission to read the subscriber.
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{sub.ID}); err != nil {
+ return err
+ }
+
+ maskRestrictedSubLists(user, &sub)
}
}
diff --git a/docs/docs/content/apis/transactional.md b/docs/docs/content/apis/transactional.md
index ae7afb00..77cacdcf 100644
--- a/docs/docs/content/apis/transactional.md
+++ b/docs/docs/content/apis/transactional.md
@@ -10,6 +10,8 @@ ______________________________________________________________________
Allows sending transactional messages to one or more subscribers via a preconfigured transactional template.
+Refering to an existing subscriber in the DB requires either `subscribers:get` (via list permissions) or `subscribers:get_all`. `external` mode does not require these permission.
+
##### Parameters
| Name | Type | Required | Description |
diff --git a/internal/auth/models.go b/internal/auth/models.go
index 0d840be3..52910716 100644
--- a/internal/auth/models.go
+++ b/internal/auth/models.go
@@ -3,6 +3,7 @@ package auth
import (
"encoding/json"
"net/http"
+ "slices"
"github.com/labstack/echo/v5"
"github.com/lib/pq"
@@ -216,7 +217,7 @@ func (u *User) hasListPerm(perm string, listID int) bool {
}
// GetPermittedLists returns a list of IDs the user has access to based on
-// the given get / manage permissions. If the user has the blanket "*_all"
+// either of the given get / manage permissions. If the user has the blanket "*_all"
// permission (or the user is a super admin), then the bool is set to true and
// the list is nil as all lists are permitted.
func (u *User) GetPermittedLists(types PermType) (bool, []int) {
@@ -247,24 +248,19 @@ func (u *User) GetPermittedLists(types PermType) (bool, []int) {
}
}
+ var out []int
if get {
- // If the user has per-list permissions, return that. Otherwise, let the
- // 'manage' permission check run.
- if len(u.GetListIDs) > 0 {
- out := make([]int, len(u.GetListIDs))
- copy(out, u.GetListIDs)
- return false, out
- }
+ out = append(out, u.GetListIDs...)
}
-
if manage {
- // User has per-list permissions.
- out := make([]int, len(u.ManageListIDs))
- copy(out, u.ManageListIDs)
- return false, out
+ for _, id := range u.ManageListIDs {
+ if !slices.Contains(out, id) {
+ out = append(out, id)
+ }
+ }
}
- return false, nil
+ return false, out
}
// FilterListsByPerm returns list IDs filtered by either of the given perms.
@@ -299,8 +295,10 @@ func (u *User) FilterListsByPerm(types PermType, listIDs []int) []int {
if get {
if _, ok := l[PermListGet]; ok {
out = append(out, id)
+ continue
}
- } else if manage {
+ }
+ if manage {
if _, ok := l[PermListManage]; ok {
out = append(out, id)
}
diff --git a/internal/core/bounces.go b/internal/core/bounces.go
index e1f528db..a64d12b7 100644
--- a/internal/core/bounces.go
+++ b/internal/core/bounces.go
@@ -12,8 +12,8 @@ import (
var bounceQuerySortFields = []string{"email", "campaign_name", "source", models.FieldCreatedAt, "type"}
// QueryBounces retrieves paginated bounce entries based on the given params.
-// It also returns the total number of bounce records in the DB.
-func (c *Core) QueryBounces(campID, subID int, source, typ, orderBy, order string, offset, limit int) ([]models.Bounce, int, error) {
+// It also returns the total number of bounce records within the permitted lists.
+func (c *Core) QueryBounces(campID, subID int, source, typ, orderBy, order string, offset, limit int, allLists bool, listIDs []int) ([]models.Bounce, int, error) {
if !strSliceContains(orderBy, bounceQuerySortFields) {
orderBy = models.FieldCreatedAt
}
@@ -21,9 +21,13 @@ func (c *Core) QueryBounces(campID, subID int, source, typ, orderBy, order strin
order = models.OrderDesc
}
+ if orderBy == "campaign_name" {
+ orderBy = "campaigns.name"
+ }
+
out := []models.Bounce{}
- stmt := strings.ReplaceAll(c.q.QueryBounces, "%order%", orderBy+" "+order)
- if err := c.db.Select(&out, stmt, 0, campID, subID, source, typ, offset, limit); err != nil {
+ stmt := strings.ReplaceAll(c.q.QueryBounces, "%order%", orderBy+" "+order+", bounces.id "+order)
+ if err := c.db.Select(&out, stmt, 0, campID, subID, source, typ, offset, limit, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error fetching bounces: %v", err)
return nil, 0, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.bounce}", "error", pqErrMsg(err)))
@@ -38,10 +42,10 @@ func (c *Core) QueryBounces(campID, subID int, source, typ, orderBy, order strin
}
// GetBounce retrieves bounce entries based on the given params.
-func (c *Core) GetBounce(id int) (models.Bounce, error) {
+func (c *Core) GetBounce(id int, allLists bool, listIDs []int) (models.Bounce, error) {
var out []models.Bounce
stmt := strings.ReplaceAll(c.q.QueryBounces, "%order%", "id "+models.OrderAsc)
- if err := c.db.Select(&out, stmt, id, 0, 0, "", "", 0, 1); err != nil {
+ if err := c.db.Select(&out, stmt, id, 0, 0, "", "", 0, 1, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error fetching bounces: %v", err)
return models.Bounce{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.bounce}", "error", pqErrMsg(err)))
@@ -87,8 +91,8 @@ func (c *Core) RecordBounce(b models.Bounce) error {
}
// BlocklistBouncedSubscribers blocklists subscribers matching bounce IDs or filters.
-func (c *Core) BlocklistBouncedSubscribers(ids []int, campID int, source, typ string) error {
- if _, err := c.q.BlocklistBouncedSubscribers.Exec(pq.Array(ids), campID, source, typ); err != nil {
+func (c *Core) BlocklistBouncedSubscribers(ids []int, campID int, source, typ string, allLists bool, listIDs []int) error {
+ if _, err := c.q.BlocklistBouncedSubscribers.Exec(pq.Array(ids), campID, source, typ, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error blocklisting bounced subscribers: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, c.i18n.Ts("subscribers.errorBlocklisting", "error", err.Error()))
}
@@ -97,13 +101,13 @@ func (c *Core) BlocklistBouncedSubscribers(ids []int, campID int, source, typ st
}
// DeleteBounce deletes a bounce record.
-func (c *Core) DeleteBounce(id int) error {
- return c.DeleteBounces([]int{id}, false, 0, "", "")
+func (c *Core) DeleteBounce(id int, allLists bool, listIDs []int) error {
+ return c.DeleteBounces([]int{id}, false, 0, "", "", allLists, listIDs)
}
// DeleteBounces deletes bounce records by IDs or filters.
-func (c *Core) DeleteBounces(ids []int, all bool, campID int, source, typ string) error {
- if _, err := c.q.DeleteBounces.Exec(pq.Array(ids), all, campID, source, typ); err != nil {
+func (c *Core) DeleteBounces(ids []int, all bool, campID int, source, typ string, allLists bool, listIDs []int) error {
+ if _, err := c.q.DeleteBounces.Exec(pq.Array(ids), all, campID, source, typ, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error deleting lists: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorDeleting", "name", "{globals.terms.list}", "error", pqErrMsg(err)))
diff --git a/internal/core/campaigns.go b/internal/core/campaigns.go
index c4b31b83..320a140f 100644
--- a/internal/core/campaigns.go
+++ b/internal/core/campaigns.go
@@ -364,9 +364,9 @@ func (c *Core) CampaignHasLists(id int, listIDs []int) (bool, error) {
}
// GetRunningCampaignStats returns the progress stats of running campaigns.
-func (c *Core) GetRunningCampaignStats() ([]models.CampaignStats, error) {
+func (c *Core) GetRunningCampaignStats(hasAllPerm bool, permittedLists []int) ([]models.CampaignStats, error) {
out := []models.CampaignStats{}
- if err := c.q.GetCampaignStatus.Select(&out, models.CampaignStatusRunning); err != nil {
+ if err := c.q.GetCampaignStatus.Select(&out, models.CampaignStatusRunning, hasAllPerm, pq.Array(permittedLists)); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
diff --git a/internal/core/subscribers.go b/internal/core/subscribers.go
index 4b3e526d..21efc912 100644
--- a/internal/core/subscribers.go
+++ b/internal/core/subscribers.go
@@ -211,14 +211,14 @@ func (c *Core) GetSubscriberLists(subID int, uuid string, listIDs []int, listUUI
// GetSubscriberProfileForExport returns the subscriber's profile data as a JSON exportable.
// 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".
-func (c *Core) GetSubscriberProfileForExport(id int, uuid string) (models.SubscriberExportProfile, error) {
+func (c *Core) GetSubscriberProfileForExport(id int, uuid string, allLists bool, listIDs []int) (models.SubscriberExportProfile, error) {
var uu any
if uuid != "" {
uu = uuid
}
var out models.SubscriberExportProfile
- if err := c.q.ExportSubscriberData.Get(&out, id, uu); err != nil {
+ if err := c.q.ExportSubscriberData.Get(&out, id, uu, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error fetching subscriber export data: %v", err)
return models.SubscriberExportProfile{}, echo.NewHTTPError(http.StatusInternalServerError,
@@ -229,9 +229,9 @@ func (c *Core) GetSubscriberProfileForExport(id int, uuid string) (models.Subscr
}
// GetSubscriberActivity returns the subscriber's campaign views and link clicks for the Activity tab.
-func (c *Core) GetSubscriberActivity(id int) (models.SubscriberActivity, error) {
+func (c *Core) GetSubscriberActivity(id int, allLists bool, listIDs []int) (models.SubscriberActivity, error) {
var out models.SubscriberActivity
- if err := c.q.GetSubscriberActivity.Get(&out, id); err != nil {
+ if err := c.q.GetSubscriberActivity.Get(&out, id, allLists, pq.Array(listIDs)); err != nil {
c.log.Printf("error fetching subscriber activity: %v", err)
return models.SubscriberActivity{}, echo.NewHTTPError(http.StatusInternalServerError,
@@ -242,9 +242,9 @@ func (c *Core) GetSubscriberActivity(id int) (models.SubscriberActivity, error)
}
// GetSubscriberCharts returns subscriber views and clicks.
-func (c *Core) GetSubscriberCharts(id int) (types.JSONText, error) {
+func (c *Core) GetSubscriberCharts(id int, allLists bool, listIDs []int) (types.JSONText, error) {
var out types.JSONText
- if err := c.q.GetSubscriberCharts.Get(&out, id); err != nil {
+ if err := c.q.GetSubscriberCharts.Get(&out, id, allLists, pq.Array(listIDs)); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "subscriber charts", "error", pqErrMsg(err)))
}
@@ -429,7 +429,7 @@ func (c *Core) UpdateSubscriber(id int, sub models.Subscriber) (models.Subscribe
c.i18n.Ts("globals.messages.errorUpdating", "name", "{globals.terms.subscriber}", "error", pqErrMsg(err)))
}
- out, err := c.GetSubscriber(sub.ID, "", sub.Email)
+ out, err := c.GetSubscriber(id, "", "")
if err != nil {
return models.Subscriber{}, err
}
@@ -475,7 +475,7 @@ func (c *Core) UpdateSubscriberWithLists(id int, sub models.Subscriber, listIDs
c.i18n.Ts("globals.messages.errorUpdating", "name", "{globals.terms.subscriber}", "error", pqErrMsg(err)))
}
- out, err := c.GetSubscriber(sub.ID, "", sub.Email)
+ out, err := c.GetSubscriber(id, "", "")
if err != nil {
return models.Subscriber{}, false, err
}
diff --git a/queries/bounces.sql b/queries/bounces.sql
index 7e3ec05e..37ba8d7c 100644
--- a/queries/bounces.sql
+++ b/queries/bounces.sql
@@ -54,14 +54,22 @@ WHERE ($1 = 0 OR bounces.id = $1)
AND ($3 = 0 OR bounces.subscriber_id = $3)
AND ($4 = '' OR bounces.source = $4)
AND ($5 = '' OR bounces.type = $5::bounce_type)
+ AND ($8 OR EXISTS (
+ SELECT 1 FROM subscriber_lists
+ WHERE subscriber_id = bounces.subscriber_id AND list_id = ANY($9::INT[])
+ ))
ORDER BY %order% OFFSET $6 LIMIT (CASE WHEN $7 < 1 THEN NULL ELSE $7 END);
-- name: delete-bounces
-DELETE FROM bounces WHERE CASE WHEN $2 THEN
+DELETE FROM bounces WHERE (CASE WHEN $2 THEN
($3 = 0 OR campaign_id = $3)
AND ($4 = '' OR source = $4)
AND ($5 = '' OR type = $5::bounce_type)
-ELSE id = ANY($1) END;
+ELSE id = ANY($1) END)
+ AND ($6 OR EXISTS (
+ SELECT 1 FROM subscriber_lists
+ WHERE subscriber_id = bounces.subscriber_id AND list_id = ANY($7::INT[])
+ ));
-- name: delete-bounces-by-subscriber
WITH sub AS (
@@ -72,11 +80,15 @@ DELETE FROM bounces WHERE subscriber_id = (SELECT id FROM sub);
-- name: blocklist-bounced-subscribers
WITH subs AS (
SELECT subscriber_id FROM bounces
- WHERE CASE WHEN CARDINALITY($1::INT[]) > 0 THEN id = ANY($1)
+ WHERE (CASE WHEN CARDINALITY($1::INT[]) > 0 THEN id = ANY($1)
ELSE ($2 = 0 OR campaign_id = $2)
AND ($3 = '' OR source = $3)
AND ($4 = '' OR type = $4::bounce_type)
- END
+ END)
+ AND ($5 OR EXISTS (
+ SELECT 1 FROM subscriber_lists
+ WHERE subscriber_id = bounces.subscriber_id AND list_id = ANY($6::INT[])
+ ))
),
b AS (
UPDATE subscribers SET status='blocklisted', updated_at=NOW()
diff --git a/queries/campaigns.sql b/queries/campaigns.sql
index a6366ce1..36b47492 100644
--- a/queries/campaigns.sql
+++ b/queries/campaigns.sql
@@ -164,7 +164,13 @@ LEFT JOIN templates ON (templates.id = (CASE WHEN $2=0 THEN campaigns.template_i
WHERE campaigns.id = $1;
-- name: get-campaign-status
-SELECT id, status, to_send, sent, started_at, updated_at FROM campaigns WHERE status=$1;
+SELECT id, status, to_send, sent, started_at, updated_at FROM campaigns
+WHERE status=$1
+ AND (
+ $2 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = campaigns.id AND list_id = ANY($3::INT[])
+ )
+ );
-- name: campaign-has-lists
-- Returns TRUE if the campaign $1 has any of the lists given in $2.
diff --git a/queries/subscribers.sql b/queries/subscribers.sql
index e8f9224e..f15617e8 100644
--- a/queries/subscribers.sql
+++ b/queries/subscribers.sql
@@ -434,17 +434,24 @@ subs AS (
FROM lists
LEFT JOIN subscriber_lists ON (subscriber_lists.list_id = lists.id)
WHERE subscriber_lists.subscriber_id = (SELECT id FROM prof)
+ AND ($3 OR lists.id = ANY($4::INT[]))
),
views AS (
SELECT subject as campaign, COUNT(subscriber_id) as views FROM campaign_views
LEFT JOIN campaigns ON (campaigns.id = campaign_views.campaign_id)
WHERE subscriber_id = (SELECT id FROM prof)
+ AND ($3 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = campaign_views.campaign_id AND list_id = ANY($4::INT[])
+ ))
GROUP BY campaigns.id ORDER BY campaigns.id
),
clicks AS (
SELECT url, COUNT(subscriber_id) as clicks FROM link_clicks
LEFT JOIN links ON (links.id = link_clicks.link_id)
WHERE subscriber_id = (SELECT id FROM prof)
+ AND ($3 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = link_clicks.campaign_id AND list_id = ANY($4::INT[])
+ ))
GROUP BY links.id ORDER BY links.id
)
SELECT (SELECT email FROM prof) as email,
@@ -473,6 +480,9 @@ WITH views AS (
FROM campaign_views cv
LEFT JOIN campaigns c ON c.id = cv.campaign_id
WHERE cv.subscriber_id = $1
+ AND ($2 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = cv.campaign_id AND list_id = ANY($3::INT[])
+ ))
GROUP BY c.id, c.uuid, c.name, c.subject
ORDER BY last_viewed_at DESC
),
@@ -490,6 +500,9 @@ clicks AS (
LEFT JOIN links l ON l.id = lc.link_id
LEFT JOIN campaigns c ON c.id = lc.campaign_id
WHERE lc.subscriber_id = $1
+ AND ($2 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = lc.campaign_id AND list_id = ANY($3::INT[])
+ ))
GROUP BY l.id, l.url, c.id, c.uuid, c.name, c.subject
ORDER BY last_clicked_at DESC
)
@@ -507,12 +520,18 @@ WITH weeks AS (
SELECT DATE_TRUNC('week', created_at)::DATE AS date, COUNT(*) AS count
FROM campaign_views
WHERE subscriber_id = $1
+ AND ($2 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = campaign_views.campaign_id AND list_id = ANY($3::INT[])
+ ))
AND created_at >= CURRENT_DATE - INTERVAL '12 months' AND created_at <= NOW()
GROUP BY date
), clicks AS (
SELECT DATE_TRUNC('week', created_at)::DATE AS date, COUNT(*) AS count
FROM link_clicks
WHERE subscriber_id = $1
+ AND ($2 OR EXISTS (
+ SELECT 1 FROM campaign_lists WHERE campaign_id = link_clicks.campaign_id AND list_id = ANY($3::INT[])
+ ))
AND created_at >= CURRENT_DATE - INTERVAL '12 months' AND created_at <= NOW()
GROUP BY date
)