/
authentication.go
305 lines (281 loc) · 8.11 KB
/
authentication.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package service
import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"net/smtp"
"strconv"
"time"
"github.com/bytedance/sonic"
"github.com/google/wire"
"github.com/samber/lo"
"github.com/xh-polaris/service-idl-gen-go/kitex_gen/platform/sts"
"github.com/zeromicro/go-zero/core/stores/redis"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/crypto/bcrypt"
"github.com/xh-polaris/platform-sts/biz/infrastructure/config"
"github.com/xh-polaris/platform-sts/biz/infrastructure/consts"
"github.com/xh-polaris/platform-sts/biz/infrastructure/data/db"
"github.com/xh-polaris/platform-sts/biz/infrastructure/mapper"
"github.com/xh-polaris/platform-sts/biz/infrastructure/sdk/wechat"
"github.com/xh-polaris/platform-sts/biz/infrastructure/util"
)
type IAuthenticationService interface {
SignIn(ctx context.Context, req *sts.SignInReq) (*sts.SignInResp, error)
SetPassword(ctx context.Context, req *sts.SetPasswordReq) (*sts.SetPasswordResp, error)
SendVerifyCode(ctx context.Context, req *sts.SendVerifyCodeReq) (*sts.SendVerifyCodeResp, error)
AddUserAuth(ctx context.Context, req *sts.AddUserAuthReq) (*sts.AddUserAuthResp, error)
}
type AuthenticationService struct {
Config *config.Config
UserMapper mapper.UserMapper
MiniProgramMap wechat.MiniProgramMap
Redis *redis.Redis
}
var AuthenticationSet = wire.NewSet(
wire.Struct(new(AuthenticationService), "*"),
wire.Bind(new(IAuthenticationService), new(*AuthenticationService)),
)
func (s *AuthenticationService) AddUserAuth(ctx context.Context, req *sts.AddUserAuthReq) (*sts.AddUserAuthResp, error) {
resp := &sts.AddUserAuthResp{}
_, err := s.UserMapper.FindOne(ctx, req.UserId)
switch err {
case nil:
return resp, nil
case consts.ErrNotFound:
oid, err := primitive.ObjectIDFromHex(req.UserId)
if err != nil {
return nil, consts.ErrInvalidObjectId
}
auth := make([]*db.Auth, 0)
auth = append(auth, &db.Auth{
Type: req.Type,
Value: req.UnionId,
})
err = s.UserMapper.Insert(ctx, &db.User{
ID: oid,
CreateAt: time.Now(),
UpdateAt: time.Now(),
Auth: auth,
})
if err != nil {
return nil, err
}
return resp, nil
default:
return nil, err
}
}
func (s *AuthenticationService) SignIn(ctx context.Context, req *sts.SignInReq) (*sts.SignInResp, error) {
resp := &sts.SignInResp{}
var err error
switch req.AuthType {
case consts.AuthTypeEmail:
fallthrough
case consts.AuthTypePhone:
resp.UserId, err = s.signInByPassword(ctx, req)
case consts.AuthTypeWechatOpenId:
fallthrough
case consts.AuthTypeWechat:
resp.UserId, resp.UnionId, resp.OpenId, resp.AppId, err = s.signInByWechat(ctx, req)
default:
return nil, consts.ErrInvalidArgument
}
if err != nil {
return nil, err
}
return resp, nil
}
func (s *AuthenticationService) signInByPassword(ctx context.Context, req *sts.SignInReq) (string, error) {
UserMapper := s.UserMapper
// 检查是否设置了验证码,若设置了检查验证码是否合法
ok, err := s.checkVerifyCode(ctx, req.GetVerifyCode(), req.AuthId)
if err != nil {
return "", err
}
auth := &db.Auth{
Type: req.AuthType,
Value: req.AuthId,
}
user, err := UserMapper.FindOneByAuth(ctx, auth)
switch err {
case nil:
case consts.ErrNotFound:
if !ok {
return "", consts.ErrNoSuchUser
}
user = &db.User{Auth: []*db.Auth{auth}}
err := UserMapper.Insert(ctx, user)
if err != nil {
return "", err
}
return user.ID.Hex(), nil
default:
return "", err
}
if ok {
return user.ID.Hex(), nil
}
// 验证码未通过,尝试密码登录
if user.Password == "" || bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.GetPassword())) != nil {
return "", consts.ErrWrongPassword
}
return user.ID.Hex(), nil
}
func (s *AuthenticationService) checkVerifyCode(ctx context.Context, except string, authValue string) (bool, error) {
verifyCode, err := s.Redis.GetCtx(ctx, consts.VerifyCodeKeyPrefix+authValue)
if err != nil {
if err == redis.Nil {
return false, nil
}
return false, err
} else if verifyCode == "" {
return false, nil
} else if verifyCode != except {
return false, nil
} else {
return true, nil
}
}
// return userId unionId openId appid
func (s *AuthenticationService) signInByWechat(ctx context.Context, req *sts.SignInReq) (string, string, string, string, error) {
jsCode := req.GetVerifyCode()
var unionId string
var openId string
var appId string
m := s.MiniProgramMap[req.GetAuthId()]
if m != nil {
// 向微信开放接口提交临时code
res, err := m.Code2Session(ctx, jsCode)
if err != nil {
return "", "", "", "", err
} else if res.ErrCode != 0 {
return "", "", "", "", errors.New(res.ErrMsg)
}
unionId = res.UnionID
openId = res.OpenID
appId = req.GetAuthId()
} else {
for _, conf := range s.Config.WechatApplicationConfigs {
if req.AuthId == conf.AppID {
res, err := util.HTTPGet(ctx, fmt.Sprintf(consts.OAuthUrl, conf.AppID, conf.AppSecret, jsCode))
if err != nil {
return "", "", "", "", err
}
var j map[string]any
if err = sonic.Unmarshal(res, &j); err != nil {
return "", "", "", "", err
}
if id := j["unionid"]; id == "" {
return "", "", "", "", consts.ErrWrongWechatCode
}
unionId = j["unionid"].(string)
if _, ok := j["openid"]; !ok {
return "", "", "", "", consts.ErrWrongWechatCode
}
openId = j["openid"].(string)
appId = conf.AppID
}
}
}
if unionId == "" {
return "", "", "", "", consts.ErrWrongWechatCode
}
UserMapper := s.UserMapper
auth := &db.Auth{
Type: req.AuthType,
Value: unionId,
}
if req.AuthType == consts.AuthTypeWechatOpenId {
auth.AppId = appId
auth.Value = openId
}
user, err := UserMapper.FindOneByAuth(ctx, auth)
switch err {
case nil:
openAuth := &db.Auth{
Type: consts.AuthTypeWechatOpenId,
Value: openId,
AppId: appId,
}
_, ok := lo.Find(user.Auth, func(item *db.Auth) bool {
return *item == *openAuth
})
if !ok {
user.Auth = append(user.Auth, openAuth)
err := UserMapper.Update(ctx, user)
if err != nil {
return "", "", "", "", err
}
}
return user.ID.Hex(), unionId, openId, appId, nil
case consts.ErrNotFound:
auths := []*db.Auth{{
Type: consts.AuthTypeWechatOpenId,
Value: openId,
AppId: appId,
}}
if unionId != "" {
auths = append(auths, &db.Auth{
Type: consts.AuthTypeWechat,
Value: unionId,
})
}
user = &db.User{Auth: auths}
err = UserMapper.Insert(ctx, user)
if err != nil {
return "", "", "", "", err
}
return user.ID.Hex(), unionId, openId, appId, nil
default:
return "", "", "", "", err
}
}
func (s *AuthenticationService) SetPassword(ctx context.Context, req *sts.SetPasswordReq) (*sts.SetPasswordResp, error) {
user, err := s.UserMapper.FindOne(ctx, req.UserId)
if err != nil {
return nil, err
}
hashPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
user.Password = string(hashPassword)
err = s.UserMapper.Update(ctx, user)
if err != nil {
return nil, err
}
return &sts.SetPasswordResp{}, nil
}
func (s *AuthenticationService) SendVerifyCode(ctx context.Context, req *sts.SendVerifyCodeReq) (*sts.SendVerifyCodeResp, error) {
var verifyCode string
switch req.AuthType {
case consts.AuthTypeEmail:
c := s.Config.SMTP
auth := smtp.PlainAuth("", c.Username, c.Password, c.Host)
code, err := rand.Int(rand.Reader, big.NewInt(900000))
code = code.Add(code, big.NewInt(100000))
if err != nil {
return nil, err
}
err = smtp.SendMail(c.Host+":"+strconv.Itoa(c.Port), auth, c.Username, []string{req.AuthId}, []byte(fmt.Sprintf(
"To: %s\r\n"+
"From: xh-polaris\r\n"+
"Content-Type: text/plain"+"; charset=UTF-8\r\n"+
"Subject: 验证码\r\n\r\n"+
"您正在进行喵社区账号注册,本次注册验证码为:%s,5分钟内有效,请勿透露给其他人。\r\n", req.AuthId, code.String())))
if err != nil {
return nil, err
}
verifyCode = code.String()
default:
return nil, errors.New("not implement")
}
err := s.Redis.SetexCtx(ctx, consts.VerifyCodeKeyPrefix+req.AuthId, verifyCode, 300)
if err != nil {
return nil, err
}
return &sts.SendVerifyCodeResp{}, nil
}