审查视图

pkg/application/auth/service/service.go 33.4 KB
yangfu authored
1 2 3
package service

import (
tangxuhui authored
4 5
	"time"
yangfu authored
6
	"github.com/GeeTeam/gt3-golang-sdk/geetest"
yangfu authored
7
	"github.com/google/uuid"
yangfu authored
8
	"github.com/linmadan/egglib-go/utils/json"
yangfu authored
9
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/dto"
yangfu authored
10 11 12 13 14 15 16 17 18 19 20 21 22
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/query"

	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"

	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/command"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/cache"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/sms_serve"
)
yangfu authored
23 24 25 26 27
const (
	captchaID  = "33a2abf9c5df0d6bc3b89fb39280114b"
	privateKey = "13320fd2b10199e9a2440a4fbb4d46f7"
)
yangfu authored
28 29 30 31 32
// 组织管理
type AuthService struct {
}

//AuthLogin 用户登录
yangfu authored
33
func (svr AuthService) AuthLogin(loginCommand *command.LoginCommand) (interface{}, error) {
yangfu authored
34
	var (
yangfu authored
35 36 37 38
		authCode      string
		result        interface{}
		err           error
		loginPlatform string = domain.LoginPlatformApp
yangfu authored
39
	)
yangfu authored
40 41 42
	if loginCommand.DeviceType == domain.DeviceTypeWeb {
		loginPlatform = domain.LoginPlatformWeb
	}
yangfu authored
43 44 45
	if len(loginCommand.LoginPlatform) != 0 {
		loginPlatform = loginCommand.LoginPlatform
	}
yangfu authored
46 47 48 49 50
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	_, err = creationUserGateway.AuthRefreshIM(allied_creation_user.ReqAuthRefreshIM{
		Phone: loginCommand.Phone,
	})
	if err != nil {
yangfu authored
51 52
		log.Logger.Error("refresh im error:" + err.Error()) // 只做提示继续进行登录
		//return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
yangfu authored
53 54
	}
	switch loginCommand.GrantType {
yangfu authored
55 56 57 58
	case domain.LoginPwd:
		authCode, err = svr.SignInPassword(loginCommand.Phone, loginCommand.Password, loginPlatform)
	case domain.LoginSmsCode:
		authCode, err = svr.SignInCaptcha(loginCommand.Phone, loginCommand.Captcha, loginPlatform)
yangfu authored
59 60 61
	default:
		err = application.ThrowError(application.TRANSACTION_ERROR, "登录方式无法解析")
	}
yangfu authored
62 63 64 65 66 67 68
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	result, err = svr.GetAuthAccessToken(&command.AccessTokenCommand{
		AuthCode:      authCode,
		SessionMode:   loginCommand.SessionMode,
		LoginPlatform: loginPlatform,
yangfu authored
69 70 71 72 73 74 75
	})
	return map[string]interface{}{
		"access": result,
	}, err
}

//AuthLogin 用户登录
yangfu authored
76
func (svr AuthService) AuthLoginPwd(loginCommand *command.LoginPwdCommand) (interface{}, error) {
yangfu authored
77 78 79 80 81 82 83 84
	if err := loginCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	login := &command.LoginCommand{
		GrantType:   "signInPassword",
		Phone:       loginCommand.Username,
		Password:    loginCommand.Password,
		SessionMode: loginCommand.SessionMode,
yangfu authored
85
		DeviceType:  loginCommand.DeviceType,
yangfu authored
86
	}
yangfu authored
87 88 89 90 91 92 93 94
	if len(loginCommand.CaptchaChallenge) > 0 {
		geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
		validateResult := geetest.SuccessValidate(loginCommand.CaptchaChallenge, loginCommand.CaptchaValidate, loginCommand.CaptchaSeccode, "", "")
		if !validateResult {
			log.Logger.Error("validate captcha fail")
		}
	}
	return svr.AuthLogin(login)
yangfu authored
95 96 97
}

//AuthLogin 用户登录
yangfu authored
98
func (svr AuthService) AuthLoginSms(loginCommand *command.LoginSmsCommand) (interface{}, error) {
yangfu authored
99 100 101 102 103 104 105 106
	if err := loginCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	login := &command.LoginCommand{
		GrantType:   "signInCaptcha",
		Phone:       loginCommand.Phone,
		Captcha:     loginCommand.Code,
		SessionMode: loginCommand.SessionMode,
yangfu authored
107
		DeviceType:  loginCommand.DeviceType,
yangfu authored
108
	}
yangfu authored
109 110 111 112 113
	return svr.AuthLogin(login)
}

//AuthLoginQrcode 扫码登录
func (svr AuthService) AuthLoginQrcode(queryParam *query.QrcodeLoginStatusQuery) (interface{}, error) {
yangfu authored
114 115 116 117
	failLoginData := map[string]interface{}{
		"isLogin": false,
		"access":  struct{}{},
	}
yangfu authored
118 119
	cache := cache.LoginQrcodeCache{}
	qrcodeMessage, err := cache.Get(queryParam.Key)
yangfu authored
120
	if err != nil {
yangfu authored
121
		log.Logger.Error(err.Error())
yangfu authored
122
		return nil, application.ThrowError(application.BUSINESS_ERROR, "二维码已失效")
yangfu authored
123
	}
yangfu authored
124
	if !qrcodeMessage.IsLogin {
yangfu authored
125
		return failLoginData, nil
yangfu authored
126
	}
yangfu authored
127
yangfu authored
128
	loginToken := domain.LoginToken{
yangfu authored
129 130 131
		UserId:     qrcodeMessage.UserId,
		UserBaseId: qrcodeMessage.UserBaseId,
		Account:    qrcodeMessage.Account,
yangfu authored
132
		Platform:   domain.LoginPlatformWeb,
yangfu authored
133 134 135 136
		CompanyId:  qrcodeMessage.CompanyId,
		OrgId:      qrcodeMessage.OrgId,
	}
	cache.Remove(queryParam.Key)
tangxuhui authored
137
	result, err := svr.getToken(loginToken)
yangfu authored
138
	if err != nil {
yangfu authored
139
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
yangfu authored
140
	}
yangfu authored
141
yangfu authored
142
	data := map[string]interface{}{
yangfu authored
143
		"isLogin": qrcodeMessage.IsLogin,
yangfu authored
144 145 146
		"access":  result["token"],
	}
	return data, nil
yangfu authored
147 148
}
yangfu authored
149 150 151
//AuthLoginQrcodeBind 扫码登录-绑定
func (svr AuthService) AuthLoginQrcodeBinding(bindingCmd *command.QrcodeBindingCommand) (interface{}, error) {
	qrCache := cache.LoginQrcodeCache{}
yangfu authored
152
	qrcodeMessage, err := qrCache.Get(bindingCmd.Key)
yangfu authored
153
	if err != nil {
yangfu authored
154
		return nil, application.ThrowError(application.BUSINESS_ERROR, "您扫描的二维码无效,请确认后重新扫描")
yangfu authored
155
	}
yangfu authored
156
	if err := qrcodeMessage.BindUser(bindingCmd.Operator); err != nil {
yangfu authored
157
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
yangfu authored
158
	}
yangfu authored
159
	if err := qrCache.Save(*qrcodeMessage); err != nil {
yangfu authored
160
		log.Logger.Error(err.Error())
yangfu authored
161
		return nil, application.ThrowError(application.BUSINESS_ERROR, "登录失败,请重试")
yangfu authored
162 163 164 165
	}
	return struct{}{}, nil
}
yangfu authored
166
//SendSmsCaptcha 发送验证码短信
yangfu authored
167
func (svr AuthService) SendSmsCaptcha(smsCodeCommand *command.SendSmsCodeCommand) error {
168 169 170 171 172 173 174 175 176
	if err := smsCodeCommand.ValidateCommand(); err != nil {
		return application.ThrowError(application.ARG_ERROR, err.Error())
	}
	if smsCodeCommand.Flag == 1 {
		creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
		userBase, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
			Account: smsCodeCommand.Phone,
		})
		if err != nil || userBase.UserInfo.Phone != smsCodeCommand.Phone {
yangfu authored
177
			return application.ThrowError(application.BUSINESS_ERROR, "输入的手机号不是平台用户,请重新输入")
178 179
		}
	}
yangfu authored
180 181 182
	smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
	err := smsServeGateway.SendSms(smsCodeCommand.Phone)
	if err != nil {
yangfu authored
183
		return application.ThrowError(application.BUSINESS_ERROR, err.Error())
yangfu authored
184 185 186 187 188
	}
	return nil
}

//SignInPassword 使用账号密码校验
yangfu authored
189
func (svr AuthService) SignInPassword(account string, password string, loginPlatform string) (string, error) {
yangfu authored
190 191 192 193 194 195 196 197
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	_, err := creationUserGateway.AuthCheckPassword(allied_creation_user.ReqAuthCheckPassword{
		Password: password,
		Phone:    account,
	})
	if err != nil {
		return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
198
	loginToken := domain.LoginToken{
yangfu authored
199 200
		UserId:    0,
		Account:   account,
yangfu authored
201
		Platform:  loginPlatform,
yangfu authored
202 203
		CompanyId: 0,
	}
yangfu authored
204
	authCode, err := loginToken.GenerateAuthCode()
yangfu authored
205 206 207
	if err != nil {
		return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
208
	return authCode, nil
yangfu authored
209 210 211
}

//SignInCaptcha 使用手机验证码登录
yangfu authored
212
func (svr AuthService) SignInCaptcha(phone string, captcha string, loginPlatform string) (string, error) {
yangfu authored
213 214 215 216 217
	smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
	err := smsServeGateway.CheckSmsCode(phone, captcha)
	if err != nil {
		return "", application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
yangfu authored
218
	loginToken := domain.LoginToken{
yangfu authored
219 220
		UserId:    0,
		Account:   phone,
yangfu authored
221
		Platform:  loginPlatform,
yangfu authored
222 223
		CompanyId: 0,
	}
yangfu authored
224
	authCode, err := loginToken.GenerateAuthCode()
yangfu authored
225 226 227
	if err != nil {
		return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
228
	return authCode, nil
yangfu authored
229 230 231
}

//GetAuthAccessToken 获取令牌Token
yangfu authored
232
func (svr AuthService) GetAuthAccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
yangfu authored
233 234 235
	if err := accessTokenCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
236 237
	loginToken := &domain.LoginToken{}
	err := loginToken.ParseToken(accessTokenCommand.AuthCode)
yangfu authored
238 239 240
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
241
	loginToken.Platform = accessTokenCommand.LoginPlatform
yangfu authored
242
	loginToken.SessionMode = accessTokenCommand.SessionMode
yangfu authored
243
	result, err := svr.getToken(*loginToken)
yangfu authored
244
	return result["token"], err
yangfu authored
245 246
}
yangfu authored
247
func (svr AuthService) RefreshAuthAccessToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
yangfu authored
248
	if err := refreshTokenCommand.ValidateCommand(); err != nil {
yangfu authored
249
		return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
yangfu authored
250
	}
yangfu authored
251 252
	loginToken := domain.LoginToken{}
	err := loginToken.ParseToken(refreshTokenCommand.RefreshToken)
yangfu authored
253
	if err != nil {
yangfu authored
254 255 256 257 258 259 260 261 262 263 264
		return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
	}
	//redis缓存
	tokenCache := cache.LoginTokenCache{}
	refreshToken, err := tokenCache.GetRefreshToken(loginToken.Account, loginToken.Platform)
	if err != nil {
		log.Logger.Debug(err.Error())
		return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
	}
	if refreshToken != refreshTokenCommand.RefreshToken {
		return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
yangfu authored
265
	}
yangfu authored
266
yangfu authored
267
	token, err := svr.getToken(loginToken)
yangfu authored
268 269 270
	if err != nil {
		return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
	}
yangfu authored
271 272 273
	return map[string]interface{}{
		"access": token["token"],
	}, err
yangfu authored
274 275 276
}

//GetUserMenus 获取用户信息
yangfu authored
277 278
func (svr AuthService) GetUserInfo(userInfoCommand *command.UserInfoCommand) (interface{}, error) {
	user, err := svr.getUserInfo(userInfoCommand.Operator)
yangfu authored
279 280 281 282 283 284 285 286
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return map[string]interface{}{
		"user": user,
	}, nil
}
yangfu authored
287
//GetUserMenus 获取用户信息-额外的数据
yangfu authored
288
func (svr AuthService) GetFavoriteMenus(userInfoCommand *command.UserInfoCommand) (interface{}, error) {
yangfu authored
289 290 291 292 293 294 295 296 297 298 299 300 301
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		userInfoCommand.Operator)
	resultUser, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
		UserId: int(userInfoCommand.Operator.UserId),
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return map[string]interface{}{
		"favoriteMenus": resultUser.FavoriteMenus,
	}, nil
}
yangfu authored
302
//GetUserMenus 获取用户菜单
yangfu authored
303
func (svr AuthService) GetUserMenus(userMenusCommand *command.UserMenusCommand) (interface{}, error) {
yangfu authored
304 305 306 307 308
	if userMenusCommand.Operator.UserId == 0 {
		return map[string]interface{}{
			"accessMenus": struct{}{},
		}, nil
	}
yangfu authored
309 310 311
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		userMenusCommand.Operator)
	resultMenu, err := creationUserGateway.UserAccessMenus(allied_creation_user.ReqUserAccessMenus{
yangfu authored
312 313 314
		UserId:         int(userMenusCommand.Operator.UserId),
		MenuCategory:   userMenusCommand.MenuCategory,
		ALLDisableMenu: userMenusCommand.ALLDisableMenu,
yangfu authored
315
		OrgId:          userMenusCommand.Operator.OrgId,
yangfu authored
316 317 318 319 320 321 322 323 324 325
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return map[string]interface{}{
		"accessMenus": resultMenu.Menus,
	}, nil
}

//GetUserMenus 获取用户组织
yangfu authored
326
func (svr AuthService) GetUserOrg(userOrgCommand *command.UserOrgCommand) (interface{}, error) {
yangfu authored
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(userOrgCommand.Operator)
	result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
		Offset:       0,
		Limit:        100,
		UserBaseId:   userOrgCommand.Operator.UserBaseId,
		UserType:     domain.UserTypeEmployee,
		EnableStatus: domain.UserStatusEnable,
		PullRealTime: true,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	var res = make([]interface{}, 0)
	for i := range result.Users {
		for j := range result.Users[i].UserOrg {
			org := result.Users[i].UserOrg[j]
			res = append(res, map[string]interface{}{
				"orgId":   org.OrgID,
				"orgName": org.OrgName,
			})
		}
	}
	return map[string]interface{}{
		"orgs": res,
	}, nil
}

//OrgSwitch 组织切换
yangfu authored
355
func (svr AuthService) OrgSwitch(switchOrgCommand *command.SwitchOrgCommand) (interface{}, error) {
yangfu authored
356 357 358
	if err := switchOrgCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
yangfu authored
359 360
	loginToken := domain.LoginToken{}
	err := loginToken.ParseToken(switchOrgCommand.Operator.Token)
yangfu authored
361
	if err != nil {
yangfu authored
362
		return nil, domain.NewApplicationError(domain.InvalidAccessToken)
yangfu authored
363
	}
yangfu authored
364 365
	loginToken.OrgId = switchOrgCommand.OrgId
	token, err := svr.getToken(loginToken)
yangfu authored
366 367 368 369 370
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	var userId int64
	if v, ok := token["userId"]; ok {
yangfu authored
371
		if vInt, ok := v.(int); !ok || vInt == 0 {
yangfu authored
372
			return nil, application.ThrowError(application.TRANSACTION_ERROR, "用户不存在")
yangfu authored
373 374
		} else {
			userId = int64(vInt)
yangfu authored
375 376
		}
	}
yangfu authored
377
	user, err := svr.getUserInfo(domain.Operator{UserId: userId, OrgId: loginToken.OrgId})
yangfu authored
378 379 380 381 382 383 384
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		switchOrgCommand.Operator)
	resultMenu, err := creationUserGateway.UserAccessMenus(allied_creation_user.ReqUserAccessMenus{
		UserId: int(userId),
yangfu authored
385
		OrgId:  switchOrgCommand.OrgId,
yangfu authored
386 387 388 389 390 391 392
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	var res = map[string]interface{}{
		"user":        user,
		"accessMenus": resultMenu.Menus,
yangfu authored
393
		"access":      token["token"],
yangfu authored
394 395 396 397 398
	}
	return res, nil
}

// CompanySignUp 企业注册
yangfu authored
399
func (svr AuthService) CompanySignUp(companySignUpCommand *command.CompanySignUpCommand) (interface{}, error) {
yangfu authored
400 401 402 403 404
	smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
	err := smsServeGateway.CheckSmsCode(companySignUpCommand.Phone, companySignUpCommand.SmsCode)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
yangfu authored
405
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
yangfu authored
406
	_, err = creationUserGateway.AuthCompanySignUp(allied_creation_user.ReqAuthCompanySignUp{
yangfu authored
407 408 409 410 411 412
		CompanyName:      companySignUpCommand.CompanyName,
		Phone:            companySignUpCommand.Phone,
		Password:         companySignUpCommand.Password,
		Contacts:         companySignUpCommand.Contacts,
		IndustryCategory: companySignUpCommand.IndustryCategory,
		Scale:            companySignUpCommand.Scale,
413 414 415 416 417

		LegalPerson:                companySignUpCommand.LegalPerson,
		SocialCreditCode:           companySignUpCommand.SocialCreditCode,
		BusinessLicenseAttachments: companySignUpCommand.BusinessLicenseAttachments,
		BusinessLicenseAddress:     companySignUpCommand.BusinessLicenseAddress,
yangfu authored
418 419 420 421 422 423 424
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return companySignUpCommand, err
}
yangfu authored
425 426 427 428 429 430 431 432 433 434 435 436 437 438
func (svr AuthService) UserSignUp(signUpCommand *command.UserSignUpCommand) (interface{}, error) {
	if err := signUpCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
	err := smsServeGateway.CheckSmsCode(signUpCommand.Phone, signUpCommand.SmsCode)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	_, err = creationUserGateway.AuthUserSignUp(allied_creation_user.ReqAuthUserSignUp{
		Name:     signUpCommand.Name,
		Phone:    signUpCommand.Phone,
		Password: signUpCommand.Password,
yangfu authored
439
		Referrer: signUpCommand.Referrer,
yangfu authored
440 441 442 443 444 445 446
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return signUpCommand, err
}
yangfu authored
447
// ResetPassword  重置密码(找回密码)
yangfu authored
448
func (svr AuthService) ResetPassword(resetPasswordCommand *command.ResetPasswordCommand) (interface{}, error) {
yangfu authored
449 450 451
	if err := resetPasswordCommand.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
	var phone = resetPasswordCommand.Phone
	if len(resetPasswordCommand.SmsCode) > 0 {
		smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
		err := smsServeGateway.CheckSmsCode(resetPasswordCommand.Phone, resetPasswordCommand.SmsCode)
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
	} else {
		pcc := cache.PhoneCheckCache{}
		var item = &cache.PhoneCheckItem{}
		if err := pcc.Get(resetPasswordCommand.SmsCodeIdentity, item); err != nil {
			log.Logger.Error(err.Error())
			return nil, application.ThrowError(application.BUSINESS_ERROR, "验证码已失效")
		}
		phone = item.Phone
yangfu authored
467
	}
468
yangfu authored
469 470 471
	// 2.重置密码
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	result, err := creationUserGateway.AuthResetPassword(allied_creation_user.ReqAuthResetPassword{
472
		Phone:    phone,
yangfu authored
473 474 475 476 477 478 479 480
		Password: resetPasswordCommand.Password,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return result, err
}
yangfu authored
481
func (svr AuthService) getUserInfo(operator domain.Operator) (interface{}, error) {
yangfu authored
482 483
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		operator)
484 485 486 487 488 489 490 491 492 493

	// 个人用户登录
	if operator.UserId == 0 && len(operator.Phone) != 0 {
		resultUser, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
			Account: operator.Phone,
		})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
		var user = map[string]interface{}{
yangfu authored
494
			"userId": resultUser.UserID,
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
			//"userOpenId": fmt.Sprintf("%v",resultUser.UserBaseID),
			"userInfo": map[string]interface{}{
				"userName":   resultUser.UserInfo.UserName,
				"userPhone":  resultUser.UserInfo.Phone,
				"userAvatar": resultUser.UserInfo.Avatar,
				"email":      resultUser.UserInfo.Email,
			},
			"department": struct{}{},
			"company":    map[string]interface{}{},
			"im":         resultUser.Im,
			"org":        struct{}{},
		}
		return user, nil
	}
	// 企业用户登录
yangfu authored
510 511 512 513 514 515
	resultUser, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
		UserId: int(operator.UserId),
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
yangfu authored
516
yangfu authored
517
	var user = map[string]interface{}{
yangfu authored
518
		"userId":   resultUser.UserId,
yangfu authored
519
		"userType": resultUser.UserType,
yangfu authored
520
		"userCode": resultUser.UserCode,
yangfu authored
521 522 523 524
		"userInfo": map[string]interface{}{
			"userName":   resultUser.UserInfo.UserName,
			"userPhone":  resultUser.UserInfo.Phone,
			"userAvatar": resultUser.UserInfo.Avatar,
525 526
			"userCode":   resultUser.UserInfo.UserCode,
			"email":      resultUser.UserInfo.Email,
yangfu authored
527
		},
yangfu authored
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
		"department":    resultUser.Department,
		"im":            resultUser.IM,
		"favoriteMenus": resultUser.FavoriteMenus,
	}
	if operator.OrgId > 0 {
		resultOrg, err := creationUserGateway.OrgGet(allied_creation_user.ReqOrgGet{
			OrgId: int(operator.OrgId),
		})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
		user["org"] = map[string]interface{}{
			"orgId":     resultOrg.OrgID,
			"orgName":   resultOrg.OrgName,
			"orgCode":   resultOrg.OrgCode,
			"companyId": resultOrg.CompanyID,
		}
	}
	if resultUser.Company != nil {
		user["company"] = map[string]interface{}{
yangfu authored
548 549
			"companyId":   resultUser.Company.CompanyId,
			"companyName": resultUser.Company.CompanyName,
tangxuhui authored
550
			"logo":        resultUser.Company.Logo,
yangfu authored
551 552
			"systemName":  resultUser.Company.SystemName,
			"address":     resultUser.Company.Address,
yangfu authored
553
		}
yangfu authored
554 555 556 557
	}
	return user, nil
}
yangfu authored
558
func (svr AuthService) getToken(loginToken domain.LoginToken) (map[string]interface{}, error) {
yangfu authored
559
	// 1.匹配账号对应的用户
yangfu authored
560
	currentUser, err := svr.matchUserV2(&loginToken)
yangfu authored
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}

	// 2. 更新LoginAccess
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var loginAccessRepository domain.LoginAccessRepository
	if loginAccessRepository, err = factory.CreateLoginAccessRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	_, lAccess, err := loginAccessRepository.Find(map[string]interface{}{
		"account":  loginToken.Account,
		"platform": loginToken.Platform,
	})
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	var currentAccess = &domain.LoginAccess{CreatedTime: time.Now()}
	if len(lAccess) > 0 {
		currentAccess = lAccess[0]
	}

	if _, err = currentAccess.ResetLoginAccess(loginToken); err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	//存数据库
	if _, err = loginAccessRepository.Save(currentAccess); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	//redis缓存
	tokenCache := cache.LoginTokenCache{}
	if err = tokenCache.SaveAccessToken(currentAccess); err != nil {
		return nil, err
	}
	if err = tokenCache.SaveRefreshToken(currentAccess); err != nil {
		return nil, err
	}

	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	nowTime := time.Now().Unix()
	token := map[string]interface{}{
		"refreshToken": currentAccess.RefreshToken,
		"accessToken":  currentAccess.AccessToken,
		"expiresIn":    currentAccess.AccessExpired - nowTime,
	}
	return map[string]interface{}{
		"token":  token,
		"userId": currentUser.UserId,
	}, nil
}

func (svr AuthService) matchUser(loginToken *domain.LoginToken) (*allied_creation_user.UserDetail, error) {
yangfu authored
626 627
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
628 629 630
		Phone:        loginToken.Account,
		UserType:     domain.UserTypeEmployee,
		EnableStatus: domain.UserStatusEnable,
yangfu authored
631 632
	})
	if err != nil {
yangfu authored
633
		return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
yangfu authored
634
	}
yangfu authored
635
	// 1 . 判定当前凭证的companyId,OrganizationId 是否在用户列表中
yangfu authored
636
	var currentOrgIsOK bool
yangfu authored
637
	var currentUser allied_creation_user.UserDetail
yangfu authored
638 639 640
loopUser1:
	for _, v := range userSearchResult.Users {
		for _, vv := range v.UserOrg {
641
			if vv.OrgID == int(loginToken.OrgId) && v.Company.Status == domain.CompanyAuthenticated {
yangfu authored
642
				currentOrgIsOK = true
yangfu authored
643
				currentUser = v
yangfu authored
644 645 646
				break loopUser1
			}
		}
yangfu authored
647 648 649 650 651
	}
	if !currentOrgIsOK {
	loopUser2:
		for _, v := range userSearchResult.Users {
			for _, vv := range v.UserOrg {
yangfu authored
652
				loginToken.OrgId = int64(vv.OrgID)
yangfu authored
653 654 655 656 657
				currentOrgIsOK = true
				currentUser = v
				break loopUser2
			}
		}
yangfu authored
658
	}
659
	if !currentOrgIsOK && loginToken.Platform == domain.LoginPlatformWeb {
yangfu authored
660 661
		return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录的公司组织不可用")
	}
662 663 664 665 666 667 668 669 670 671 672 673
	if currentOrgIsOK {
		loginToken.UserId = int64(currentUser.UserId)
		loginToken.UserBaseId = int64(currentUser.UserBaseId)
		loginToken.CompanyId = int64(currentUser.Company.CompanyId)
		var orgIds []int64
		for i := range currentUser.UserOrg {
			orgIds = append(orgIds, int64(currentUser.UserOrg[i].OrgID))
		}
		loginToken.OrgIds = orgIds
	}

	// 个人登录
yangfu authored
674
	if !currentOrgIsOK { //|| len(userSearchResult.Users) == 0
675 676 677 678 679 680
		userBase, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
			Account: loginToken.Account,
		})
		if err != nil {
			return nil, application.ThrowError(application.TRANSACTION_ERROR, "账号不存在")
		}
yangfu authored
681
		loginToken.UserId = int64(userBase.UserID)
682
		loginToken.UserBaseId = int64(userBase.UserBaseID)
yangfu authored
683 684 685 686 687 688 689 690 691 692 693 694 695
		if userBase.UserBaseID > 0 {
			cooperationUsers, _ := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
				UserBaseId:   int64(userBase.UserBaseID),
				UserType:     domain.UserTypeCooperation,
				EnableStatus: domain.UserStatusEnable,
			})
			if len(cooperationUsers.Users) > 0 {
				loginToken.CompanyId = int64(cooperationUsers.Users[0].Company.CompanyId)
				loginToken.UserId = int64(cooperationUsers.Users[0].UserId)
				loginToken.OrgId = int64(cooperationUsers.Users[0].Org.OrgId)
				currentUser = cooperationUsers.Users[0]
			}
		}
yangfu authored
696
	}
yangfu authored
697
	return &currentUser, nil
yangfu authored
698 699
}
yangfu authored
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
func (svr AuthService) matchUserV2(loginToken *domain.LoginToken) (*allied_creation_user.UserDetail, error) {
	var users []allied_creation_user.UserDetail
	var currentUser *allied_creation_user.UserDetail
	var defaultUser *allied_creation_user.UserDetail
	var ok bool
	var mapOrgUser = make(map[int]*allied_creation_user.UserDetail)
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	switch loginToken.Platform {
	case domain.LoginPlatformWeb:
		userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
			Phone:        loginToken.Account,
			UserType:     domain.UserTypeEmployee,
			EnableStatus: domain.UserStatusEnable,
		})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
		}
		users = userSearchResult.Users
	case domain.LoginPlatformApp:
		userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
			Phone:        loginToken.Account,
			UserType:     domain.UserTypeEmployee | domain.UserTypeCooperation | domain.UserTypeVisitor,
			EnableStatus: domain.UserStatusEnable,
		})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
		}
		users = userSearchResult.Users
	case domain.LoginPlatformOperatorWeb:
		userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
			Phone:        loginToken.Account,
			UserType:     domain.UserTypeOperationAdmin,
			EnableStatus: domain.UserStatusEnable,
		})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
		}
		users = userSearchResult.Users
	}
	if len(users) == 0 {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, "账号不存在")
	}

	for index, user := range users {
		if user.Company != nil && user.Company.Status != domain.CompanyAuthenticated {
			continue
		}
		for _, userOrg := range user.UserOrg {
			mapOrgUser[userOrg.OrgID] = &users[index]
			if defaultUser == nil {
				defaultUser = &users[index]
			}
		}
	}
	if defaultUser == nil {
		defaultUser = &users[0]
	}
	//切换组织
	if loginToken.OrgId != 0 {
		if currentUser, ok = mapOrgUser[int(loginToken.OrgId)]; !ok { //&& loginToken.Platform == domain.LoginPlatformWeb
			return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录的公司组织不可用")
		}
	}
	// 使用默认账号
	if currentUser == nil {
		currentUser = defaultUser
	}

	SetLoginToken(loginToken, currentUser)

	return currentUser, nil
}

func SetLoginToken(loginToken *domain.LoginToken, currentUser *allied_creation_user.UserDetail) {
	// 当前登录的公司用户信息
	loginToken.UserId = int64(currentUser.UserId)
	loginToken.UserBaseId = int64(currentUser.UserBaseId)
	if currentUser.Company != nil {
		loginToken.CompanyId = int64(currentUser.Company.CompanyId)
	}

	// 关联的组织
	var orgIds []int64
	for i := range currentUser.UserOrg {
		orgIds = append(orgIds, int64(currentUser.UserOrg[i].OrgID))
		// 默认组织
		if loginToken.OrgId == 0 {
			loginToken.OrgId = int64(currentUser.UserOrg[i].OrgID)
		}
	}
	loginToken.OrgIds = orgIds
}
yangfu authored
793
//GetCompanyOrgsByUser 获取登录用户的公司组织列表
yangfu authored
794
func (svr AuthService) GetCompanyOrgsByUser(queryParam *query.GetCompanyOrgsByUserQuery) (interface{}, error) {
yangfu authored
795 796
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(queryParam.Operator)
	result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
yangfu authored
797
		Phone:        queryParam.Operator.Phone,
yangfu authored
798 799
		UserType:     domain.UserTypeEmployee,
		PullRealTime: true,
yangfu authored
800
		EnableStatus: domain.UserStatusEnable,
yangfu authored
801 802 803 804 805
	})
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	var (
yangfu authored
806 807 808
		companys   []dto.CompanyItem
		orgs       []dto.OrgItem
		mapCompany = make(map[int]interface{})
yangfu authored
809 810
	)
yangfu authored
811 812
	for i := range result.Users {
		user := result.Users[i]
yangfu authored
813
		if _, ok := mapCompany[user.Company.CompanyId]; !ok && len(user.UserOrg) > 0 {
yangfu authored
814 815 816 817
			companys = append(companys, dto.CompanyItem{
				CompanyId:   user.Company.CompanyId,
				CompanyName: user.Company.CompanyName,
			})
818 819 820
			if user.Company.Status != domain.CompanyAuthenticated {
				continue
			}
yangfu authored
821 822 823
		}
		for j := range user.UserOrg {
			org := user.UserOrg[j]
yangfu authored
824
			orgs = append(orgs, dto.OrgItem{
yangfu authored
825 826 827
				OrganizationId:   org.OrgID,
				OrganizationName: org.OrgName,
				CompanyId:        user.Company.CompanyId,
yangfu authored
828 829 830 831 832 833 834 835 836 837 838 839
			})
		}
	}

	data := map[string]interface{}{
		"companys":      companys,
		"organizations": orgs,
	}
	return data, nil
}

//GetQrcode 获取扫码登录需要的二维码
yangfu authored
840
func (svr AuthService) GetQrcode() (interface{}, error) {
yangfu authored
841
	qrcodeMessage := domain.QrcodeMessage{}
yangfu authored
842
	_, err := qrcodeMessage.Init()
yangfu authored
843 844 845 846
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	qrCache := cache.LoginQrcodeCache{}
yangfu authored
847
	err = qrCache.Save(qrcodeMessage)
yangfu authored
848 849 850 851
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	data := map[string]interface{}{
yangfu authored
852
		"key": qrcodeMessage.Token,
yangfu authored
853 854 855 856 857
	}
	return data, nil
}

//CheckSmsCode 验证手机短信验证码
yangfu authored
858
func (svr AuthService) CheckSmsCode(smsCodeCommand *command.CheckSmsCodeCommand) (interface{}, error) {
yangfu authored
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
	smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
	err := smsServeGateway.CheckSmsCode(smsCodeCommand.Phone, smsCodeCommand.SmsCode)
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	uid := uuid.New()
	pcc := cache.PhoneCheckCache{}
	if err := pcc.Add(uid.String(), cache.PhoneCheckItem{
		Phone:           smsCodeCommand.Phone,
		SmsCodeIdentity: uid.String(),
		Action:          smsCodeCommand.Action,
	}); err != nil {
		log.Logger.Error(err.Error())
		return nil, application.ThrowError(application.BUSINESS_ERROR, "系统错误")
	}
	return map[string]interface{}{
		"smsCodeIdentity": uid.String(),
	}, nil
}
yangfu authored
878 879 880 881 882

func (svr *AuthService) CaptchaInit(request *query.CaptchaInitRequest) (interface{}, error) {
	var rsp map[string]interface{}
	var err error
yangfu authored
883 884
	lib := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
	status, responseBt := lib.PreProcess("", request.UserIp)
yangfu authored
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	var geetestRsp geetest.FailbackRegisterRespnse
	json.Unmarshal(responseBt, &geetestRsp)
	rspData := map[string]interface{}{
		"success":    geetestRsp.Success,
		"gt":         geetestRsp.GT,
		"challenge":  geetestRsp.Challenge,
		"newCaptcha": geetestRsp.NewCaptcha,
	}
	if status == 0 {
		return nil, application.ThrowError(application.BUSINESS_ERROR, "获取图形验证码失败,请重试")
	}

	rsp = rspData
	return rsp, err
}
yangfu authored
900 901 902 903 904

/*******************运营登录**********************/
//AuthLogin 用户登录
func (svr AuthService) AuthAdminLogin(loginCommand *command.LoginPwdCommand) (interface{}, error) {
	login := &command.LoginCommand{
yangfu authored
905 906 907 908 909 910
		GrantType:     "signInPassword",
		Phone:         loginCommand.Username,
		Password:      loginCommand.Password,
		SessionMode:   loginCommand.SessionMode,
		DeviceType:    loginCommand.DeviceType,
		LoginPlatform: domain.LoginPlatformOperatorWeb,
yangfu authored
911 912 913
	}
	return svr.AuthLogin(login)
}
yangfu authored
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

//AuthLogin 用户登录
//func (svr AuthService) AuthAdminLoginBak(loginCommand *command.LoginPwdCommand) (interface{}, error) {
//	if err := loginCommand.ValidateCommand(); err != nil {
//		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
//	}
//	if len(loginCommand.Username) == 0 {
//		return nil, application.ThrowError(application.BUSINESS_ERROR, "账号不存在")
//	}
//	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
//	users, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
//		UserType: domain.UserTypeOperationAdmin,
//		Phone:    loginCommand.Username,
//	})
//	if err != nil {
//		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
//	}
//	if len(users.Users) == 0 {
//		return nil, application.ThrowError(application.BUSINESS_ERROR, "账号不存在")
//	}
//	login := &command.LoginCommand{
//		GrantType:   "signInPassword",
//		Phone:       loginCommand.Username,
//		Password:    loginCommand.Password,
//		SessionMode: loginCommand.SessionMode,
//		DeviceType:  loginCommand.DeviceType,
//	}
//	if len(loginCommand.CaptchaChallenge) > 0 {
//		geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
//		validateResult := geetest.SuccessValidate(loginCommand.CaptchaChallenge, loginCommand.CaptchaValidate, loginCommand.CaptchaSeccode, "", "")
//		if !validateResult {
//			log.Logger.Error("validate captcha fail")
//		}
//	}
//	return svr.AuthLogin(login)
//}