Support auto-hashing fields via hooks.

This commit is contained in:
mikestefanello 2025-04-12 16:19:18 -04:00
parent 56f8a619a5
commit 7ff1e3f9d2
6 changed files with 49 additions and 36 deletions

View file

@ -1,11 +1,15 @@
package schema
import (
"context"
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
ge "github.com/mikestefanello/pagoda/ent"
"github.com/mikestefanello/pagoda/ent/hook"
"golang.org/x/crypto/bcrypt"
)
// PasswordToken holds the schema definition for the PasswordToken entity.
@ -34,3 +38,25 @@ func (PasswordToken) Edges() []ent.Edge {
Unique(),
}
}
// Hooks of the PasswordToken.
func (PasswordToken) Hooks() []ent.Hook {
return []ent.Hook{
hook.On(
func(next ent.Mutator) ent.Mutator {
return hook.PasswordTokenFunc(func(ctx context.Context, m *ge.PasswordTokenMutation) (ent.Value, error) {
if v, exists := m.Hash(); exists {
hash, err := bcrypt.GenerateFromPassword([]byte(v), bcrypt.DefaultCost)
if err != nil {
return "", err
}
m.SetHash(string(hash))
}
return next.Mutate(ctx, m)
})
},
// Limit the hook only for these operations.
ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
),
}
}