/
checker.go
220 lines (186 loc) · 6.53 KB
/
checker.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package security
import (
"context"
"fmt"
"time"
"github.com/infraboard/mcube/app"
"github.com/infraboard/mcube/cache"
"github.com/infraboard/mcube/exception"
"github.com/infraboard/mcube/logger"
"github.com/infraboard/mcube/logger/zap"
"github.com/infraboard/keyauth/apps/domain"
"github.com/infraboard/keyauth/apps/ip2region"
"github.com/infraboard/keyauth/apps/session"
"github.com/infraboard/keyauth/apps/token"
"github.com/infraboard/keyauth/apps/user"
)
// NewChecker todo
func NewChecker() (Checker, error) {
c := cache.C()
if c == nil {
return nil, fmt.Errorf("denpence cache service is nil")
}
return &checker{
domain: app.GetGrpcApp(domain.AppName).(domain.ServiceServer),
user: app.GetGrpcApp(user.AppName).(user.ServiceServer),
session: app.GetGrpcApp(session.AppName).(session.ServiceServer),
cache: c,
ip2Regoin: app.GetInternalApp(ip2region.AppName).(ip2region.Service),
log: zap.L().Named("Login Security"),
}, nil
}
type checker struct {
domain domain.ServiceServer
user user.ServiceServer
session session.ServiceServer
cache cache.Cache
ip2Regoin ip2region.Service
log logger.Logger
}
func (c *checker) MaxFailedRetryCheck(ctx context.Context, req *token.IssueTokenRequest) error {
ss := c.getOrDefaultSecuritySettingWithUser(ctx, req.Username)
if !ss.LoginSecurity.RetryLock {
c.log.Debugf("retry lock check disabled, don't check")
return nil
}
c.log.Debugf("max failed retry lock check enabled, checking ...")
var count uint32
err := c.cache.Get(req.AbnormalUserCheckKey(), &count)
if err != nil {
c.log.Errorf("get key %s from cache error, %s", req.AbnormalUserCheckKey(), err)
}
rc := ss.LoginSecurity.RetryLockConfig
c.log.Debugf("retry times: %d, retry limite: %d", count, rc.RetryLimite)
if count+1 >= rc.RetryLimite {
return fmt.Errorf("登录失败次数过多, 请%d分钟后重试", rc.LockedMinite)
}
return nil
}
func (c *checker) UpdateFailedRetry(ctx context.Context, req *token.IssueTokenRequest) error {
ss := c.getOrDefaultSecuritySettingWithUser(ctx, req.Username)
if !ss.LoginSecurity.RetryLock {
c.log.Debugf("retry lock check disabled, don't check")
return nil
}
c.log.Debugf("update failed retry count, check key: %s", req.AbnormalUserCheckKey())
var count int
if err := c.cache.Get(req.AbnormalUserCheckKey(), &count); err == nil {
// 之前已经登陆失败过
err := c.cache.Put(req.AbnormalUserCheckKey(), count+1)
if err != nil {
c.log.Errorf("set key %s to cache error, %s", req.AbnormalUserCheckKey())
}
} else {
// 首次登陆失败
err := c.cache.PutWithTTL(
req.AbnormalUserCheckKey(),
count+1,
ss.LoginSecurity.RetryLockConfig.LockedMiniteDuration(),
)
if err != nil {
c.log.Errorf("set key %s to cache error, %s", req.AbnormalUserCheckKey())
}
}
return nil
}
func (c *checker) OtherPlaceLoggedInChecK(ctx context.Context, tk *token.Token) error {
ss := c.getOrDefaultSecuritySettingWithDomain(ctx, tk.Account, tk.Domain)
if !ss.LoginSecurity.ExceptionLock {
c.log.Debugf("exception check disabled, don't check")
return nil
}
if !ss.LoginSecurity.ExceptionLockConfig.OtherPlaceLogin {
c.log.Debugf("other place login check disabled, don't check")
return nil
}
c.log.Debugf("other place login check enabled, checking ...")
// 查询当前登陆IP地域
rip := tk.GetRemoteIP()
c.log.Debugf("query remote ip: %s location ...", rip)
login, err := c.ip2Regoin.LookupIP(rip)
if err != nil {
c.log.Errorf("lookup ip %s error, %s, skip OtherPlaceLoggedInChecK", rip, err)
return nil
}
// 查询出用户上次登陆的地域
queryReq := session.NewQueryUserLastSessionRequest(tk.Account)
us, err := c.session.QueryUserLastSession(ctx, queryReq)
if err != nil {
if exception.IsNotFoundError(err) {
c.log.Debugf("user %s last login session not found", tk.Account)
return nil
}
return err
}
if us.IpInfo == nil {
c.log.Debugf("last login session no ip info found, skip OtherPlaceLoggedInChecK")
return nil
}
// city为0 表示内网IP, 不错异地登录校验
if login.CityID == 0 || us.IpInfo.CityId == 0 {
c.log.Warnf("city id is 0, 内网IP skip OtherPlaceLoggedInChecK")
return nil
}
if us != nil {
c.log.Debugf("user last login city: %s (%d)", us.IpInfo.City, us.IpInfo.CityId)
if login.CityID != us.IpInfo.CityId {
return fmt.Errorf("异地登录, 请输入验证码后再次提交")
}
}
return nil
}
func (c *checker) NotLoginDaysChecK(ctx context.Context, tk *token.Token) error {
ss := c.getOrDefaultSecuritySettingWithUser(ctx, tk.Account)
if !ss.LoginSecurity.ExceptionLock {
c.log.Debugf("exception check disabled, don't check")
return nil
}
c.log.Debugf("not login days check enabled, checking ...")
// 查询出用户上次登陆的地域
queryReq := session.NewQueryUserLastSessionRequest(tk.Account)
us, err := c.session.QueryUserLastSession(ctx, queryReq)
if err != nil {
if exception.IsNotFoundError(err) {
c.log.Debugf("user %s last login session not found", tk.Account)
return nil
}
return err
}
if us != nil {
days := uint32(time.Now().Sub(time.Unix(us.LoginAt/1000, 0)).Hours() / 24)
c.log.Debugf("user %d days not login", days)
maxDays := ss.LoginSecurity.ExceptionLockConfig.NotLoginDays
if days > maxDays {
return fmt.Errorf("user not login days %d", days)
}
c.log.Debugf("not login days check passed, days: %d, max days: %d", days, maxDays)
}
return nil
}
func (c *checker) IPProtectCheck(ctx context.Context, req *token.IssueTokenRequest) error {
ss := c.getOrDefaultSecuritySettingWithUser(ctx, req.Username)
if !ss.LoginSecurity.IpLimite {
c.log.Debugf("ip limite check disabled, don't check")
return nil
}
c.log.Debugf("ip limite check enabled, checking ...")
return nil
}
func (c *checker) getOrDefaultSecuritySettingWithUser(ctx context.Context, account string) *domain.SecuritySetting {
ss := domain.NewDefaultSecuritySetting()
u, err := c.user.DescribeAccount(ctx, user.NewDescriptAccountRequestWithAccount(account))
if err != nil {
c.log.Errorf("get user account error, %s, use default setting to check", err)
return ss
}
return c.getOrDefaultSecuritySettingWithDomain(ctx, u.Account, u.Domain)
}
func (c *checker) getOrDefaultSecuritySettingWithDomain(ctx context.Context, account, domainName string) *domain.SecuritySetting {
ss := domain.NewDefaultSecuritySetting()
d, err := c.domain.DescribeDomain(ctx, domain.NewDescribeDomainRequestWithName(domainName))
if err != nil {
c.log.Errorf("get domain error, %s, use default setting to check", err)
return ss
}
return d.SecuritySetting
}