-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.go
133 lines (110 loc) · 2.51 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package gocqrs
import (
"errors"
"github.com/diegogub/lib"
"golang.org/x/crypto/bcrypt"
"time"
)
const (
UserEntity = "users"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
Created time.Time `json:"created`
AccountID string `json:"accid"`
ActiveToken bool `json:"activeToken"`
Token string `json:"token"`
Groups []string `json:"groups"`
Data map[string]interface{} `json:"data"`
}
type UserEventHandler struct {
}
const UserCreatedEvent = "UserCreated"
const UserTokenUpdated = "UserTokenUpdated"
func (uh UserEventHandler) EventName() []string {
return []string{
UserCreatedEvent,
UserTokenUpdated,
}
}
func (uh UserEventHandler) Handle(id, accid, userid, role string, event Eventer, entity *Entity, replay bool) (StoreOptions, error) {
var opt StoreOptions
var err error
switch event.GetType() {
case UserCreatedEvent:
var u User
DecodeEvent(event, &u)
u.Username = id
// create new user
opt.Create = true
if !replay {
err = u.Encrypt()
if err != nil {
return opt, err
}
u.Created = time.Now().UTC()
u.GenerateToken()
err = u.Valid()
if err != nil {
return opt, err
}
event.SetData("accid", accid)
event.SetData("token", u.Token)
event.SetData("password", u.Password)
}
entity.Data = ToMap(u)
case UserTokenUpdated:
if !replay {
var u User
u.GenerateToken()
token := u.Token
event.ClearData()
event.SetData("token", token)
} else {
data := event.GetData()
entity.Data["token"] = data["token"]
}
}
return opt, err
}
func (uh UserEventHandler) CheckBase(e Eventer) bool {
switch e.GetType() {
case UserCreatedEvent:
return true
}
return false
}
func (u *User) Valid() error {
var err error
if u.Username == "" {
return errors.New("Invalid username")
}
_, ok := runningApp.Roles[u.Role]
if !ok {
return errors.New("Invalid role")
}
return err
}
func (u *User) Encrypt() error {
if u.Password == "" {
return errors.New("Invalid password")
}
b, err := bcrypt.GenerateFromPassword([]byte(u.Password), 11)
u.Password = string(b)
return err
}
func (u *User) CheckPassword(password string) error {
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
}
func (u *User) CheckToken(token string) error {
if u.Token == token {
return nil
}
return errors.New("Invalid token")
}
func (u *User) GenerateToken() {
t := lib.NewLongId("t") + lib.NewLongId("d") + lib.NewLongId("4")
u.Token = t
}