fix(database): create the first panel user with random credentials

The first user is now created when the server starts, with a random
username and password printed once to its log (docker logs, the journal),
instead of a fixed pair seeded by InitDB. CLI calls that initialize the
database are often piped away, as the Docker entrypoint's port lookup is, so
only the server's own log reliably reaches the operator.

`x-ui setting -show` keeps reporting hasDefaultCredential: true until a user
exists, so install.sh still sets its own credentials on a fresh install.
Existing databases are not changed. Verified on a built binary: fresh
setting -show, install.sh-style credential set, first start, login and
restart. The PostgreSQL lane was not run locally; the change adds no query.
This commit is contained in:
MHSanaei
2026-10-24 01:26:05 +02:00
parent 0faad4f4f3
commit 1df8ab29f8
9 changed files with 148 additions and 39 deletions
+13 -25
View File
@@ -57,11 +57,7 @@ func Dialect() string {
return db.Name()
}
const (
defaultUsername = "admin"
defaultPassword = "admin"
sqliteBackupDirPrefix = ".x-ui-backup-"
)
const sqliteBackupDirPrefix = ".x-ui-backup-"
func allModels() []any {
return []any{
@@ -1316,26 +1312,22 @@ func isIgnorableDuplicateColumnErr(gdb *gorm.DB, err error, mdl any) bool {
return false
}
func initUser() error {
// EnsureFirstUser creates the panel's first user with random credentials and returns
// them, or returns "" when one exists; only the starting server calls it, so it can print them.
func EnsureFirstUser() (username, password string, err error) {
empty, err := isTableEmpty("users")
if err != nil || !empty {
return "", "", err
}
username, password = random.Seq(10), random.Seq(16)
hashedPassword, err := crypto.HashPasswordAsBcrypt(password)
if err != nil {
log.Printf("Error checking if users table is empty: %v", err)
return err
return "", "", err
}
if empty {
hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
if err != nil {
log.Printf("Error hashing default password: %v", err)
return err
}
user := &model.User{
Username: defaultUsername,
Password: hashedPassword,
}
return db.Create(user).Error
if err := db.Create(&model.User{Username: username, Password: hashedPassword}).Error; err != nil {
return "", "", err
}
return nil
return username, password, nil
}
func seedRandomSubscriptionPaths() error {
@@ -3145,10 +3137,6 @@ func InitDB(dbPath string) error {
return err
}
}
if err := initUser(); err != nil {
return err
}
return runSeeders(isUsersEmpty)
}