Skip to content

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

Add first-time Super Admin setup UI on fresh install.

Kailash Nadh5b3d6e2be0af
diff --git a/cmd/auth.go b/cmd/auth.go
index b0cdd82f..e161ab6d 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -10,8 +10,10 @@ 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"
)
type loginTpl struct {
@@ -35,6 +37,17 @@ var oidcProviders = map[string]bool{
// handleLoginPage renders the login page and handles the login form.
func handleLoginPage(c echo.Context) error {
+ app := c.Get("app").(*App)
+
+ // Has the user been setup?
+ app.Lock()
+ needsUserSetup := app.needsUserSetup
+ app.Unlock()
+
+ if needsUserSetup {
+ return handleLoginSetupPage(c)
+ }
+
// Process POST login request.
var loginErr error
if c.Request().Method == http.MethodPost {
@@ -47,6 +60,26 @@ func handleLoginPage(c echo.Context) error {
return renderLoginPage(c, loginErr)
}
+// handleLoginSetupPage renders the first time user login page and handles the login form.
+func handleLoginSetupPage(c echo.Context) error {
+ app := c.Get("app").(*App)
+
+ // Process POST login request.
+ var loginErr error
+
+ if c.Request().Method == http.MethodPost {
+ loginErr = doLoginSetup(c)
+ if loginErr == nil {
+ app.Lock()
+ app.needsUserSetup = false
+ app.Unlock()
+ return c.Redirect(http.StatusFound, utils.SanitizeURI(c.FormValue("next")))
+ }
+ }
+
+ return renderLoginSetupPage(c, loginErr)
+}
+
// handleLogout logs a user out.
func handleLogout(c echo.Context) error {
var (
@@ -189,6 +222,34 @@ func renderLoginPage(c echo.Context, loginErr error) error {
return c.Render(http.StatusOK, "admin-login", out)
}
+// renderLoginSetupPage renders the first time user setup page.
+func renderLoginSetupPage(c echo.Context, loginErr error) error {
+ var (
+ app = c.Get("app").(*App)
+ next = utils.SanitizeURI(c.FormValue("next"))
+ )
+
+ if next == "/" {
+ next = uriAdmin
+ }
+
+ out := loginTpl{
+ Title: app.i18n.T("users.login"),
+ PasswordEnabled: true,
+ NextURI: next,
+ }
+
+ if loginErr != nil {
+ if e, ok := loginErr.(*echo.HTTPError); ok {
+ out.Error = e.Message.(string)
+ } else {
+ out.Error = loginErr.Error()
+ }
+ }
+
+ return c.Render(http.StatusOK, "admin-login-setup", out)
+}
+
// doLogin logs a user in with a username and password.
func doLogin(c echo.Context) error {
var (
@@ -233,3 +294,78 @@ func doLogin(c echo.Context) error {
return nil
}
+
+// doLoginSetup sets a user up for the first time.
+func doLoginSetup(c echo.Context) error {
+ var (
+ app = c.Get("app").(*App)
+ )
+
+ // 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, app.i18n.T("users.invalidRequest"))
+ // }
+
+ var (
+ email = strings.TrimSpace(c.FormValue("email"))
+ username = strings.TrimSpace(c.FormValue("username"))
+ password = strings.TrimSpace(c.FormValue("password"))
+ password2 = strings.TrimSpace(c.FormValue("password2"))
+ )
+
+ if !utils.ValidateEmail(email) {
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ }
+ if !strHasLen(username, 3, stdInputMaxLen) {
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "username"))
+ }
+ if !strHasLen(password, 8, stdInputMaxLen) {
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "password"))
+ }
+ if password != password2 {
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("users.passwordMismatch"))
+ }
+
+ // Create the default "Super Admin".
+ r := models.Role{
+ Type: models.RoleTypeUser,
+ Name: null.NewString("Super Admin", true),
+ }
+ for p := range app.constants.Permissions {
+ r.Permissions = append(r.Permissions, p)
+ }
+ role, err := app.core.CreateRole(r)
+ if err != nil {
+ return err
+ }
+
+ // Create the super admin user.
+ u := models.User{
+ Type: models.UserTypeUser,
+ HasPassword: true,
+ PasswordLogin: true,
+ Username: username,
+ Name: username,
+ Password: null.NewString(password, true),
+ Email: null.NewString(email, true),
+ UserRoleID: role.ID,
+ Status: models.UserStatusEnabled,
+ }
+ if _, err := app.core.CreateUser(u); err != nil {
+ return err
+ }
+
+ // Log the user in.
+ user, err := app.core.LoginUser(username, password)
+ if err != nil {
+ return err
+ }
+
+ // Set the session.
+ if err := app.auth.SaveSession(user, "", c); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/cmd/init.go b/cmd/init.go
index 1b5d9de1..9dc0c766 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -938,7 +938,7 @@ func initTplFuncs(i *i18n.I18n, cs *constants) template.FuncMap {
return funcs
}
-func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
+func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) (bool, *auth.Auth) {
var oidcCfg auth.OIDCConfig
if ko.Bool("security.oidc.enabled") {
@@ -976,8 +976,9 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
}
// Cache all API users in-memory for token auth.
- if err := cacheAPIUsers(co, a); err != nil {
- lo.Fatalf("error loading API users: %v", err)
+ hasUsers, err := cacheUsers(co, a)
+ if err != nil {
+ lo.Fatalf("error loading API users to cache: %v", err)
}
// If the legacy username+password is set in the TOML file, use that as an API
@@ -1004,5 +1005,5 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
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.`)
}
- return a
+ return hasUsers, a
}
diff --git a/cmd/install.go b/cmd/install.go
index 58fc9f27..3d61ca2a 100644
--- a/cmd/install.go
+++ b/cmd/install.go
@@ -8,7 +8,6 @@ import (
"github.com/gofrs/uuid/v5"
"github.com/jmoiron/sqlx"
- "github.com/knadh/listmonk/internal/utils"
"github.com/knadh/listmonk/models"
"github.com/knadh/stuffbin"
"github.com/lib/pq"
@@ -73,15 +72,24 @@ func install(lastVer string, db *sqlx.DB, fs stuffbin.FileSystem, prompt, idempo
// Sample campaign.
installCampaign(campTplID, archiveTplID, q)
- // Super admin role.
- user, password := installUser(q)
+ // Setup the user optionally.
+ var (
+ user = os.Getenv("LISTMONK_ADMIN_USER")
+ password = os.Getenv("LISTMONK_ADMIN_PASSWORD")
+ )
+ 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)
+ } else {
+ lo.Printf("no Super Admin user created. Visit webpage to create user.")
+ }
lo.Printf("setup complete")
lo.Printf(`run the program and access the dashboard at %s`, ko.MustString("app.address"))
-
- if user != "" {
- fmt.Printf("\n\033[31mIMPORTANT! CHANGE PASSWORD AFTER LOGGING IN\033[0m\nusername: \033[32m%s\033[0m and password: \033[32m%s\033[0m\n\n", user, password)
- }
}
// installSchema executes the SQL schema and creates the necessary tables and types.
@@ -99,64 +107,6 @@ func installSchema(curVer string, db *sqlx.DB, fs stuffbin.FileSystem) error {
return recordMigrationVersion(curVer, db)
}
-func installUser(q *models.Queries) (string, string) {
- consts := initConstants()
-
- // Super admin role.
- perms := []string{}
- for p := range consts.Permissions {
- perms = append(perms, p)
- }
-
- if _, err := q.CreateRole.Exec("Super Admin", "user", pq.Array(perms)); err != nil {
- lo.Fatalf("error creating super admin role: %v", err)
- }
-
- // Create super admin.
- var (
- user = os.Getenv("LISTMONK_ADMIN_USER")
- password = os.Getenv("LISTMONK_ADMIN_PASSWORD")
- typ = "env"
- )
-
- if user != "" {
- // If the env vars are set, use those values
- if len(user) < 2 || len(password) < 8 {
- lo.Fatal("LISTMONK_ADMIN_USER should be min 3 chars and LISTMONK_ADMIN_PASSWORD should be min 8 chars")
- }
- } else if ko.Exists("app.admin_username") {
- // Legacy admin/password are set in the config or env var. Use those.
- user = ko.String("app.admin_username")
- password = ko.String("app.admin_password")
-
- if len(user) < 2 || len(password) < 8 {
- lo.Fatal("admin_username should be min 3 chars and admin_password should be min 8 chars")
- }
- typ = "legacy config"
- } else {
- // None are set. Auto-generate.
- user = "admin"
- if p, err := utils.GenerateRandomString(12); err != nil {
- lo.Fatal("error generating admin password")
- } else {
- password = p
- }
- typ = "auto-generated"
- }
-
- lo.Printf("creating admin user '%s'. Credential source is '%s'", user, typ)
-
- if _, err := q.CreateUser.Exec(user, true, password, user+"@listmonk", user, "user", 1, nil, "enabled"); err != nil {
- lo.Fatalf("error creating superadmin user: %v", err)
- }
-
- if typ == "auto-generated" {
- return user, password
- }
-
- return "", ""
-}
-
func installLists(q *models.Queries) (int, int) {
var (
defList int
@@ -318,3 +268,21 @@ func checkSchema(db *sqlx.DB) (bool, error) {
}
return true, nil
}
+
+func installUser(username, password string, q *models.Queries) {
+ consts := initConstants()
+
+ // Super admin role.
+ perms := []string{}
+ for p := range consts.Permissions {
+ perms = append(perms, p)
+ }
+
+ if _, err := q.CreateRole.Exec("Super Admin", "user", 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 {
+ lo.Fatalf("error creating superadmin user: %v", err)
+ }
+}
diff --git a/cmd/main.go b/cmd/main.go
index 20574522..64c79aca 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -64,6 +64,9 @@ type App struct {
// after a settings update.
needsRestart bool
+ // First time installation with no user records in the DB. Needs user setup.
+ needsUserSetup bool
+
// Global state that stores data on an available remote update.
update *AppUpdate
sync.Mutex
@@ -212,7 +215,13 @@ func main() {
app.queries = queries
app.manager = initCampaignManager(app.queries, app.constants, app)
app.importer = initImporter(app.queries, db, app.core, app)
- app.auth = initAuth(db.DB, ko, app.core)
+
+ hasUsers, auth := initAuth(db.DB, ko, app.core)
+ app.auth = auth
+ // If there are are no users in the DB who can login, the app has to prompt
+ // for new user setup.
+ app.needsUserSetup = !hasUsers
+
app.notifTpls = initNotifTemplates("/email-templates/*.html", fs, app.i18n, app.constants)
initTxTemplates(app.manager, app)
diff --git a/cmd/roles.go b/cmd/roles.go
index cf193cdc..c28423f6 100644
--- a/cmd/roles.go
+++ b/cmd/roles.go
@@ -116,7 +116,7 @@ func handleUpdateUserRole(c echo.Context) error {
}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
@@ -153,7 +153,7 @@ func handleUpdateListRole(c echo.Context) error {
}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
@@ -176,7 +176,7 @@ func handleDeleteRole(c echo.Context) error {
}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
diff --git a/cmd/users.go b/cmd/users.go
index f01f99c4..9c259cce 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -104,7 +104,7 @@ func handleCreateUser(c echo.Context) error {
}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
@@ -186,7 +186,7 @@ func handleUpdateUser(c echo.Context) error {
user.Password = null.String{}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
@@ -214,7 +214,7 @@ func handleDeleteUsers(c echo.Context) error {
}
// Cache the API token for validating API queries without hitting the DB every time.
- if err := cacheAPIUsers(app.core, app.auth); err != nil {
+ if _, err := cacheUsers(app.core, app.auth); err != nil {
return err
}
@@ -270,19 +270,27 @@ func handleUpdateUserProfile(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{out})
}
-func cacheAPIUsers(co *core.Core, a *auth.Auth) error {
+// cacheUsers fetches (API) users and caches them in the auth module.
+// It also returns a bool indicating whether there are any actual users in the DB at all,
+// which if there aren't, the first time user setup needs to be run.
+func cacheUsers(co *core.Core, a *auth.Auth) (bool, error) {
allUsers, err := co.GetUsers()
if err != nil {
- return err
+ return false, err
}
+ hasUser := false
apiUsers := make([]models.User, 0, len(allUsers))
for _, u := range allUsers {
if u.Type == models.UserTypeAPI && u.Status == models.UserStatusEnabled {
apiUsers = append(apiUsers, u)
}
+
+ if u.Type == models.UserTypeUser {
+ hasUser = true
+ }
}
a.CacheAPIUsers(apiUsers)
- return nil
+ return hasUser, nil
}
diff --git a/frontend/cypress.config.js b/frontend/cypress.config.js
index c13f90b6..0a068027 100644
--- a/frontend/cypress.config.js
+++ b/frontend/cypress.config.js
@@ -4,11 +4,13 @@ module.exports = defineConfig({
env: {
apiUrl: 'http://localhost:9000',
serverInitCmd:
+ 'pkill -9 listmonk | cd ../ && LISTMONK_ADMIN_USER=admin LISTMONK_ADMIN_PASSWORD=listmonk ./listmonk --install --yes && ./listmonk > /dev/null 2>/dev/null &',
+ serverInitBlankCmd:
'pkill -9 listmonk | cd ../ && ./listmonk --install --yes && ./listmonk > /dev/null 2>/dev/null &',
- username: 'listmonk',
- password: 'listmonk',
+ LISTMONK_ADMIN_USER: 'admin',
+ LISTMONK_ADMIN_PASSWORD: 'listmonk',
},
- viewportWidth: 1300,
+ viewportWidth: 1400,
viewportHeight: 950,
e2e: {
testIsolation: false,
diff --git a/frontend/cypress/e2e/users.cy.js b/frontend/cypress/e2e/users.cy.js
index 481e76b3..74c769c2 100644
--- a/frontend/cypress/e2e/users.cy.js
+++ b/frontend/cypress/e2e/users.cy.js
@@ -1,5 +1,23 @@
const apiUrl = Cypress.env('apiUrl');
+describe('First time user setup', () => {
+ it('Sets up the superadmin user', () => {
+ cy.resetDBBlank();
+ cy.visit('/admin/login');
+
+ cy.get('input[name=email]').type('super@domain');
+ cy.get('input[name=username]').type('super');
+ cy.get('input[name=password]').type('super123');
+ cy.get('input[name=password2]').type('super123');
+ cy.get('button[type=submit]').click();
+ cy.wait(500);
+ cy.visit('/admin/users');
+
+ cy.get('[data-cy=btn-edit]').first().click();
+ cy.get('select[name=user_role]').should('have.value', '1');
+ });
+});
+
describe('User roles', () => {
it('Opens user roles page', () => {
cy.resetDB();
diff --git a/frontend/cypress/support/commands.js b/frontend/cypress/support/commands.js
index 1997e3f4..d3b2bca6 100644
--- a/frontend/cypress/support/commands.js
+++ b/frontend/cypress/support/commands.js
@@ -9,6 +9,10 @@ Cypress.Commands.add('resetDB', () => {
cy.exec(Cypress.env('serverInitCmd'));
});
+Cypress.Commands.add('resetDBBlank', () => {
+ cy.exec(Cypress.env('serverInitBlankCmd'));
+});
+
// Takes a th class selector of a Buefy table, clicks it sorting the table,
// then compares the values of [td.data-id] attri of all the rows in the
// table against the given IDs, asserting the expected order of sort.
diff --git a/frontend/src/views/Users.vue b/frontend/src/views/Users.vue
index 77b8cc2b..7e110922 100644
--- a/frontend/src/views/Users.vue
+++ b/frontend/src/views/Users.vue
@@ -45,12 +45,12 @@
<b-tag v-if="props.row.status === 'disabled'">
{{ $t(`users.status.${props.row.status}`) }}
</b-tag>
- <div class="has-text-grey is-size-7">
+ <b-tag v-if="props.row.type === 'api'" class="api">
+ <b-icon icon="code" />
+ {{ $t(`users.type.${props.row.type}`) }}
+ </b-tag>
+ <div class="has-text-grey is-size-7 mt-2">
{{ props.row.name }}
- <b-tag v-if="props.row.type === 'api'" class="is-small api">
- <b-icon icon="code" />
- {{ $t(`users.type.${props.row.type}`) }}
- </b-tag>
</div>
</b-table-column>
diff --git a/i18n/en.json b/i18n/en.json
index 32d23161..26b6b4ab 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -610,6 +610,7 @@
"users.listRole": "List roles | List role",
"users.listRoles": "List roles",
"users.login": "Login",
+ "users.firstTime": "This is a fresh install. Pick a username and password for the Super Admin account.",
"users.loginOIDC": "Login with {name}",
"users.logout": "Logout",
"users.needSuper": "User(s) couldn't updated. There has to be at least one active Super Admin user.",