Add USER_EMAIL and USER_PASSWORD env vars to set the email / pass of initial user (#1137)

This commit is contained in:
henrygd
2025-09-05 11:42:43 -04:00
parent e22d7ca801
commit f6f85f8f9d
3 changed files with 164 additions and 5 deletions

View File

@@ -1,6 +1,8 @@
package migrations
import (
"os"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
@@ -19,11 +21,50 @@ func init() {
if err := app.Save(settings); err != nil {
return err
}
// create superuser
collection, _ := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
user := core.NewRecord(collection)
user.SetEmail(TempAdminEmail)
user.SetRandomPassword()
return app.Save(user)
superuserCollection, _ := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
superUser := core.NewRecord(superuserCollection)
// set email
email, _ := GetEnv("USER_EMAIL")
password, _ := GetEnv("USER_PASSWORD")
didProvideUserDetails := email != "" && password != ""
// set superuser email
if email == "" {
email = TempAdminEmail
}
superUser.SetEmail(email)
// set superuser password
if password != "" {
superUser.SetPassword(password)
} else {
superUser.SetRandomPassword()
}
// if user details are provided, we create a regular user as well
if didProvideUserDetails {
usersCollection, _ := app.FindCollectionByNameOrId("users")
user := core.NewRecord(usersCollection)
user.SetEmail(email)
user.SetPassword(password)
err := app.Save(user)
if err != nil {
return err
}
}
return app.Save(superUser)
}, nil)
}
// GetEnv retrieves an environment variable with a "BESZEL_HUB_" prefix, or falls back to the unprefixed key.
func GetEnv(key string) (value string, exists bool) {
if value, exists = os.LookupEnv("BESZEL_HUB_" + key); exists {
return value, exists
}
// Fallback to the old unprefixed key
return os.LookupEnv(key)
}