user_auth.go
2.6 KB
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
package domain
import (
"strings"
"time"
)
// 用户认证实体
type UserAuth struct {
// 用户认证编号
UserAuthId int64 `json:"userAuthId"`
// 用户id列表
Users []int64 `json:"users"`
// 手机认证
PhoneAuth *PhoneAuth `json:"phoneAuth"`
// 凭证认证
CredentialAuths []*CredentialAuth `credentialAuths`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
}
type UserAuthRepository interface {
Save(userAuth *UserAuth) (*UserAuth, error)
Remove(userAuth *UserAuth) (*UserAuth, error)
FindOne(queryOptions map[string]interface{}) (*UserAuth, error)
Find(queryOptions map[string]interface{}) (int64, []*UserAuth, error)
}
func (userAuth *UserAuth) Identify() interface{} {
if userAuth.UserAuthId == 0 {
return nil
}
return userAuth.UserAuthId
}
func (userAuth *UserAuth) Update(data map[string]interface{}) error {
if users, ok := data["users"]; ok {
userAuth.Users = users.([]int64)
}
if phone, ok := data["phone"]; ok {
userAuth.PhoneAuth.Phone = phone.(string)
}
if password, ok := data["password"]; ok && len(password.(string)) > 0 {
userAuth.PhoneAuth.Password = password.(string)
}
if uid, ok := data["userId"]; ok {
var userExisted bool = false
userId := uid.(int64)
for i := range userAuth.Users {
if userAuth.Users[i] == userId {
userExisted = true
}
}
if !userExisted {
userAuth.Users = append(userAuth.Users, userId)
}
}
return nil
}
// 绑定凭证
func (userAuth *UserAuth) BindCredentialAuth(cred *CredentialAuth) error {
var exists bool
if err := cred.Check(); err != nil {
return err
}
for i, v := range userAuth.CredentialAuths {
if v.DeviceType == cred.DeviceType {
userAuth.CredentialAuths[i] = cred
exists = true
}
}
if !exists {
userAuth.CredentialAuths = append(userAuth.CredentialAuths, cred)
}
return nil
}
// 解除凭证
func (userAuth *UserAuth) UnbindCredentialAuth(deviceType int) error {
length := len(userAuth.CredentialAuths)
for i, v := range userAuth.CredentialAuths {
if v.DeviceType == deviceType {
if length <= 1 {
userAuth.CredentialAuths = []*CredentialAuth{}
} else {
userAuth.CredentialAuths[i] = userAuth.CredentialAuths[length-1]
userAuth.CredentialAuths = userAuth.CredentialAuths[:length-1]
}
return nil
}
}
return nil
}
// 检查凭证
func (userAuth *UserAuth) CheckCredentialAuth(deviceType int, cred string) bool {
for _, v := range userAuth.CredentialAuths {
if v.DeviceType == deviceType && strings.EqualFold(v.Credential, cred) {
if err := v.Check(); err != nil {
return false
}
return true
}
}
return false
}