always register the installer hooks in case the superuser is created by a console command

This commit is contained in:
Gani Georgiev
2024-11-06 14:22:57 +02:00
parent f38700982c
commit e4cd6810ab
3 changed files with 48 additions and 40 deletions
+39 -1
View File
@@ -1,6 +1,8 @@
package core
import (
"database/sql"
"errors"
"fmt"
"github.com/pocketbase/pocketbase/tools/hook"
@@ -9,6 +11,10 @@ import (
const CollectionNameSuperusers = "_superusers"
// DefaultInstallerEmail is the default superuser email address
// for the initial autogenerated superuser account.
const DefaultInstallerEmail = "__pbinstaller@example.com"
func (app *BaseApp) registerSuperuserHooks() {
app.OnRecordDelete(CollectionNameSuperusers).Bind(&hook.Handler[*RecordEvent]{
Id: "pbSuperusersRecordDelete",
@@ -39,13 +45,45 @@ func (app *BaseApp) registerSuperuserHooks() {
Id: "pbSuperusersRecordSaveExec",
Func: func(e *RecordEvent) error {
e.Record.SetVerified(true) // always mark superusers as verified
return e.Next()
if err := e.Next(); err != nil {
return err
}
// ensure that the installer superuser is deleted
if e.Type == ModelEventTypeCreate && e.Record.Email() != DefaultInstallerEmail {
record, err := app.FindAuthRecordByEmail(CollectionNameSuperusers, DefaultInstallerEmail)
if errors.Is(err, sql.ErrNoRows) {
// already deleted
} else if err != nil {
e.App.Logger().Warn("Failed to fetch installer superuser", "error", err)
} else {
err = e.App.Delete(record)
if err != nil {
e.App.Logger().Warn("Failed to delete installer superuser", "error", err)
}
}
}
return nil
},
Priority: -99,
}
app.OnRecordCreateExecute(CollectionNameSuperusers).Bind(recordSaveHandler)
app.OnRecordUpdateExecute(CollectionNameSuperusers).Bind(recordSaveHandler)
// prevent sending password reset emails to the installer address
app.OnMailerRecordPasswordResetSend(CollectionNameSuperusers).Bind(&hook.Handler[*MailerRecordEvent]{
Id: "pbSuperusersInstallerPasswordReset",
Func: func(e *MailerRecordEvent) error {
if e.Record.Email() == DefaultInstallerEmail {
return errors.New("cannot reset the password for the installer superuser")
}
return e.Next()
},
})
collectionSaveHandler := &hook.Handler[*CollectionEvent]{
Id: "pbSuperusersCollectionSaveExec",
Func: func(e *CollectionEvent) error {