/
local.go
229 lines (197 loc) · 6.66 KB
/
local.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
221
222
223
224
225
226
227
228
229
/*
Copyright 2021 The KodeRover Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package login
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/koderover/zadig/pkg/microservice/user/core/repository"
"github.com/mojocn/base64Captcha"
"github.com/patrickmn/go-cache"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"github.com/koderover/zadig/pkg/microservice/user/config"
"github.com/koderover/zadig/pkg/microservice/user/core/repository/orm"
"github.com/koderover/zadig/pkg/setting"
"github.com/koderover/zadig/pkg/shared/client/plutusvendor"
)
type LoginArgs struct {
Account string `json:"account"`
Password string `json:"password"`
CaptchaID string `json:"captcha_id"`
CaptchaAnswer string `json:"captcha_answer"`
}
type User struct {
Uid string `json:"uid"`
Token string `json:"token"`
Email string `json:"email"`
Phone string `json:"phone"`
Name string `json:"name"`
Account string `json:"account"`
IdentityType string `json:"identityType"`
}
type CheckSignatureRes struct {
Code int `json:"code"`
Description string `json:"description"`
Extra map[string]interface{} `json:"extra"`
Message string `json:"message"`
Type string `json:"type"`
}
func CheckSignature(ifLoggedIn bool, logger *zap.SugaredLogger) error {
userNum, err := orm.CountUser(repository.DB)
if err != nil {
return err
}
vendorClient := plutusvendor.New()
err = vendorClient.Health()
if err == nil {
res, checkErr := vendorClient.CheckSignature(userNum)
if checkErr != nil {
return checkErr
}
if res.Code == 6694 {
if ifLoggedIn {
return nil
} else {
return fmt.Errorf("系统使用用户数量已达授权人数上限,请联系系统管理员")
}
}
}
return nil
}
var (
loginCache = cache.New(time.Hour, time.Second*10)
)
func LocalLogin(args *LoginArgs, logger *zap.SugaredLogger) (*User, int, error) {
user, err := orm.GetUser(args.Account, config.SystemIdentityType, repository.DB)
if err != nil {
logger.Errorf("InternalLogin get user account:%s error", args.Account)
return nil, 0, err
}
if user == nil {
return nil, 0, fmt.Errorf("user not exist")
}
userLogin, err := orm.GetUserLogin(user.UID, args.Account, config.AccountLoginType, repository.DB)
if err != nil {
logger.Errorf("LocalLogin get user:%s user login not exist, error msg:%s", args.Account, err.Error())
return nil, 0, err
}
if userLogin == nil {
logger.Errorf("InternalLogin user:%s user login not exist", args.Account)
return nil, 0, fmt.Errorf("user login not exist")
}
failedCountInterface, failedCountfound := loginCache.Get(user.UID)
if failedCountfound {
if failedCountInterface.(int) >= 5 {
// first check if a captcha answer is provided
if args.CaptchaAnswer == "" || args.CaptchaID == "" {
return nil, 5, fmt.Errorf("captcha is required")
}
// captcha validation
if passed := store.Verify(args.CaptchaID, args.CaptchaAnswer, false); !passed {
return nil, 5, fmt.Errorf("captcha is wrong")
}
}
}
password := []byte(args.Password)
err = bcrypt.CompareHashAndPassword([]byte(userLogin.Password), password)
if err == bcrypt.ErrMismatchedHashAndPassword {
if !failedCountfound {
loginCache.Set(user.UID, 1, time.Hour)
} else {
err := loginCache.Increment(user.UID, 1)
if err != nil {
logger.Errorf("failed to do login cache increment for UID: [%s], error: %s", user.UID, err)
}
}
failedCount, ok := failedCountInterface.(int)
if !ok {
failedCount = 0
}
return nil, failedCount + 1, fmt.Errorf("password is wrong")
}
if err != nil {
logger.Errorf("LocalLogin user:%s check password error, error msg:%s", args.Account, err)
return nil, 0, fmt.Errorf("check password error, error msg:%s", err)
}
err = CheckSignature(userLogin.LastLoginTime > 0, logger)
if err != nil {
return nil, 0, err
}
userLogin.LastLoginTime = time.Now().Unix()
err = orm.UpdateUserLogin(userLogin.UID, userLogin, repository.DB)
if err != nil {
logger.Errorf("LocalLogin user:%s update user login password error, error msg:%s", args.Account, err.Error())
return nil, 0, err
}
token, err := CreateToken(&Claims{
Name: user.Name,
UID: user.UID,
Email: user.Email,
PreferredUsername: user.Account,
StandardClaims: jwt.StandardClaims{
Audience: setting.ProductName,
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
},
FederatedClaims: FederatedClaims{
ConnectorId: user.IdentityType,
UserId: user.Account,
},
})
if err != nil {
logger.Errorf("LocalLogin user:%s create token error, error msg:%s", args.Account, err.Error())
return nil, 0, err
}
return &User{
Uid: user.UID,
Token: token,
Email: user.Email,
Phone: user.Phone,
Name: user.Name,
Account: user.Account,
IdentityType: user.IdentityType,
}, 0, nil
}
func LocalLogout(userID string, logger *zap.SugaredLogger) (bool, string, error) {
userInfo, err := orm.GetUserByUid(userID, repository.DB)
if err != nil {
logger.Errorf("LocalLogout get user:%s error, error msg:%s", userID, err.Error())
return false, "", err
}
logger.Infof("user Info: %v", userInfo)
if userInfo.IdentityType != config.OauthIdentityType {
return false, "", nil
}
// if we found a user with ouath login type, we check if the connector is still there
// if the connector exist, we check if the logout configuration is enabled and return.
connectorInfo, err := orm.GetConnectorInfo(config.OauthIdentityType, repository.DexDB)
if err != nil {
logger.Errorf("LocalLogout get connector info error, error msg:%s", err.Error())
return false, "", err
}
if connectorInfo.EnableLogOut {
return true, connectorInfo.LogoutRedirectURL, nil
}
return false, "", nil
}
var store = base64Captcha.DefaultMemStore
func GetCaptcha(logger *zap.SugaredLogger) (string, string, error) {
driver := base64Captcha.DefaultDriverDigit
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := c.Generate()
if err != nil {
logger.Errorf("failed to generate captcha, error: %s", err)
return "", "", fmt.Errorf("captcha generate error")
}
return id, b64s, nil
}