Database Hooks
Configure database hooks to run custom logic before and after database operations.
Authula provides powerful hooks to let you run custom logic before and after database operations for users, accounts, sessions, verifications and more. This allows you to integrate with your own systems, perform validations, trigger side effects, or log activity.
Config
type CoreDatabaseHooksConfig struct {
Users *UserDatabaseHooksConfig
Accounts *AccountDatabaseHooksConfig
Sessions *SessionDatabaseHooksConfig
Verifications *VerificationDatabaseHooksConfig
}
type UserDatabaseHooksConfig struct {
BeforeCreate func(user *User) error
AfterCreate func(user User) error
BeforeUpdate func(user *User) error
AfterUpdate func(user User) error
}
type AccountDatabaseHooksConfig struct {
BeforeCreate func(account *Account) error
AfterCreate func(account Account) error
BeforeUpdate func(account *Account) error
AfterUpdate func(account Account) error
}
type SessionDatabaseHooksConfig struct {
BeforeCreate func(session *Session) error
AfterCreate func(session Session) error
BeforeUpdate func(session *Session) error
AfterUpdate func(session Session) error
}
type VerificationDatabaseHooksConfig struct {
BeforeCreate func(verification *Verification) error
AfterCreate func(verification Verification) error
}Example:
Suppose you want to log every time a user is created in your system. You can use the BeforeCreate or AfterCreate hooks in the UserDatabaseHooksConfig.
import (
"log"
authula "github.com/Authula/authula"
authulaconfig "github.com/Authula/authula/config"
authulamodels "github.com/Authula/authula/models"
)
func logUserCreation(user authulamodels.User) error {
log.Printf("New user created - ID: %s, Email: %s", user.ID, user.Email)
return nil
}
config := authulaconfig.NewConfig(
authulaconfig.WithCoreDatabaseHooks(authulamodels.CoreDatabaseHooksConfig{
Users: &authulamodels.UserDatabaseHooksConfig{
AfterCreate: logUserCreation,
},
}),
)Available Database Hooks
You can hook into the following events:
- Users:
BeforeCreate,AfterCreate,BeforeUpdate,AfterUpdate - Accounts:
BeforeCreate,AfterCreate,BeforeUpdate,AfterUpdate - Sessions:
BeforeCreate,AfterCreate,BeforeUpdate,AfterUpdate - Verifications:
BeforeCreate,AfterCreate
Each hook has a parameter to the entity being created/updated. For "before" hooks, it is a pointer to the entity so direct modifications can be made to the entity before being stored in the database. For "after" hooks, it is a copy of the entity itself if you want to perform read-only operations. However, you can return an error to abort the operation.
How to Integrate
- Implement your hook functions matching the required signature.
- Pass them to the appropriate field in the
CoreDatabaseHooksConfigwhen creating your Authula config. - Return an error from your hook to abort the operation, or
nilto continue.
See the Config Reference for the full structure and all available hooks.
