Skip to content

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

Refactor user auth models and permission checks.

Kailash Nadh17998fbff5e6
diff --git a/cmd/auth.go b/cmd/auth.go
index de7cf106..dff0d8dd 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -12,7 +12,6 @@ import (
"github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/internal/utils"
- "github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
"github.com/zerodha/simplesessions/v3"
"gopkg.in/volatiletech/null.v6"
@@ -361,8 +360,8 @@ func doLoginSetup(c echo.Context) error {
}
// Create the default "Super Admin".
- r := models.Role{
- Type: models.RoleTypeUser,
+ r := auth.Role{
+ Type: auth.RoleTypeUser,
Name: null.NewString("Super Admin", true),
}
for p := range app.constants.Permissions {
@@ -374,8 +373,8 @@ func doLoginSetup(c echo.Context) error {
}
// Create the super admin user.
- u := models.User{
- Type: models.UserTypeUser,
+ u := auth.User{
+ Type: auth.UserTypeUser,
HasPassword: true,
PasswordLogin: true,
Username: username,
@@ -383,7 +382,7 @@ func doLoginSetup(c echo.Context) error {
Password: null.NewString(password, true),
Email: null.NewString(email, true),
UserRoleID: role.ID,
- Status: models.UserStatusEnabled,
+ Status: auth.UserStatusEnabled,
}
if _, err := app.core.CreateUser(u); err != nil {
return err
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index 69d37820..ffee30b0 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -54,7 +54,7 @@ var (
func handleGetCampaigns(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
pg = app.paginator.NewFromURL(c.Request().URL.Query())
status = c.QueryParams()["status"]
@@ -66,14 +66,14 @@ func handleGetCampaigns(c echo.Context) error {
)
var (
- hasAllPerm = user.HasPerm(models.PermCampaignsGetAll)
+ hasAllPerm = user.HasPerm(auth.PermCampaignsGetAll)
permittedLists []int
)
if !hasAllPerm {
// Either the user has campaigns:get_all permissions and can view all campaigns,
// or the campaigns are filtered by the lists the user has get|manage access to.
- hasAllPerm, permittedLists = user.GetPermittedLists(true, true)
+ hasAllPerm, permittedLists = user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
}
// Query and retrieve the campaigns.
@@ -120,7 +120,7 @@ func handleGetCampaign(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, true, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
return err
}
@@ -151,7 +151,7 @@ func handlePreviewCampaign(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, true, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
return err
}
@@ -278,7 +278,7 @@ func handleUpdateCampaign(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, false, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -326,7 +326,7 @@ func handleUpdateCampaignStatus(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, false, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -359,7 +359,7 @@ func handleUpdateCampaignArchive(c echo.Context) error {
)
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, false, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -401,7 +401,7 @@ func handleDeleteCampaign(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, false, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -467,7 +467,7 @@ func handleTestCampaign(c echo.Context) error {
}
// Check if the user has access to the campaign.
- if err := checkCampaignPerm(id, false, c); err != nil {
+ if err := checkCampaignPerm(auth.PermTypeManage, id, c); err != nil {
return err
}
@@ -707,32 +707,32 @@ func makeOptinCampaignMessage(o campaignReq, app *App) (campaignReq, error) {
}
// checkCampaignPerm checks if the user has get or manage access to the given campaign.
-func checkCampaignPerm(id int, isGet bool, c echo.Context) error {
+func checkCampaignPerm(types auth.PermType, id int, c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
)
- perm := models.PermCampaignsGet
- if isGet {
+ perm := auth.PermCampaignsGet
+ if types&auth.PermTypeGet != 0 {
// It's a get request and there's a blanket get all permission.
- if user.HasPerm(models.PermCampaignsGetAll) {
+ if user.HasPerm(auth.PermCampaignsGetAll) {
return nil
}
} else {
// It's a manage request and there's a blanket manage_all permission.
- if user.HasPerm(models.PermCampaignsManageAll) {
+ if user.HasPerm(auth.PermCampaignsManageAll) {
return nil
}
- perm = models.PermCampaignsManage
+ perm = auth.PermCampaignsManage
}
// There are no *_all campaign permissions. Instead, check if the user access
// blanket get_all/manage_all list permissions. If yes, then the user can access
// 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(true, true); !hasAllPerm {
+ if hasAllPerm, permittedListIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage); !hasAllPerm {
if ok, err := app.core.CampaignHasLists(id, permittedListIDs); err != nil {
return err
} else if !ok {
diff --git a/cmd/init.go b/cmd/init.go
index 82caea42..7708518c 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -977,7 +977,7 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) (bool, *auth.Auth) {
c.SetCookie(cookie)
return nil
},
- GetUser: func(id int) (models.User, error) {
+ GetUser: func(id int) (auth.User, error) {
return co.GetUser(id, "", "")
},
}
@@ -1005,15 +1005,15 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) (bool, *auth.Auth) {
password = ko.String("app.admin_password")
)
if len(username) > 2 && len(password) > 6 {
- u := models.User{
+ u := auth.User{
Username: username,
Password: null.String{Valid: true, String: password},
PasswordLogin: true,
HasPassword: true,
- Status: models.UserStatusEnabled,
- Type: models.UserTypeAPI,
+ Status: auth.UserStatusEnabled,
+ Type: auth.UserTypeAPI,
}
- u.UserRole.ID = models.SuperAdminRoleID
+ u.UserRole.ID = auth.SuperAdminRoleID
a.CacheAPIUser(u)
lo.Println(`WARNING: Remove the admin_username and admin_password fields from the TOML configuration file. If you are using APIs, create and use new credentials. Users are now managed via the Admin -> Settings -> Users dashboard.`)
diff --git a/cmd/lists.go b/cmd/lists.go
index dcbcff96..aca7c59e 100644
--- a/cmd/lists.go
+++ b/cmd/lists.go
@@ -14,7 +14,7 @@ import (
func handleGetLists(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
pg = app.paginator.NewFromURL(c.Request().URL.Query())
query = strings.TrimSpace(c.FormValue("query"))
@@ -29,7 +29,7 @@ func handleGetLists(c echo.Context) error {
)
// Get the list IDs (or blanket permission) the user has access to.
- hasAllPerm, permittedIDs := user.GetPermittedLists(true, false)
+ hasAllPerm, permittedIDs := user.GetPermittedLists(auth.PermTypeGet)
// Minimal query simply returns the list of all lists without JOIN subscriber counts. This is fast.
if minimal {
@@ -69,7 +69,9 @@ func handleGetLists(c echo.Context) error {
// It's permission checked by the listPerm middleware.
func handleGetList(c echo.Context) error {
var (
- app = c.Get("app").(*App)
+ app = c.Get("app").(*App)
+ user = c.Get(auth.UserKey).(auth.User)
+
id, _ = strconv.Atoi(c.Param("id"))
)
@@ -78,7 +80,7 @@ func handleGetList(c echo.Context) error {
}
// Check if the user has access to the list.
- if err := checkListPerm(true, false, c, id); err != nil {
+ if err := user.HasListPerm(auth.PermTypeGet, id); err != nil {
return err
}
@@ -119,7 +121,9 @@ func handleCreateList(c echo.Context) error {
// It's permission checked by the listPerm middleware.
func handleUpdateList(c echo.Context) error {
var (
- app = c.Get("app").(*App)
+ app = c.Get("app").(*App)
+ user = c.Get(auth.UserKey).(auth.User)
+
id, _ = strconv.Atoi(c.Param("id"))
)
@@ -128,7 +132,7 @@ func handleUpdateList(c echo.Context) error {
}
// Check if the user has access to the list.
- if err := checkListPerm(false, true, c, id); err != nil {
+ if err := user.HasListPerm(auth.PermTypeManage, id); err != nil {
return err
}
@@ -155,7 +159,9 @@ func handleUpdateList(c echo.Context) error {
// It's permission checked by the listPerm middleware.
func handleDeleteLists(c echo.Context) error {
var (
- app = c.Get("app").(*App)
+ app = c.Get("app").(*App)
+ user = c.Get(auth.UserKey).(auth.User)
+
id, _ = strconv.ParseInt(c.Param("id"), 10, 64)
ids []int
)
@@ -169,7 +175,7 @@ func handleDeleteLists(c echo.Context) error {
}
// Check if the user has access to the list.
- if err := checkListPerm(true, false, c, ids...); err != nil {
+ if err := user.HasListPerm(auth.PermTypeManage, ids...); err != nil {
return err
}
@@ -180,35 +186,3 @@ func handleDeleteLists(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
}
-
-// checkListPerm checks if the user has get or manage access to the given list.
-func checkListPerm(get, manage bool, c echo.Context, listIDs ...int) error {
- var (
- app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
- )
-
- var permAll, perm string
- if get {
- permAll = models.PermListGetAll
- perm = models.PermListGet
- } else if manage {
- permAll = models.PermListManageAll
- perm = models.PermListManage
- }
-
- // Check if the user has permissions for all lists or the specific list.
- if user.HasPerm(permAll) {
- return nil
- }
-
- for _, id := range listIDs {
- if id > 0 {
- if user.HasListPerm(id, perm) {
- return nil
- }
- }
- }
-
- return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.permissionDenied", "name", "list"))
-}
diff --git a/cmd/roles.go b/cmd/roles.go
index c28423f6..f4376659 100644
--- a/cmd/roles.go
+++ b/cmd/roles.go
@@ -6,7 +6,7 @@ import (
"strconv"
"strings"
- "github.com/knadh/listmonk/models"
+ "github.com/knadh/listmonk/internal/auth"
"github.com/labstack/echo/v4"
)
@@ -44,7 +44,7 @@ func handleGeListRoles(c echo.Context) error {
func handleCreateUserRole(c echo.Context) error {
var (
app = c.Get("app").(*App)
- r = models.Role{}
+ r = auth.Role{}
)
if err := c.Bind(&r); err != nil {
@@ -67,7 +67,7 @@ func handleCreateUserRole(c echo.Context) error {
func handleCreateListRole(c echo.Context) error {
var (
app = c.Get("app").(*App)
- r = models.ListRole{}
+ r = auth.ListRole{}
)
if err := c.Bind(&r); err != nil {
@@ -98,7 +98,7 @@ func handleUpdateUserRole(c echo.Context) error {
}
// Incoming params.
- var r models.Role
+ var r auth.Role
if err := c.Bind(&r); err != nil {
return err
}
@@ -135,7 +135,7 @@ func handleUpdateListRole(c echo.Context) error {
}
// Incoming params.
- var r models.ListRole
+ var r auth.ListRole
if err := c.Bind(&r); err != nil {
return err
}
@@ -183,7 +183,7 @@ func handleDeleteRole(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
}
-func validateUserRole(r models.Role, app *App) error {
+func validateUserRole(r auth.Role, app *App) error {
// Validate fields.
if !strHasLen(r.Name.String, 1, stdInputMaxLen) {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "name"))
@@ -198,7 +198,7 @@ func validateUserRole(r models.Role, app *App) error {
return nil
}
-func validateListRole(r models.ListRole, app *App) error {
+func validateListRole(r auth.ListRole, app *App) error {
// Validate fields.
if !strHasLen(r.Name.String, 1, stdInputMaxLen) {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "name"))
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index 1a25eb59..a26dd2dc 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -56,17 +56,19 @@ func handleGetSubscriber(c echo.Context) error {
var (
app = c.Get("app").(*App)
id, _ = strconv.Atoi(c.Param("id"))
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
)
if id < 1 {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
}
+ // Check if the user has access to at least one of the lists on the subscriber.
if err := hasSubPerm(user, []int{id}, app); err != nil {
return err
}
+ // Fetch the subscriber from the DB.
out, err := app.core.GetSubscriber(id, "", "")
if err != nil {
return err
@@ -79,7 +81,7 @@ func handleGetSubscriber(c echo.Context) error {
func handleQuerySubscribers(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
pg = app.paginator.NewFromURL(c.Request().URL.Query())
// The "WHERE ?" bit.
@@ -114,7 +116,7 @@ func handleQuerySubscribers(c echo.Context) error {
func handleExportSubscribers(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
// The "WHERE ?" bit.
query = sanitizeSQLExp(c.FormValue("query"))
@@ -183,7 +185,7 @@ loop:
func handleCreateSubscriber(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
req subimporter.SubReq
)
@@ -200,7 +202,7 @@ func handleCreateSubscriber(c echo.Context) error {
}
// Filter lists against the current user's permitted lists.
- listIDs := user.FilterListsByPerm(req.Lists, false, true)
+ listIDs := user.FilterListsByPerm(auth.PermTypeManage, req.Lists)
// Insert the subscriber into the DB.
sub, _, err := app.core.InsertSubscriber(req.Subscriber, listIDs, nil, req.PreconfirmSubs)
@@ -215,7 +217,7 @@ func handleCreateSubscriber(c echo.Context) error {
func handleUpdateSubscriber(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
id, _ = strconv.Atoi(c.Param("id"))
req struct {
@@ -245,7 +247,7 @@ func handleUpdateSubscriber(c echo.Context) error {
}
// Filter lists against the current user's permitted lists.
- listIDs := user.FilterListsByPerm(req.Lists, false, true)
+ listIDs := user.FilterListsByPerm(auth.PermTypeManage, req.Lists)
out, _, err := app.core.UpdateSubscriberWithLists(id, req.Subscriber, listIDs, nil, req.PreconfirmSubs, true)
if err != nil {
@@ -324,7 +326,7 @@ func handleBlocklistSubscribers(c echo.Context) error {
func handleManageSubscriberLists(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
pID = c.Param("id")
subIDs []int
@@ -355,7 +357,7 @@ func handleManageSubscriberLists(c echo.Context) error {
}
// Filter lists against the current user's permitted lists.
- listIDs := user.FilterListsByPerm(req.TargetListIDs, false, true)
+ listIDs := user.FilterListsByPerm(auth.PermTypeManage, req.TargetListIDs)
// Action.
var err error
@@ -466,7 +468,7 @@ func handleBlocklistSubscribersByQuery(c echo.Context) error {
func handleManageSubscriberListsByQuery(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
req subQueryReq
)
@@ -480,8 +482,8 @@ func handleManageSubscriberListsByQuery(c echo.Context) error {
}
// Filter lists against the current user's permitted lists.
- sourceListIDs := user.FilterListsByPerm(req.ListIDs, false, true)
- targetListIDs := user.FilterListsByPerm(req.TargetListIDs, false, true)
+ sourceListIDs := user.FilterListsByPerm(auth.PermTypeManage, req.ListIDs)
+ targetListIDs := user.FilterListsByPerm(auth.PermTypeManage, req.TargetListIDs)
// Action.
var err error
@@ -671,16 +673,16 @@ func sendOptinConfirmationHook(app *App) func(sub models.Subscriber, listIDs []i
// hasSubPerm checks whether the current user has permission to access the given list
// of subscriber IDs.
-func hasSubPerm(u models.User, subIDs []int, app *App) error {
- if u.UserRoleID == models.SuperAdminRoleID {
- return nil
- }
+func hasSubPerm(u auth.User, subIDs []int, app *App) error {
+ allPerm, listIDs := u.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
- if _, ok := u.PermissionsMap[models.PermSubscribersGetAll]; ok {
+ // User has blanket get_all|manage_all permission.
+ if allPerm {
return nil
}
- res, err := app.core.HasSubscriberLists(subIDs, u.GetListIDs)
+ // Check whether the subscribers have the list IDs permitted to the user.
+ res, err := app.core.HasSubscriberLists(subIDs, listIDs)
if err != nil {
return err
}
@@ -694,7 +696,7 @@ func hasSubPerm(u models.User, subIDs []int, app *App) error {
return nil
}
-func filterListQueryByPerm(qp url.Values, user models.User, app *App) ([]int, error) {
+func filterListQueryByPerm(qp url.Values, user auth.User, app *App) ([]int, error) {
var listIDs []int
// If there are incoming list query params, filter them by permission.
@@ -704,13 +706,13 @@ func filterListQueryByPerm(qp url.Values, user models.User, app *App) ([]int, er
return nil, echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
}
- listIDs = user.FilterListsByPerm(ids, true, true)
+ listIDs = user.FilterListsByPerm(auth.PermTypeGet|auth.PermTypeManage, ids)
}
// There are no incoming params. If the user doesn't have permission to get all subscribers,
// filter by the lists they have access to.
if len(listIDs) == 0 {
- if _, ok := user.PermissionsMap[models.PermSubscribersGetAll]; !ok {
+ if _, ok := user.PermissionsMap[auth.PermSubscribersGetAll]; !ok {
if len(user.GetListIDs) > 0 {
listIDs = user.GetListIDs
} else {
diff --git a/cmd/users.go b/cmd/users.go
index 0ca78c02..aa4a8dc1 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -9,7 +9,6 @@ import (
"github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/internal/core"
"github.com/knadh/listmonk/internal/utils"
- "github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
"gopkg.in/volatiletech/null.v6"
)
@@ -59,7 +58,7 @@ func handleGetUsers(c echo.Context) error {
func handleCreateUser(c echo.Context) error {
var (
app = c.Get("app").(*App)
- u = models.User{}
+ u = auth.User{}
)
if err := c.Bind(&u); err != nil {
@@ -77,7 +76,7 @@ func handleCreateUser(c echo.Context) error {
if !reUsername.MatchString(u.Username) {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
- if u.Type != models.UserTypeAPI {
+ if u.Type != auth.UserTypeAPI {
if !utils.ValidateEmail(email) {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
@@ -99,7 +98,7 @@ func handleCreateUser(c echo.Context) error {
if err != nil {
return err
}
- if user.Type != models.UserTypeAPI {
+ if user.Type != auth.UserTypeAPI {
user.Password = null.String{}
}
@@ -123,7 +122,7 @@ func handleUpdateUser(c echo.Context) error {
}
// Incoming params.
- var u models.User
+ var u auth.User
if err := c.Bind(&u); err != nil {
return err
}
@@ -141,7 +140,7 @@ func handleUpdateUser(c echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
}
- if u.Type != models.UserTypeAPI {
+ if u.Type != auth.UserTypeAPI {
if !utils.ValidateEmail(email) {
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
}
@@ -224,7 +223,7 @@ func handleDeleteUsers(c echo.Context) error {
// handleGetUserProfile fetches the uesr profile for the currently logged in user.
func handleGetUserProfile(c echo.Context) error {
var (
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
)
user.Password.String = ""
user.Password.Valid = false
@@ -236,10 +235,10 @@ func handleGetUserProfile(c echo.Context) error {
func handleUpdateUserProfile(c echo.Context) error {
var (
app = c.Get("app").(*App)
- user = c.Get(auth.UserKey).(models.User)
+ user = c.Get(auth.UserKey).(auth.User)
)
- u := models.User{}
+ u := auth.User{}
if err := c.Bind(&u); err != nil {
return err
}
@@ -280,13 +279,13 @@ func cacheUsers(co *core.Core, a *auth.Auth) (bool, error) {
}
hasUser := false
- apiUsers := make([]models.User, 0, len(allUsers))
+ apiUsers := make([]auth.User, 0, len(allUsers))
for _, u := range allUsers {
- if u.Type == models.UserTypeAPI && u.Status == models.UserStatusEnabled {
+ if u.Type == auth.UserTypeAPI && u.Status == auth.UserStatusEnabled {
apiUsers = append(apiUsers, u)
}
- if u.Type == models.UserTypeUser {
+ if u.Type == auth.UserTypeUser {
hasUser = true
}
}
diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js
index 8abb08b9..a083ff60 100644
--- a/frontend/src/api/index.js
+++ b/frontend/src/api/index.js
@@ -443,87 +443,87 @@ export const deleteGCSubscriptions = async (beforeDate) => http.delete(
export const getUsers = () => http.get(
'/api/users',
{
- loading: models.users,
- store: models.users,
+ loading: auth.Users,
+ store: auth.Users,
},
);
export const queryUsers = () => http.get(
'/api/users',
{
- loading: models.users,
- store: models.users,
+ loading: auth.Users,
+ store: auth.Users,
},
);
export const getUser = async (id) => http.get(
`/api/users/${id}`,
- { loading: models.users },
+ { loading: auth.Users },
);
export const createUser = (data) => http.post(
'/api/users',
data,
- { loading: models.users },
+ { loading: auth.Users },
);
export const updateUser = (data) => http.put(
`/api/users/${data.id}`,
data,
- { loading: models.users },
+ { loading: auth.Users },
);
export const deleteUser = (id) => http.delete(
`/api/users/${id}`,
- { loading: models.users },
+ { loading: auth.Users },
);
export const getUserProfile = () => http.get(
'/api/profile',
- { loading: models.users, store: models.profile },
+ { loading: auth.Users, store: models.profile },
);
export const updateUserProfile = (data) => http.put(
'/api/profile',
data,
- { loading: models.users, store: models.profile },
+ { loading: auth.Users, store: models.profile },
);
export const getUserRoles = async () => http.get(
'/api/roles/users',
- { loading: models.userRoles, store: models.userRoles },
+ { loading: auth.UserRoles, store: auth.UserRoles },
);
export const getListRoles = async () => http.get(
'/api/roles/lists',
- { loading: models.listRoles, store: models.listRoles },
+ { loading: auth.ListRoles, store: auth.ListRoles },
);
export const createUserRole = (data) => http.post(
'/api/roles/users',
data,
- { loading: models.userRoles },
+ { loading: auth.UserRoles },
);
export const createListRole = (data) => http.post(
'/api/roles/lists',
data,
- { loading: models.listRoles },
+ { loading: auth.ListRoles },
);
export const updateUserRole = (data) => http.put(
`/api/roles/users/${data.id}`,
data,
- { loading: models.userRoles },
+ { loading: auth.UserRoles },
);
export const updateListRole = (data) => http.put(
`/api/roles/lists/${data.id}`,
data,
- { loading: models.userRoles },
+ { loading: auth.UserRoles },
);
export const deleteRole = (id) => http.delete(
`/api/roles/${id}`,
- { loading: models.userRoles },
+ { loading: auth.UserRoles },
);
diff --git a/frontend/src/store/index.js b/frontend/src/store/index.js
index a5bfeb3d..f2c6e901 100644
--- a/frontend/src/store/index.js
+++ b/frontend/src/store/index.js
@@ -41,10 +41,10 @@ export default new Vuex.Store({
[models.campaigns]: (state) => state[models.campaigns],
[models.media]: (state) => state[models.media],
[models.templates]: (state) => state[models.templates],
- [models.users]: (state) => state[models.users],
+ [auth.Users]: (state) => state[auth.Users],
[models.profile]: (state) => state[models.profile],
- [models.userRoles]: (state) => state[models.userRoles],
- [models.listRoles]: (state) => state[models.listRoles],
+ [auth.UserRoles]: (state) => state[auth.UserRoles],
+ [auth.ListRoles]: (state) => state[auth.ListRoles],
[models.settings]: (state) => state[models.settings],
[models.serverConfig]: (state) => state[models.serverConfig],
[models.logs]: (state) => state[models.logs],
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index bbab01d4..154ffd4c 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -14,19 +14,12 @@ import (
"time"
"github.com/coreos/go-oidc/v3/oidc"
- "github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
"github.com/zerodha/simplesessions/stores/postgres/v3"
"github.com/zerodha/simplesessions/v3"
"golang.org/x/oauth2"
)
-const (
- // UserKey is the key on which the User profile is set on echo handlers.
- UserKey = "auth_user"
- SessionKey = "auth_session"
-)
-
const (
sessTypeNative = "native"
sessTypeOIDC = "oidc"
@@ -62,11 +55,11 @@ type Config struct {
type Callbacks struct {
SetCookie func(cookie *http.Cookie, w interface{}) error
GetCookie func(name string, r interface{}) (*http.Cookie, error)
- GetUser func(id int) (models.User, error)
+ GetUser func(id int) (User, error)
}
type Auth struct {
- apiUsers map[string]models.User
+ apiUsers map[string]User
sync.RWMutex
cfg Config
@@ -85,7 +78,7 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) {
cb: cb,
log: lo,
- apiUsers: map[string]models.User{},
+ apiUsers: map[string]User{},
}
// Initialize OIDC.
@@ -141,9 +134,9 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) {
// CacheAPIUsers caches API users for authenticating requests. It wipes
// the existing cache every time and is meant for syncing all API users
// in the database in one shot.
-func (o *Auth) CacheAPIUsers(users []models.User) {
+func (o *Auth) CacheAPIUsers(users []User) {
o.Lock()
- o.apiUsers = map[string]models.User{}
+ o.apiUsers = map[string]User{}
for _, u := range users {
o.apiUsers[u.Username] = u
@@ -152,20 +145,20 @@ func (o *Auth) CacheAPIUsers(users []models.User) {
}
// CacheAPIUser caches an API user for authenticating requests.
-func (o *Auth) CacheAPIUser(u models.User) {
+func (o *Auth) CacheAPIUser(u User) {
o.Lock()
o.apiUsers[u.Username] = u
o.Unlock()
}
// GetAPIToken validates an API user+token.
-func (o *Auth) GetAPIToken(user string, token string) (models.User, bool) {
+func (o *Auth) GetAPIToken(user string, token string) (User, bool) {
o.RLock()
t, ok := o.apiUsers[user]
o.RUnlock()
if !ok || subtle.ConstantTimeCompare([]byte(t.Password.String), []byte(token)) != 1 {
- return models.User{}, false
+ return User{}, false
}
return t, true
@@ -274,14 +267,14 @@ func (o *Auth) Middleware(next echo.HandlerFunc) echo.HandlerFunc {
func (o *Auth) Perm(next echo.HandlerFunc, perms ...string) echo.HandlerFunc {
return func(c echo.Context) error {
- u, ok := c.Get(UserKey).(models.User)
+ u, ok := c.Get(UserKey).(User)
if !ok {
c.Set(UserKey, echo.NewHTTPError(http.StatusForbidden, "invalid session"))
return next(c)
}
// If the current user is a Super Admin user, do no checks.
- if u.UserRole.ID == models.SuperAdminRoleID {
+ if u.UserRole.ID == SuperAdminRoleID {
return next(c)
}
@@ -306,7 +299,7 @@ func (o *Auth) Perm(next echo.HandlerFunc, perms ...string) echo.HandlerFunc {
}
// SaveSession creates and sets a session (post successful login/auth).
-func (o *Auth) SaveSession(u models.User, oidcToken string, c echo.Context) error {
+func (o *Auth) SaveSession(u User, oidcToken string, c echo.Context) error {
sess, err := o.sess.NewSession(c, c)
if err != nil {
o.log.Printf("error creating login session: %v", err)
@@ -321,24 +314,24 @@ func (o *Auth) SaveSession(u models.User, oidcToken string, c echo.Context) erro
return nil
}
-func (o *Auth) validateSession(c echo.Context) (*simplesessions.Session, models.User, error) {
+func (o *Auth) validateSession(c echo.Context) (*simplesessions.Session, User, error) {
// Cookie session.
sess, err := o.sess.Acquire(nil, c, c)
if err != nil {
- return nil, models.User{}, echo.NewHTTPError(http.StatusForbidden, err.Error())
+ return nil, User{}, echo.NewHTTPError(http.StatusForbidden, err.Error())
}
// Get the session variables.
vars, err := sess.GetMulti("user_id", "oidc_token")
if err != nil {
- return nil, models.User{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
+ return nil, User{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
// Validate the user ID in the session.
userID, err := o.sessStore.Int(vars["user_id"], nil)
if err != nil || userID < 1 {
o.log.Printf("error fetching session user ID: %v", err)
- return nil, models.User{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
+ return nil, User{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
// Fetch user details from the database.
diff --git a/models/users.go b/internal/auth/models.go
similarity index 60%
rename from models/users.go
rename to internal/auth/models.go
index 8aabd905..4276fd2d 100644
--- a/models/users.go
+++ b/internal/auth/models.go
@@ -1,14 +1,84 @@
-package models
+package auth
import (
"encoding/json"
+ "net/http"
+ "github.com/labstack/echo/v4"
"github.com/lib/pq"
null "gopkg.in/volatiletech/null.v6"
)
-// SuperAdminRoleID is the database ID of the primordial super admin role.
-const SuperAdminRoleID = 1
+var ErrPermDenied = echo.NewHTTPError(http.StatusForbidden, "permission denied")
+
+// PermType indicates a generic permission type which is either get (read) or manage (write).
+type PermType uint8
+
+const (
+ PermTypeGet PermType = 1 << iota
+ PermTypeManage
+)
+
+const (
+ // UserKey is the key on which the User profile is set on echo handlers.
+ UserKey = "auth_user"
+ SessionKey = "auth_session"
+)
+
+const (
+ // SuperAdminRoleID is the database ID of the primordial super admin role.
+ SuperAdminRoleID = 1
+
+ // User.
+ UserTypeUser = "user"
+ UserTypeAPI = "api"
+ UserStatusEnabled = "enabled"
+ UserStatusDisabled = "disabled"
+
+ // Role.
+ RoleTypeUser = "user"
+ RoleTypeList = "list"
+)
+
+// List of all granular permissions.
+const (
+ PermListGetAll = "lists:get_all"
+ PermListManageAll = "lists:manage_all"
+ PermListManage = "list:manage"
+ PermListGet = "list:get"
+ PermSubscribersGet = "subscribers:get"
+ PermSubscribersGetAll = "subscribers:get_all"
+ PermSubscribersManage = "subscribers:manage"
+ PermSubscribersImport = "subscribers:import"
+ PermSubscribersSqlQuery = "subscribers:sql_query"
+ PermTxSend = "tx:send"
+ PermCampaignsGet = "campaigns:get"
+ PermCampaignsGetAll = "campaigns:get_all"
+ PermCampaignsGetAnalytics = "campaigns:get_analytics"
+ PermCampaignsManage = "campaigns:manage"
+ PermCampaignsManageAll = "campaigns:manage_all"
+ PermBouncesGet = "bounces:get"
+ PermBouncesManage = "bounces:manage"
+ PermWebhooksPostBounce = "webhooks:post_bounce"
+ PermMediaGet = "media:get"
+ PermMediaManage = "media:manage"
+ PermTemplatesGet = "templates:get"
+ PermTemplatesManage = "templates:manage"
+ PermUsersGet = "users:get"
+ PermUsersManage = "users:manage"
+ PermRolesGet = "roles:get"
+ PermRolesManage = "roles:manage"
+ PermSettingsGet = "settings:get"
+ PermSettingsManage = "settings:manage"
+ PermSettingsMaintain = "settings:maintain"
+)
+
+// Base holds common fields shared across models.
+type Base struct {
+ ID int `db:"id" json:"id"`
+ CreatedAt null.Time `db:"created_at" json:"created_at"`
+ UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
+}
// User represents an admin user.
type User struct {
@@ -95,7 +165,40 @@ func (u *User) HasPerm(perm string) bool {
return ok
}
-func (u *User) HasListPerm(listID int, perm string) bool {
+// HasListPerm checks if the user has get or manage access to the given list.
+// perm is either PermGet or PermManage.
+func (u *User) HasListPerm(types PermType, listIDs ...int) error {
+ var permAll, perm string
+
+ if types == 0 {
+ return ErrPermDenied
+ }
+
+ if types&PermTypeGet != 0 {
+ permAll = PermListGetAll
+ perm = PermListGet
+ } else if types&PermTypeManage != 0 {
+ permAll = PermListManageAll
+ perm = PermListManage
+ }
+
+ // Check if the user has permissions for all lists or the specific list.
+ if u.HasPerm(permAll) {
+ return nil
+ }
+
+ for _, id := range listIDs {
+ if id > 0 {
+ if u.hasListPerm(perm, id) {
+ return nil
+ }
+ }
+ }
+
+ return ErrPermDenied
+}
+
+func (u *User) hasListPerm(perm string, listID int) bool {
// Short-circuit if the user is the primordial super admin.
if u.UserRoleID == SuperAdminRoleID {
return true
@@ -113,12 +216,21 @@ func (u *User) HasListPerm(listID int, perm string) bool {
// 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(get, manage bool) (bool, []int) {
+func (u *User) GetPermittedLists(types PermType) (bool, []int) {
+ if types == 0 {
+ return false, nil
+ }
+
// Short-circuit if the user is the primordial super admin.
if u.UserRoleID == SuperAdminRoleID {
return true, nil
}
+ var (
+ get = types&PermTypeGet != 0
+ manage = types&PermTypeManage != 0
+ )
+
// If the user has the list:get_all or list:manage_all permission, no
// further checks are required.
if get {
@@ -153,7 +265,16 @@ func (u *User) GetPermittedLists(get, manage bool) (bool, []int) {
}
// FilterListsByPerm returns list IDs filtered by either of the given perms.
-func (u *User) FilterListsByPerm(listIDs []int, get, manage bool) []int {
+func (u *User) FilterListsByPerm(types PermType, listIDs []int) []int {
+ if types == 0 {
+ return nil
+ }
+
+ var (
+ get = types&PermTypeGet != 0
+ manage = types&PermTypeManage != 0
+ )
+
// If the user has full list management permission,
// no further checks are required.
if get {
@@ -168,8 +289,6 @@ func (u *User) FilterListsByPerm(listIDs []int, get, manage bool) []int {
}
out := make([]int, 0, len(listIDs))
-
- // Go through every list ID.
for _, id := range listIDs {
// Check if it exists in the map.
if l, ok := u.ListPermissionsMap[id]; ok {
diff --git a/internal/core/roles.go b/internal/core/roles.go
index 346c91f8..681e1502 100644
--- a/internal/core/roles.go
+++ b/internal/core/roles.go
@@ -4,14 +4,14 @@ import (
"encoding/json"
"net/http"
- "github.com/knadh/listmonk/models"
+ "github.com/knadh/listmonk/internal/auth"
"github.com/labstack/echo/v4"
"github.com/lib/pq"
)
// GetRoles retrieves all roles.
-func (c *Core) GetRoles() ([]models.Role, error) {
- out := []models.Role{}
+func (c *Core) GetRoles() ([]auth.Role, error) {
+ out := []auth.Role{}
if err := c.q.GetUserRoles.Select(&out); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))
@@ -21,8 +21,8 @@ func (c *Core) GetRoles() ([]models.Role, error) {
}
// GetListRoles retrieves all list roles.
-func (c *Core) GetListRoles() ([]models.ListRole, error) {
- out := []models.ListRole{}
+func (c *Core) GetListRoles() ([]auth.ListRole, error) {
+ out := []auth.ListRole{}
if err := c.q.GetListRoles.Select(&out); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))
@@ -43,10 +43,10 @@ func (c *Core) GetListRoles() ([]models.ListRole, error) {
}
// CreateRole creates a new role.
-func (c *Core) CreateRole(r models.Role) (models.Role, error) {
- var out models.Role
+func (c *Core) CreateRole(r auth.Role) (auth.Role, error) {
+ var out auth.Role
- if err := c.q.CreateRole.Get(&out, r.Name, models.RoleTypeUser, pq.Array(r.Permissions)); err != nil {
+ if err := c.q.CreateRole.Get(&out, r.Name, auth.RoleTypeUser, pq.Array(r.Permissions)); err != nil {
return out, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorCreating", "name", "{users.role}", "error", pqErrMsg(err)))
}
@@ -55,10 +55,10 @@ func (c *Core) CreateRole(r models.Role) (models.Role, error) {
}
// CreateListRole creates a new list role.
-func (c *Core) CreateListRole(r models.ListRole) (models.ListRole, error) {
- var out models.ListRole
+func (c *Core) CreateListRole(r auth.ListRole) (auth.ListRole, error) {
+ var out auth.ListRole
- if err := c.q.CreateRole.Get(&out, r.Name, models.RoleTypeList, pq.Array([]string{})); err != nil {
+ if err := c.q.CreateRole.Get(&out, r.Name, auth.RoleTypeList, pq.Array([]string{})); err != nil {
return out, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorCreating", "name", "{users.role}", "error", pqErrMsg(err)))
}
@@ -72,7 +72,7 @@ func (c *Core) CreateListRole(r models.ListRole) (models.ListRole, error) {
}
// UpsertListPermissions upserts permission for a role.
-func (c *Core) UpsertListPermissions(roleID int, lp []models.ListPermission) error {
+func (c *Core) UpsertListPermissions(roleID int, lp []auth.ListPermission) error {
var (
listIDs = make([]int, 0, len(lp))
listPerms = make([][]string, 0, len(lp))
@@ -113,8 +113,8 @@ func (c *Core) DeleteListPermission(roleID, listID int) error {
}
// UpdateUserRole updates a given role.
-func (c *Core) UpdateUserRole(id int, r models.Role) (models.Role, error) {
- var out models.Role
+func (c *Core) UpdateUserRole(id int, r auth.Role) (auth.Role, error) {
+ var out auth.Role
if err := c.q.UpdateRole.Get(&out, id, r.Name, pq.Array(r.Permissions)); err != nil {
return out, echo.NewHTTPError(http.StatusInternalServerError,
@@ -129,8 +129,8 @@ func (c *Core) UpdateUserRole(id int, r models.Role) (models.Role, error) {
}
// UpdateListRole updates a given role.
-func (c *Core) UpdateListRole(id int, r models.ListRole) (models.ListRole, error) {
- var out models.ListRole
+func (c *Core) UpdateListRole(id int, r auth.ListRole) (auth.ListRole, error) {
+ var out auth.ListRole
if err := c.q.UpdateRole.Get(&out, id, r.Name, pq.Array([]string{})); err != nil {
return out, echo.NewHTTPError(http.StatusInternalServerError,
diff --git a/internal/core/subscribers.go b/internal/core/subscribers.go
index 5415ef4d..7d354222 100644
--- a/internal/core/subscribers.go
+++ b/internal/core/subscribers.go
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/gofrs/uuid/v5"
+ "github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
"github.com/lib/pq"
@@ -271,7 +272,7 @@ func (c *Core) InsertSubscriber(sub models.Subscriber, listIDs []int, listUUIDs
subStatus = models.SubscriptionStatusConfirmed
}
if sub.Status == "" {
- sub.Status = models.UserStatusEnabled
+ sub.Status = auth.UserStatusEnabled
}
// For pq.Array()
diff --git a/internal/core/users.go b/internal/core/users.go
index a2c64570..dcb3f1fb 100644
--- a/internal/core/users.go
+++ b/internal/core/users.go
@@ -5,15 +5,15 @@ import (
"encoding/json"
"net/http"
+ "github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/internal/utils"
- "github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
"github.com/lib/pq"
"gopkg.in/volatiletech/null.v6"
)
-func (c *Core) GetUsers() ([]models.User, error) {
- out := []models.User{}
+func (c *Core) GetUsers() ([]auth.User, error) {
+ out := []auth.User{}
if err := c.q.GetUsers.Select(&out); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.users}", "error", pqErrMsg(err)))
@@ -23,8 +23,8 @@ func (c *Core) GetUsers() ([]models.User, error) {
}
// GetUser retrieves a specific user based on any one given identifier.
-func (c *Core) GetUser(id int, username, email string) (models.User, error) {
- var out models.User
+func (c *Core) GetUser(id int, username, email string) (auth.User, error) {
+ var out auth.User
if err := c.q.GetUser.Get(&out, id, username, email); err != nil {
if err == sql.ErrNoRows {
return out, echo.NewHTTPError(http.StatusInternalServerError,
@@ -36,20 +36,20 @@ func (c *Core) GetUser(id int, username, email string) (models.User, error) {
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.users}", "error", pqErrMsg(err)))
}
- return c.setupUserFields([]models.User{out})[0], nil
+ return c.setupUserFields([]auth.User{out})[0], nil
}
// CreateUser creates a new user.
-func (c *Core) CreateUser(u models.User) (models.User, error) {
+func (c *Core) CreateUser(u auth.User) (auth.User, error) {
var id int
// If it's an API user, generate a random token for password
// and set the e-mail to default.
- if u.Type == models.UserTypeAPI {
+ if u.Type == auth.UserTypeAPI {
// Generate a random admin password.
tk, err := utils.GenerateRandomString(32)
if err != nil {
- return models.User{}, err
+ return auth.User{}, err
}
u.Email = null.String{String: u.Username + "@api", Valid: true}
@@ -58,13 +58,13 @@ func (c *Core) CreateUser(u models.User) (models.User, error) {
}
if err := c.q.CreateUser.Get(&id, u.Username, u.PasswordLogin, u.Password, u.Email, u.Name, u.Type, u.UserRoleID, u.ListRoleID, u.Status); err != nil {
- return models.User{}, echo.NewHTTPError(http.StatusInternalServerError,
+ return auth.User{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorCreating", "name", "{globals.terms.user}", "error", pqErrMsg(err)))
}
// Hide the password field in the response except for when the user type is an API token,
// where the frontend shows the token on the UI just once.
- if u.Type != models.UserTypeAPI {
+ if u.Type != auth.UserTypeAPI {
u.Password = null.String{Valid: false}
}
@@ -73,7 +73,7 @@ func (c *Core) CreateUser(u models.User) (models.User, error) {
}
// UpdateUser updates a given user.
-func (c *Core) UpdateUser(id int, u models.User) (models.User, error) {
+func (c *Core) UpdateUser(id int, u auth.User) (auth.User, error) {
listRoleID := 0
if u.ListRoleID == nil {
listRoleID = -1
@@ -83,12 +83,12 @@ func (c *Core) UpdateUser(id int, u models.User) (models.User, error) {
res, err := c.q.UpdateUser.Exec(id, u.Username, u.PasswordLogin, u.Password, u.Email, u.Name, u.Type, u.UserRoleID, listRoleID, u.Status)
if err != nil {
- return models.User{}, echo.NewHTTPError(http.StatusInternalServerError,
+ return auth.User{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorUpdating", "name", "{globals.terms.user}", "error", pqErrMsg(err)))
}
if n, _ := res.RowsAffected(); n == 0 {
- return models.User{}, echo.NewHTTPError(http.StatusBadRequest, c.i18n.T("users.needSuper"))
+ return auth.User{}, echo.NewHTTPError(http.StatusBadRequest, c.i18n.T("users.needSuper"))
}
out, err := c.GetUser(id, "", "")
@@ -97,15 +97,15 @@ func (c *Core) UpdateUser(id int, u models.User) (models.User, error) {
}
// UpdateUserProfile updates the basic fields of a given uesr (name, email, password).
-func (c *Core) UpdateUserProfile(id int, u models.User) (models.User, error) {
+func (c *Core) UpdateUserProfile(id int, u auth.User) (auth.User, error) {
res, err := c.q.UpdateUserProfile.Exec(id, u.Name, u.Email, u.PasswordLogin, u.Password)
if err != nil {
- return models.User{}, echo.NewHTTPError(http.StatusInternalServerError,
+ return auth.User{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorUpdating", "name", "{globals.terms.user}", "error", pqErrMsg(err)))
}
if n, _ := res.RowsAffected(); n == 0 {
- return models.User{}, echo.NewHTTPError(http.StatusBadRequest,
+ return auth.User{}, echo.NewHTTPError(http.StatusBadRequest,
c.i18n.Ts("globals.messages.notFound", "name", "{globals.terms.user}"))
}
@@ -137,8 +137,8 @@ func (c *Core) DeleteUsers(ids []int) error {
}
// LoginUser attempts to log the given user_id in by matching the password.
-func (c *Core) LoginUser(username, password string) (models.User, error) {
- var out models.User
+func (c *Core) LoginUser(username, password string) (auth.User, error) {
+ var out auth.User
if err := c.q.LoginUser.Get(&out, username, password); err != nil {
if err == sql.ErrNoRows {
return out, echo.NewHTTPError(http.StatusForbidden,
@@ -153,7 +153,7 @@ func (c *Core) LoginUser(username, password string) (models.User, error) {
}
// setupUserFields prepares and sets up various user fields.
-func (c *Core) setupUserFields(users []models.User) []models.User {
+func (c *Core) setupUserFields(users []auth.User) []auth.User {
for n, u := range users {
u := u
@@ -162,7 +162,7 @@ func (c *Core) setupUserFields(users []models.User) []models.User {
u.PasswordLogin = true
}
- if u.Type == models.UserTypeAPI {
+ if u.Type == auth.UserTypeAPI {
u.Email = null.String{}
}
@@ -180,14 +180,14 @@ func (c *Core) setupUserFields(users []models.User) []models.User {
if u.ListRoleID != nil {
// Unmarshall the raw list perms map.
- var listPerms []models.ListPermission
+ var listPerms []auth.ListPermission
if u.ListsPermsRaw != nil {
if err := json.Unmarshal(*u.ListsPermsRaw, &listPerms); err != nil {
c.log.Printf("error unmarshalling list permissions for role %d: %v", u.ID, err)
}
}
- u.ListRole = &models.ListRolePermissions{ID: *u.ListRoleID, Name: u.ListRoleName.String, Lists: listPerms}
+ u.ListRole = &auth.ListRolePermissions{ID: *u.ListRoleID, Name: u.ListRoleName.String, Lists: listPerms}
// Iterate each list in the list permissions and setup get/manage list IDs.
for _, p := range listPerms {
@@ -197,10 +197,10 @@ func (c *Core) setupUserFields(users []models.User) []models.User {
u.ListPermissionsMap[p.ID][perm] = struct{}{}
// List IDs with get / manage permissions.
- if perm == models.PermListGet {
+ if perm == auth.PermListGet {
u.GetListIDs = append(u.GetListIDs, p.ID)
}
- if perm == models.PermListManage {
+ if perm == auth.PermListManage {
u.ManageListIDs = append(u.ManageListIDs, p.ID)
}
}
diff --git a/models/models.go b/models/models.go
index 989de718..bdba0fe4 100644
--- a/models/models.go
+++ b/models/models.go
@@ -55,16 +55,6 @@ const (
ListOptinSingle = "single"
ListOptinDouble = "double"
- // User.
- UserTypeUser = "user"
- UserTypeAPI = "api"
- UserStatusEnabled = "enabled"
- UserStatusDisabled = "disabled"
-
- // Role.
- RoleTypeUser = "user"
- RoleTypeList = "list"
-
// BaseTpl is the name of the base template.
BaseTpl = "base"
diff --git a/models/permissions.go b/models/permissions.go
deleted file mode 100644
index b2fdd0fe..00000000
--- a/models/permissions.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package models
-
-const (
- PermListGetAll = "lists:get_all"
- PermListManageAll = "lists:manage_all"
- PermListManage = "list:manage"
- PermListGet = "list:get"
- PermSubscribersGet = "subscribers:get"
- PermSubscribersGetAll = "subscribers:get_all"
- PermSubscribersManage = "subscribers:manage"
- PermSubscribersImport = "subscribers:import"
- PermSubscribersSqlQuery = "subscribers:sql_query"
- PermTxSend = "tx:send"
- PermCampaignsGet = "campaigns:get"
- PermCampaignsGetAll = "campaigns:get_all"
- PermCampaignsGetAnalytics = "campaigns:get_analytics"
- PermCampaignsManage = "campaigns:manage"
- PermCampaignsManageAll = "campaigns:manage_all"
- PermBouncesGet = "bounces:get"
- PermBouncesManage = "bounces:manage"
- PermWebhooksPostBounce = "webhooks:post_bounce"
- PermMediaGet = "media:get"
- PermMediaManage = "media:manage"
- PermTemplatesGet = "templates:get"
- PermTemplatesManage = "templates:manage"
- PermUsersGet = "users:get"
- PermUsersManage = "users:manage"
- PermRolesGet = "roles:get"
- PermRolesManage = "roles:manage"
- PermSettingsGet = "settings:get"
- PermSettingsManage = "settings:manage"
- PermSettingsMaintain = "settings:maintain"
-)