-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
59 lines (52 loc) · 1.18 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package schema
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/schema/field"
gen "github.com/fitv/min/ent"
"github.com/fitv/min/ent/hook"
"github.com/fitv/min/util/hash"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Mixin of the User.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
TimeMixin{},
CharsetMixin{},
}
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("username").Unique(),
field.String("password").Sensitive(),
}
}
// Hooks of the User.
func (User) Hooks() []ent.Hook {
return []ent.Hook{
hook.On(
func(next ent.Mutator) ent.Mutator {
return hook.UserFunc(func(ctx context.Context, m *gen.UserMutation) (ent.Value, error) {
if password, ok := m.Password(); ok && len(password) <= 20 {
hashPassword, err := hash.Make(password)
if err != nil {
return nil, fmt.Errorf("failed to hash password: %w", err)
}
m.SetPassword(string(hashPassword))
}
return next.Mutate(ctx, m)
})
},
ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return nil
}