Skip to content

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

Introduce `LISTMONK_ADMIN_API_USER` to `--install`. Closes #2314, #2322.

Kailash Nadh562e52cd226b
diff --git a/cmd/auth.go b/cmd/auth.go
index 0eac69df..ed9c872f 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -325,19 +325,20 @@ func (a *App) doFirstTimeSetup(c echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("users.passwordMismatch"))
}
- // Create the default "Super Admin" with all permission.
- r := auth.Role{
- Type: auth.RoleTypeUser,
- Name: null.NewString("Super Admin", true),
- }
- for p := range a.cfg.Permissions {
- r.Permissions = append(r.Permissions, p)
- }
+ // Create the default "Super Admin" with all permissions if it doesn't exist.
+ if _, err := a.core.GetRole(auth.SuperAdminRoleID); err != nil {
+ r := auth.Role{
+ Type: auth.RoleTypeUser,
+ Name: null.NewString("Super Admin", true),
+ }
+ for p := range a.cfg.Permissions {
+ r.Permissions = append(r.Permissions, p)
+ }
- // Create the role in the DB.
- role, err := a.core.CreateRole(r)
- if err != nil {
- return err
+ // Create the role in the DB.
+ if _, err := a.core.CreateRole(r); err != nil {
+ return err
+ }
}
// Create the super admin user in the DB.
@@ -349,7 +350,7 @@ func (a *App) doFirstTimeSetup(c echo.Context) error {
Name: username,
Password: null.NewString(password, true),
Email: null.NewString(email, true),
- UserRoleID: role.ID,
+ UserRoleID: auth.SuperAdminRoleID,
Status: auth.UserStatusEnabled,
}
if _, err := a.core.CreateUser(u); err != nil {
diff --git a/cmd/install.go b/cmd/install.go
index 245be984..f2080ff2 100644
--- a/cmd/install.go
+++ b/cmd/install.go
@@ -8,9 +8,12 @@ import (
"github.com/gofrs/uuid/v5"
"github.com/jmoiron/sqlx"
+ "github.com/knadh/listmonk/internal/auth"
+ "github.com/knadh/listmonk/internal/utils"
"github.com/knadh/listmonk/models"
"github.com/knadh/stuffbin"
"github.com/lib/pq"
+ null "gopkg.in/volatiletech/null.v6"
)
// install runs the first time setup of setting up the database.
@@ -72,20 +75,42 @@ func install(lastVer string, db *sqlx.DB, fs stuffbin.FileSystem, prompt, idempo
// Sample campaign.
installCampaign(campTplID, archiveTplID, q)
- // Setup the user optionally.
+ // Setup admin user optionally.
var (
user = os.Getenv("LISTMONK_ADMIN_USER")
password = os.Getenv("LISTMONK_ADMIN_PASSWORD")
+ apiUser = os.Getenv("LISTMONK_ADMIN_API_USER")
+
+ hasUser = false
)
+
+ // Admin user.
if user != "" && password != "" {
if len(user) < 3 || len(password) < 8 {
lo.Fatal("LISTMONK_ADMIN_USER should be min 3 chars and LISTMONK_ADMIN_PASSWORD should be min 8 chars")
}
- lo.Printf("creating Super Admin user '%s'", user)
- installUser(user, password, q)
+ lo.Printf("creating superadmin user '%s'", user)
+ hasUser = true
} else {
- lo.Printf("no Super Admin user created. Visit webpage to create user.")
+ lo.Printf("no superadmin user created. Visit webpage to create user.")
+ }
+
+ // API User.
+ if apiUser != "" {
+ if !hasUser {
+ lo.Fatal("LISTMONK_ADMIN_API_USER requires LISTMONK_ADMIN_USER and LISTMONK_ADMIN_PASSWORD to be set")
+ }
+
+ if len(apiUser) < 3 {
+ lo.Fatal("LISTMONK_ADMIN_API_USER should be min 3 chars")
+ }
+
+ lo.Printf("creating superadmin API user '%s'", apiUser)
+ }
+
+ if hasUser {
+ installUser(user, password, apiUser, q)
}
lo.Printf("setup complete")
@@ -269,20 +294,45 @@ func checkSchema(db *sqlx.DB) (bool, error) {
return true, nil
}
-func installUser(username, password string, q *models.Queries) {
+func installUser(username, password, apiUsername string, q *models.Queries) {
consts := initConstConfig(ko)
- // Super admin role.
+ // Super Admin role gets all permissions.
perms := []string{}
for p := range consts.Permissions {
perms = append(perms, p)
}
- if _, err := q.CreateRole.Exec("Super Admin", "user", pq.Array(perms)); err != nil {
+ // Create the Super Admin role in the DB.
+ var role auth.Role
+ if err := q.CreateRole.Get(&role, "Super Admin", auth.RoleTypeUser, pq.Array(perms)); err != nil {
lo.Fatalf("error creating super admin role: %v", err)
}
- if _, err := q.CreateUser.Exec(username, true, password, username+"@listmonk", username, "user", 1, nil, "enabled"); err != nil {
+ // Create the admin user.
+ if _, err := q.CreateUser.Exec(username, true, password, username+"@listmonk", username, auth.RoleTypeUser, role.ID, nil, auth.UserStatusEnabled); err != nil {
lo.Fatalf("error creating superadmin user: %v", err)
}
+
+ // Create the admin API user.
+ if apiUsername != "" {
+ // Generate a random API token.
+ tk, err := utils.GenerateRandomString(32)
+ if err != nil {
+ lo.Fatalf("error generating API token: %v", err)
+ }
+
+ var (
+ email = null.String{String: apiUsername + "@api", Valid: true}
+ password = null.String{String: tk, Valid: true}
+ )
+
+ if _, err := q.CreateUser.Exec(apiUsername, false, password, email, apiUsername, auth.UserTypeAPI, role.ID, nil, auth.UserStatusEnabled); err != nil {
+ lo.Fatalf("error creating superadmin API user: %v", err)
+ }
+
+ // Print the token to stdout so that it can be grepped out.
+ lo.Println("writing API token LISTMONK_ADMIN_API_TOKEN to stderr")
+ fmt.Fprintf(os.Stderr, "export LISTMONK_ADMIN_API_TOKEN=\"%s\"\n", tk)
+ }
}
diff --git a/internal/core/roles.go b/internal/core/roles.go
index 681e1502..63cfa624 100644
--- a/internal/core/roles.go
+++ b/internal/core/roles.go
@@ -12,7 +12,7 @@ import (
// GetRoles retrieves all roles.
func (c *Core) GetRoles() ([]auth.Role, error) {
out := []auth.Role{}
- if err := c.q.GetUserRoles.Select(&out); err != nil {
+ if err := c.q.GetUserRoles.Select(&out, nil); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))
}
@@ -20,6 +20,23 @@ func (c *Core) GetRoles() ([]auth.Role, error) {
return out, nil
}
+// GetRole retrieves a role.
+func (c *Core) GetRole(id int) (auth.Role, error) {
+ out := []auth.Role{}
+ if err := c.q.GetUserRoles.Select(&out, id); err != nil {
+ return auth.Role{}, echo.NewHTTPError(http.StatusInternalServerError,
+ c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))
+ }
+
+ // Role does not exist.
+ if len(out) == 0 {
+ return auth.Role{}, echo.NewHTTPError(http.StatusInternalServerError,
+ c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", "role not found"))
+ }
+
+ return out[0], nil
+}
+
// GetListRoles retrieves all list roles.
func (c *Core) GetListRoles() ([]auth.ListRole, error) {
out := []auth.ListRole{}
diff --git a/queries.sql b/queries.sql
index 03faf9c3..9d6d59fe 100644
--- a/queries.sql
+++ b/queries.sql
@@ -1126,7 +1126,7 @@ UPDATE users SET
-- name: delete-users
WITH u AS (
- SELECT COUNT(*) AS num FROM users WHERE NOT(id = ANY($1)) AND user_role_id=1 AND status='enabled'
+ SELECT COUNT(*) AS num FROM users WHERE NOT(id = ANY($1)) AND user_role_id=1 AND type='user' AND status='enabled'
)
DELETE FROM users WHERE id = ALL($1) AND (SELECT num FROM u) > 0;
@@ -1233,7 +1233,8 @@ UPDATE users SET loggedin_at=NOW(), avatar=(CASE WHEN $2 != '' THEN $2 ELSE avat
-- name: get-user-roles
WITH mainroles AS (
- SELECT ur.* FROM roles ur WHERE type = 'user' AND ur.parent_id IS NULL
+ SELECT ur.* FROM roles ur WHERE type = 'user' AND ur.parent_id IS NULL AND
+ CASE WHEN $1::INT != 0 THEN ur.id = $1 ELSE TRUE END
),
listPerms AS (
SELECT ur.parent_id, JSONB_AGG(JSONB_BUILD_OBJECT('id', ur.list_id, 'name', lists.name, 'permissions', ur.permissions)) AS listPerms