作者 陈志颖

合并分支 'dev' 到 'master'

Dev



查看合并请求 !46
# 合伙人项目
\ No newline at end of file
# 合伙人项目
### 系统架构
### 领域驱动设计
### 核心登录流程
... ...
... ... @@ -66,6 +66,8 @@ spec:
value: "31543"
- name: LOG_LEVEL
value: "debug"
- name: LOG_PREFIX
value: "[partner_dev]"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
... ...
... ... @@ -66,6 +66,8 @@ spec:
value: "31544"
- name: LOG_LEVEL
value: "debug"
- name: LOG_PREFIX
value: "[partner_prd]"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
... ...
... ... @@ -66,6 +66,8 @@ spec:
value: "31543"
- name: LOG_LEVEL
value: "debug"
- name: LOG_PREFIX
value: "[partner_test]"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
... ...
... ... @@ -23,5 +23,8 @@ func main() {
//注册事件
event.InitEventCenter()
//启动kafaka消息订阅
//go sarama.Run()
beego.Run()
}
... ...
... ... @@ -2,6 +2,10 @@ package auth
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/tiptok/gocomm/xa/eda"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
... ... @@ -14,9 +18,6 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
"strconv"
"strings"
"time"
)
// 该方法废弃
... ... @@ -301,49 +302,126 @@ func UCenterRevoke(header *protocol.RequestHeader, userId int64) (rsp *protocol.
return
}
// 企业平台-多公司登录
// 企业平台-密码校验
func PasswordLogin(header *protocol.RequestHeader, request *protocol.LoginRequest) (v interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
loginSvr = domain_service.NewPgLoginService(transactionContext)
)
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
// loginSvr 初始化
loginSvr.Init(request.Phone)
if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
v = map[string]interface{}{}
err = protocol.NewErrWithMessage(10001)
return
}
if len(request.Password) == 0 {
v = map[string]interface{}{}
err = protocol.NewCustomMessage(1, "密码不能为空!")
return
}
if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
v = map[string]interface{}{}
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
v = map[string]interface{}{}
err = transactionContext.CommitTransaction()
return
}
/**
* @Author SteveChan
* @Description // 企业平台-多公司登录,判断是否高管
* @Date 15:01 2021/1/12
* @Param
* @return
**/
func CompaniesLogin(header *protocol.RequestHeader, request *protocolx.CenterCompanysRequest) (v interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
imInfo *domain.ImInfo
loginSvr = domain_service.NewPgLoginService(transactionContext)
)
// 转换手机号码
phoneId, e := strconv.Atoi(request.Phone)
if e != nil {
log.Error(e)
e = protocol.NewErrWithMessage(2)
return
}
rsp := &protocolx.CenterCompanysResponse{}
// 启动事务
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
// 通过短信验证码登录的游客,注册一个账号到配置的公司去(ios审核使用)
if request.GrantType == protocol.LoginBySmsCode {
e := loginSvr.RegistryGuest(request.Phone)
if e != nil {
log.Error(e)
// 通过密码或校验码登录的普通用户或通过校验码登录的游客,注册一个账号到配置的公司去
if request.GrantType == protocol.LoginBySmsCode || request.GrantType == protocol.LoginByPassword {
userErr := loginSvr.RegistryUser(request.Phone)
if userErr != nil {
log.Error(userErr)
}
}
// loginSvr 初始化
loginSvr.Init(request.Phone)
if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
err = protocol.NewErrWithMessage(10001)
_ = loginSvr.Init(request.Phone)
// 所有公司有效用户不存在、所有公司有效合伙人不存在、所有公司合伙人不存在
if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 && len(loginSvr.NormalPartnerInfo) == 0 {
err = protocol.NewErrWithMessage(10001) // 用户不存在
return
}
switch request.GrantType {
case protocol.LoginByPassword:
if len(request.Password) == 0 {
err = protocol.NewCustomMessage(1, "密码不能为空!")
return
}
if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
manageLoginErr := loginSvr.ManagerLogin(request.Phone, request.Password)
fmt.Print("用户登录:", manageLoginErr, "\n")
partnerLoginErr := loginSvr.PartnerLogin(request.Phone, request.Password)
fmt.Print("合伙人登录:", partnerLoginErr, "\n")
if manageLoginErr != nil && partnerLoginErr != nil {
if len(loginSvr.PartnerInfo) == 0 { // 不存在有效用户
err = protocol.NewErrWithMessage(10008)
return
}
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
} else if manageLoginErr != nil && partnerLoginErr == nil {
if len(loginSvr.PartnerInfo) == 1 && len(loginSvr.NormalUsers) == 0 {
if loginSvr.PartnerInfo[0].CompanyId == int64(constant.DEFAULT_GUEST_COMPANY) {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
}
}
break
case protocol.LoginBySmsCode:
... ... @@ -372,8 +450,9 @@ func CompaniesLogin(header *protocol.RequestHeader, request *protocolx.CenterCom
// 获取统计信息(合伙人/高管)
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
if !loginSvr.HasAvailableCompany {
err = protocol.NewErrWithMessage(10008) //账号禁用
if !loginSvr.HasAvailableCompany && !loginSvr.HasAvailableManagerCompany { // 判断合伙人或者高管是否有可访问的公司
err = protocol.NewErrWithMessage(10008) //账号禁用, 抱歉,企业管理员未帮您开通权限。如需访问,请联系企业管理员
return
}
... ... @@ -395,33 +474,45 @@ func CompaniesLogin(header *protocol.RequestHeader, request *protocolx.CenterCom
rsp.Phone = request.Phone
rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)
//添加手机对应的凭证
// 添加手机对应的凭证
userAuth.NewRedisUserCredential(request.Phone).AddAuth(rsp.Credentials)
v = map[string]interface{}{"center": rsp}
err = transactionContext.CommitTransaction()
return
}
// 企业平台-多公司登录 - 通过凭证
/**
* @Author SteveChan
* @Description // 企业平台-多公司登录 - 通过凭证,判断是否高管
* @Date 15:00 2021/1/12
* @Param
* @return
**/
func CompaniesLoginByCredential(header *protocol.RequestHeader, request *protocolx.CompanysRequest) (rsp *protocolx.CompanysResponse, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
loginSvr = domain_service.NewPgLoginService(transactionContext)
claim *utils.UserTokenClaims
)
rsp = &protocolx.CompanysResponse{}
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
//凭证是否存在
if constant.DISENABLE_MULTI_DEVICE_LOGIN {
if credential, e := userAuth.NewRedisUserCredential(claim.Phone).GetAuth(); e != nil || !strings.EqualFold(credential, request.Credentials) {
... ... @@ -432,10 +523,23 @@ func CompaniesLoginByCredential(header *protocol.RequestHeader, request *protoco
}
// loginSvr 初始化
loginSvr.Init(claim.Phone)
_ = loginSvr.Init(claim.Phone)
// 高管标志位初始化
_ = loginSvr.InitSenior(claim.Phone)
// 合伙人标志位初始化
_ = loginSvr.InitPartner(claim.Phone)
if len(loginSvr.PartnerInfo) == 0 && len(loginSvr.Users) == 0 {
err = protocol.NewErrWithMessage(4104)
return
}
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
if !loginSvr.HasAvailableCompany {
if !loginSvr.HasAvailableCompany && !loginSvr.HasAvailableManagerCompany {
err = protocol.NewErrWithMessage(4140, err) //账号禁用
return
}
... ... @@ -444,7 +548,13 @@ func CompaniesLoginByCredential(header *protocol.RequestHeader, request *protoco
return
}
// 登录
/**
* @Author SteveChan
* @Description //TODO 登录
* @Date 15:05 2021/1/15
* @Param
* @return
**/
func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (rsp *protocol.LoginResponse, err error) {
var (
claim *utils.UserTokenClaims
... ... @@ -480,6 +590,15 @@ func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (
}
switch request.IdType {
case int(protocolx.AdminTypePartner):
// 用户信息检索
//if u, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
// userId = u.Id
// if !u.IsEnable() {
// err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
// return
// }
//}
// 合伙人检索
if p, e := PartnerInfoRepository.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
userId = p.Id
if !p.IsEnable() {
... ... @@ -500,9 +619,10 @@ func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (
}
break
case int(protocolx.AdminTypeManager):
// 用户信息检索
if p, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
userId = p.Id
if !p.IsEnable() {
if !p.IsEnable() || !p.IsUserSenior() {
err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
return
}
... ... @@ -520,6 +640,7 @@ func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (
err = protocol.NewErrWithMessage(2, fmt.Errorf("idType :%v not in range (1,2)", request.IdType)) //用户类型有误
return
}
if userId == 0 {
err = protocol.NewErrWithMessage(10001, err) //账号不存在
return
... ...
... ... @@ -68,6 +68,7 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
rsp.User.Salesman = map[string]interface{}{}
}
}
funcManagerInfo := func() {
if user, err = UsersRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
... ... @@ -196,25 +197,33 @@ func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoReques
UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
company *domain.Company
user *domain.Users
//loginSvr = domain_service.NewPgLoginService(transactionContext)
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
rsp = &protocol.UserInfoResponse{}
rspMap := make(map[string]interface{})
// 获取合伙人信息
funcPartnerInfo := func() {
if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if company, err = CompanyRepository.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
return
}
var miniProgram map[string]interface{}
if len(company.Applets) > 0 {
if company.Applets[0].Valid() {
miniProgram = make(map[string]interface{})
... ... @@ -228,6 +237,7 @@ func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoReques
miniProgram["title"] = company.Applets[0].Name
}
}
u := userx.User{
Id: partnerInfo.Id,
PartnerName: partnerInfo.PartnerName,
... ... @@ -265,18 +275,22 @@ func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoReques
} else {
u.CooperateCompany.Salesman = map[string]interface{}{}
}
rspMap["user"] = u
rsp = rspMap
}
// 获取管理员信息
funcManagerInfo := func() {
if user, err = UsersRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if company, err = CompanyRepository.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
return
}
rspMap["user"] = userx.User{
Id: user.Id,
PartnerName: user.Name,
... ... @@ -288,9 +302,14 @@ func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoReques
MiniProgram: nil,
},
}
rsp = rspMap
}
//判断是否高管
//phone := strconv.Itoa(header.SimNum)
//ok, _ := loginSvr.CheckIsSenior(phone, header.CompanyId)
switch header.AdminType {
case int(protocolx.AdminTypePartner):
funcPartnerInfo()
... ... @@ -302,6 +321,7 @@ func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoReques
funcPartnerInfo()
break
}
err = transactionContext.CommitTransaction()
return
}
... ...
... ... @@ -9,6 +9,7 @@ const SERVICE_NAME = "partner"
var LOG_LEVEL = "debug"
var LOG_File = "app.log"
var LOG_PREFIX = "[partner_dev]"
var MMM_SMS_SERVICE_HOST = "https://sms.fjmaimaimai.com:9897"
var UCENTER_SERVICE_HOST = "https://suplus-ucenter-test.fjmaimaimai.com"
... ... @@ -17,7 +18,7 @@ var UCENTER_APP_KEY = "0c2c2a23dfc64ae230f5c54ab243ab52"
var BUSINESS_ADMIN_SERVICE_HOST = "http://suplus-business-admin-test.fjmaimaimai.com"
var BUSINESS_ADMIN_PLATFORM_ID = "25" //合伙人模块
var DEFAULT_GUEST_COMPANY int = 10011
var DEFAULT_GUEST_COMPANY int = 358
var SHARE_SHOP_PREVIEW_IMADGE = "https://media.fjmaimaimai.com/image/default/3E0C7050C13147CE8C7AF86C75F904E9-6-2.jpg" //分享店铺预览图
var WEHAT_MINI_PROGRAM_VERSION_TYPE = 2 //0:正式版 1:开发版 2:体验版
... ... @@ -28,6 +29,9 @@ func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
if os.Getenv("LOG_PREFIX") != "" {
LOG_PREFIX = os.Getenv("LOG_PREFIX")
}
if os.Getenv("UCENTER_SERVICE_HOST") != "" {
UCENTER_SERVICE_HOST = os.Getenv("UCENTER_SERVICE_HOST")
}
... ...
... ... @@ -2,4 +2,4 @@ package constant
const TOPIC_UCENT_USER_CHANGE_PHONE = "ucent-user-changePhone"
const KAFKA_HOSTS = "106.52.15.41:9092"
const KAFKA_HOSTS = "127.0.0.1:9092"
... ...
... ... @@ -46,6 +46,8 @@ type Users struct {
AccessPartners []*PartnerInfo
// 1普通用户 2主管理员
AdminType int8 `json:"adminType"`
// 是否高管
IsSenior int8 `json:"isSenior"`
}
func (Users *Users) AccessPartnerIds() []int64 {
... ... @@ -71,6 +73,11 @@ func (m *Users) IsEnable() bool {
return m.Status == 1
}
// 账号是否是高管
func (m *Users) IsUserSenior() bool {
return m.IsSenior == 1
}
func (m *Users) Identify() interface{} {
if m.Id == 0 {
return nil
... ...
... ... @@ -21,8 +21,8 @@ func NewPgAuthService(ctx *transaction.TransactionContext) *PgAuthService {
}
func (s *PgAuthService) ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error) {
errPartner := s.partner.ChangeUserPhone(userId, newPhone, oldPhone)
errManager := s.manager.ChangeUserPhone(userId, newPhone, oldPhone)
errPartner := s.partner.ChangeUserPhone(userId, newPhone, oldPhone) // 合伙人修改手机号
errManager := s.manager.ChangeUserPhone(userId, newPhone, oldPhone) // 高管修改手机号
return errResolve(errPartner, errManager)
}
func (s *PgAuthService) ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error) {
... ...
package domain_service
import (
"fmt"
"github.com/tiptok/gocomm/xa/eda"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
... ... @@ -20,11 +21,19 @@ import (
type PgLoginService struct {
Phone string
eda.EventCenterPublisher
PartnerInfo []*domain.PartnerInfo
Users []*domain.Users
transactionContext *transaction.TransactionContext
PartnerInfo []*domain.PartnerInfo // 所有公司有效合伙人
GuestPartnerInfo []*domain.PartnerInfo // 游客公司合伙人
GuestPartnerInfoAvailable []*domain.PartnerInfo // 游客公司有效合伙人
NormalPartnerInfo []*domain.PartnerInfo // 所有公司合伙人
IsPartnerInfo []*domain.PartnerInfo // 真实公司有效合伙人
Users []*domain.Users // 所有公司有效用户
NormalUsers []*domain.Users // 所有公司用户
IsSenior []*domain.Users // 所有公司有效高管
IsRealSenior []*domain.Users // 真实公司的有效高管
transactionContext *transaction.TransactionContext
// 标识:登录的账号信息是否有可用的公司, true:有 false:没有
HasAvailableCompany bool
HasAvailableCompany bool // 是否有可访问的合伙公司
HasAvailableManagerCompany bool // 是否有可访问的高管公司
}
func (svr *PgLoginService) Init(phone string) (err error) {
... ... @@ -32,12 +41,118 @@ func (svr *PgLoginService) Init(phone string) (err error) {
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
)
svr.Phone = phone
// 所有公司合伙人
_, svr.NormalPartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "sortByCreateTime": "ASC"})
// 所有公司有效合伙人
_, svr.PartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC"})
// 真实公司有效合伙人
_, svr.IsPartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC", "isNot": constant.DEFAULT_GUEST_COMPANY})
// 游客公司合伙人
_, svr.GuestPartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "sortByCreateTime": "ASC", "companyId": constant.DEFAULT_GUEST_COMPANY})
// 游客公司有效合伙人
_, svr.GuestPartnerInfoAvailable, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC", "companyId": constant.DEFAULT_GUEST_COMPANY})
// 所有公司用户
_, svr.NormalUsers, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "sortByCreateTime": "ASC", "deleteAtIsNull": true})
// 所有公司有效用户
_, svr.Users, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true})
// 所有公司有效高管
_, svr.IsSenior, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true, "isSenior": 1})
// 真实公司有效高管
_, svr.IsRealSenior, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true, "isSenior": 1, "isNot": constant.DEFAULT_GUEST_COMPANY})
return nil
}
func (svr *PgLoginService) InitNormal(phone string) (err error) {
var (
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
)
svr.Phone = phone
_, svr.NormalPartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "sortByCreateTime": "ASC"})
return nil
}
func (svr *PgLoginService) InitSenior(phone string) (err error) {
var (
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
)
svr.Phone = phone
_, svr.IsSenior, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true, "isSenior": 1})
return nil
}
func (svr *PgLoginService) InitPartner(phone string) (err error) {
var (
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
)
svr.Phone = phone
_, svr.IsPartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC", "isNot": constant.DEFAULT_GUEST_COMPANY})
return nil
}
/**
* @Author SteveChan
* @Description // 判断是否是高管
* @Date 10:44 2021/1/12
* @Param
* @return
**/
func (svr *PgLoginService) CheckIsSenior(phone string, companyId int64) (ok bool, err error) {
var (
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
)
svr.Phone = phone
user, err := UsersRepository.FindOne(map[string]interface{}{"phone": phone, "status": 1, "companyId": companyId, "deleteAtIsNull": true})
if err != nil {
return false, err
} else {
if user.IsSenior == 1 {
ok = true
} else if user.IsSenior == 2 {
ok = false
}
}
return ok, nil
}
/**
* @Author SteveChan
* @Description // 判断是否合伙人
* @Date 13:25 2021/1/13
* @Param
* @return
**/
func (svr *PgLoginService) CheckIsPartner(phone string, companyId int64) (ok bool, err error) {
var (
PartnerInfoRepository, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
)
svr.Phone = phone
user, err := PartnerInfoRepository.FindOne(map[string]interface{}{"account": phone, "status": 1})
if err != nil {
return false, err
}
if user != nil {
ok = true
} else {
ok = false
}
return ok, nil
}
//合伙人登录
func (svr *PgLoginService) PartnerLogin(phone string, password string) (err error) {
if len(svr.PartnerInfo) == 0 {
... ... @@ -46,7 +161,7 @@ func (svr *PgLoginService) PartnerLogin(phone string, password string) (err erro
return
}
if !strings.EqualFold(svr.PartnerInfo[0].Password, password) {
err = protocol.NewCustomMessage(1, "密码输入误!")
err = protocol.NewCustomMessage(1, "密码输入误!")
return
}
return
... ... @@ -73,10 +188,12 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
response := make(map[string]interface{})
response["id"] = protocolx.AdminTypePartner
response["name"] = protocolx.AdminTypePartnerName
if len(svr.PartnerInfo) == 0 {
response["companys"] = make([]struct{}, 0)
return response, nil
}
var (
OrderDao, _ = dao.NewOrderBaseDao(svr.transactionContext)
BusinessBonusDao, _ = dao.NewBusinessBonusDao(svr.transactionContext)
... ... @@ -87,6 +204,7 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
)
doGetCompanyIds := func() []int64 {
var companies []int64
for i := range svr.PartnerInfo {
... ... @@ -94,6 +212,7 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
}
return companies
}
doGetPartnerIds := func() []int64 {
var array []int64
for i := range svr.PartnerInfo {
... ... @@ -101,17 +220,21 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
}
return array
}
companyList = svr.GetCompanyList(doGetCompanyIds)
if len(companyList) == 0 {
return response, nil
}
totalBonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), OrderTypes: domain.UserOrderTypes(domain.Career)})
if e != nil {
return response, e
}
if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), IsDisable: 1}); e == nil {
totalBonus.Bonus += businessBonus.Bonus
}
_, allPartnerCategory, e = PartnerCategoryInfoRepository.Find(map[string]interface{}{"sortById": domain.ASC})
var mapPartnerBussinessBonus = make(map[int64]*domain.BusinessBonus)
if _, bussinessBonus, e := BusinessBonusRepository.Find(map[string]interface{}{"inPartnerIds": doGetPartnerIds(), "isDisable": 1}); e == nil {
... ... @@ -129,6 +252,7 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
mapCompanyAdminUsers[adminUsers[i].CompanyId] = adminUsers[i]
}
}
var companys = make([]*Company, 0)
for i := range companyList {
c := companyList[i]
... ... @@ -166,13 +290,26 @@ func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
}
companys = append(companys, item)
}
if len(companys) > 0 {
svr.HasAvailableCompany = true
}
if len(companys) > 1 || len(svr.IsRealSenior) > 0 { // 有真实合伙公司或高管公司时,过滤游客公司
var companies = make([]*Company, 0)
for _, company := range companys {
if company.CompanyBase.Id != int64(constant.DEFAULT_GUEST_COMPANY) {
companies = append(companies, company)
}
}
companys = companies
}
response["companys"] = companys
return response, nil
}
// 高管统计信息
func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
response := make(map[string]interface{})
response["id"] = protocolx.AdminTypeManager
... ... @@ -187,8 +324,8 @@ func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
)
doGetCompanyIds := func() []int64 {
var companies []int64
for i := range svr.Users {
companies = append(companies, svr.Users[i].CompanyId)
for i := range svr.IsSenior {
companies = append(companies, svr.IsSenior[i].CompanyId)
}
return companies
}
... ... @@ -200,9 +337,9 @@ func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
if constant.POSTGRESQL_DB_NAME != "partner_dev" {
//通过企业平台 校验模块权限
var user *domain.Users
for j := range svr.Users {
if svr.Users[j].CompanyId == c.Id {
user = svr.Users[j]
for j := range svr.IsSenior {
if svr.IsSenior[j].CompanyId == c.Id {
user = svr.IsSenior[j]
break
}
}
... ... @@ -219,12 +356,23 @@ func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
companys = append(companys, item)
}
if len(companys) > 0 {
svr.HasAvailableCompany = true
svr.HasAvailableManagerCompany = true
}
if len(companys) > 1 || len(svr.IsPartnerInfo) > 0 { // 有真实合伙公司或高管公司时,过滤游客公司
var companies = make([]protocol.CompanyBase, 0)
for _, company := range companys {
if company.Id != int64(constant.DEFAULT_GUEST_COMPANY) {
companies = append(companies, company)
}
}
companys = companies
}
response["companys"] = companys
return response, nil
}
func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*domain.Company {
var (
CompanyRepository, _ = repository.NewCompanyRepository(svr.transactionContext)
... ... @@ -242,6 +390,7 @@ func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*d
}
return companyList
}
func (svr *PgLoginService) GetJoinWays(partnerCategory []*domain.PartnerCategoryInfo, partnerInfo *domain.PartnerInfo, bonus float64) []joinWay {
searchCategory := func(partnerCategory []*domain.PartnerCategoryInfo, id int64) *domain.PartnerCategoryInfo {
for i := range partnerCategory {
... ... @@ -285,16 +434,182 @@ func computeBonusPercent(totalBonus float64, bonus float64) float64 {
return utils.Decimal(bonus / totalBonus)
}
/**
* @Author SteveChan
* @Description // 注册用户到合伙人
* @Date 13:52 2021/1/13
* @Param
* @return
**/
func (svr *PgLoginService) RegistryUser(phone string) error {
var (
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
isPartner bool
isPartnerAvailable bool
isGuestPartner bool
isGuestPartnerAvailable bool
isUser bool
isUserAvailable bool
isUserSenior bool
)
partnerInfo, _ := PartnerInfoService.FindOne(map[string]interface{}{"account": phone, "isNot": constant.DEFAULT_GUEST_COMPANY}) // 合伙人在正常公司是否存在
if partnerInfo == nil {
isPartner = false
} else {
isPartner = true
}
partnerAvailableInfo, errPartner := PartnerInfoService.FindOne(map[string]interface{}{"account": phone, "status": 1, "isNot": constant.DEFAULT_GUEST_COMPANY}) // 合伙人在正常公司是否有效
if partnerAvailableInfo == nil {
isPartnerAvailable = false
} else {
isPartnerAvailable = true
}
guestInfo, _ := PartnerInfoService.FindOne(map[string]interface{}{"account": phone, "companyId": constant.DEFAULT_GUEST_COMPANY}) // 合伙人是否存在游客公司
if guestInfo == nil {
isGuestPartner = false
} else {
isGuestPartner = true
}
guestAvailableInfo, _ := PartnerInfoService.FindOne(map[string]interface{}{"account": phone, "status": 1, "companyId": constant.DEFAULT_GUEST_COMPANY}) // 合伙人在游客公司是否有效
if guestAvailableInfo == nil {
isGuestPartnerAvailable = false
} else {
isGuestPartnerAvailable = true
}
user, _ := UsersRepository.FindOne(map[string]interface{}{"phone": phone, "deleteAtIsNull": true}) // 用户是否存在
if user == nil {
isUser = false
} else {
isUser = true
}
userAvailable, _ := UsersRepository.FindOne(map[string]interface{}{"phone": phone, "status": 1, "deleteAtIsNull": true}) // 用户是否有效
if userAvailable == nil {
isUserAvailable = false
} else {
isUserAvailable = true
}
senior, _ := UsersRepository.FindOne(map[string]interface{}{"phone": phone, "status": 1, "isSenior": 1, "deleteAtIsNull": true}) // 用户是否是高管
if senior == nil {
isUserSenior = false
} else {
isUserSenior = true
}
fmt.Print("合伙人在正常公司存在?", isPartner, "\n")
fmt.Print("合伙人在正常公司有效?", isPartnerAvailable, "\n")
fmt.Print("合伙人在游客公司存在?", isGuestPartner, "\n")
fmt.Print("合伙人在游客公司有效?", isGuestPartnerAvailable, "\n")
fmt.Print("用户存在?", isUser, "\n")
fmt.Print("用户有效?", isUserAvailable, "\n")
fmt.Print("用户高管?", isUserSenior, "\n")
// 用户在正常公司存在且无效或者不存在、合伙人在正常公司存在且无效或者不存在、合伙人在游客公司存在且无效,更新游客公司合伙人状态
//if (isUser && !isUserAvailable || !isUser) && (isPartner && !isPartnerAvailable || !isPartner) && (isGuestPartner && !isGuestPartnerAvailable) {
// _, err := svr.transactionContext.PgTx.Model(&models.PartnerInfo{
// CompanyId: int64(constant.DEFAULT_GUEST_COMPANY),
// PartnerName: phone,
// Account: phone,
// Password: "7c4a8d09ca3762af61e59520943dc26494f8941b",
// PartnerCategory: 1,
// RegionInfo: &domain.RegionInfo{
// RegionName: "客户区域",
// RegionId: 0,
// },
// Status: 1,
// CooperateTime: time.Now(),
// CreateAt: time.Now(),
// UpdateAt: time.Now(),
// PartnerCategoryInfos: []*models.PartnerCategoryInfo{&models.PartnerCategoryInfo{Id: 1, Code: phone}},
// Salesman: []*domain.Salesman{&domain.Salesman{Name: phone, Telephone: phone}}}).
// Where("partner_info.account = ?", phone).
// Where("partner_info.company_id = ?", constant.DEFAULT_GUEST_COMPANY).
// Update()
// if err != nil {
// return err
// }
//}
// 合伙人存在、用户存在、是高管(高管合伙人)
// 合伙人不存在、用户存在、是高管(高管)|| partnerInfo == nil && user != nil && senior != nil
// 合伙人存在、用户存在、非高管(合伙人)
// 游客公司合伙人存在
//if partnerInfo != nil && user != nil && senior != nil || partnerInfo != nil && user != nil && senior == nil || guestInfo != nil {
// return nil
//}
if guestInfo != nil {
return nil
}
// 用户在正常公司存在且无效或者存在非高管或者不存在、合伙人在正常公司存在且无效或者不存在、合伙人在游客公司不存在、注册合伙人到游客公司
if !isGuestPartner && (isUser && !isUserAvailable || isUser && !isUserSenior || !isUser) && (isPartner && !isPartnerAvailable || !isPartner) {
id := time.Now().Unix()
errPartner = svr.transactionContext.PgDd.Insert(&models.PartnerInfo{
Id: id,
CompanyId: int64(constant.DEFAULT_GUEST_COMPANY),
PartnerName: phone,
Account: phone,
Password: "7c4a8d09ca3762af61e59520943dc26494f8941b",
Status: 1,
PartnerCategory: 1,
RegionInfo: &domain.RegionInfo{
RegionName: "客户区域",
RegionId: 0,
},
CooperateTime: time.Now(),
CreateAt: time.Now(),
UpdateAt: time.Now(),
PartnerCategoryInfos: []*models.PartnerCategoryInfo{&models.PartnerCategoryInfo{Id: 1, Code: phone}},
Salesman: []*domain.Salesman{&domain.Salesman{Name: phone, Telephone: phone}},
})
}
// 合伙人不存在、用户存在、非高管(普通用户)-> 注册用户
// 合伙人不存在、用户不存在(游客)-> 注册用户
//if errPartner != nil && errUser == nil && errSenior == nil || errPartner != nil && errUser != nil {
// id := time.Now().Unix()
// errPartner = svr.transactionContext.PgDd.Insert(&models.PartnerInfo{
// Id: id,
// CompanyId: int64(constant.DEFAULT_GUEST_COMPANY),
// PartnerName: phone,
// Account: phone,
// Password: "7c4a8d09ca3762af61e59520943dc26494f8941b",
// Status: 1,
// PartnerCategory: 1,
// RegionInfo: &domain.RegionInfo{
// RegionName: "客户区域",
// RegionId: 0,
// },
// CooperateTime: time.Now(),
// CreateAt: time.Now(),
// UpdateAt: time.Now(),
// PartnerCategoryInfos: []*models.PartnerCategoryInfo{&models.PartnerCategoryInfo{Id: 1, Code: phone}},
// Salesman: []*domain.Salesman{&domain.Salesman{Name: phone, Telephone: phone}},
// })
//}
return errPartner
}
// 注册游客到指定的公司
func (svr *PgLoginService) RegistryGuest(phone string) error {
var (
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
)
partnerInfo, errPartner := PartnerInfoService.FindOne(map[string]interface{}{"account": phone})
user, errUser := UsersRepository.FindOne(map[string]interface{}{"phone": phone})
user, errUser := UsersRepository.FindOne(map[string]interface{}{"phone": phone, "deleteAtIsNull": true})
if partnerInfo != nil || user != nil {
return nil
}
if errUser != nil && errPartner != nil {
id := time.Now().Unix()
errPartner = svr.transactionContext.PgDd.Insert(&models.PartnerInfo{
... ...
... ... @@ -50,4 +50,6 @@ type Users struct {
AccessPartners []*domain.PartnerInfo
// 1普通用户 2主管理员
AdminType int8
// 是否高管
IsSenior int8
}
... ...
... ... @@ -57,6 +57,7 @@ func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interfa
query.SetWhere("partner_info.account = ?", "account")
query.SetWhere("partner_info.status = ?", "status")
query.SetWhere("partner_info.company_id = ?", "companyId")
query.SetWhere("partner_info.company_id <> ?", "isNot")
//if inParterIds,ok :=queryOptions["inParterIds"];ok{
// query.Relation("PartnerInfo", func(q *orm.Query) (*orm.Query, error) {
// return q.Where("id in (?)",pg.In(inParterIds.([]int64))),nil
... ... @@ -80,6 +81,7 @@ func (repository *PartnerInfoRepository) Find(queryOptions map[string]interface{
SetWhere("partner_info.account = ?", "account").
SetWhere(`partner_info.status = ?`, "status").
SetWhere(`partner_info.partner_category = ?`, "partnerCategory").
SetWhere("partner_info.company_id <> ?", "isNot").
SetLimit().
SetOrder("partner_info.create_at", "sortByCreateTime").
SetOrder("partner_info.update_at", "sortByUpdateTime")
... ...
... ... @@ -55,6 +55,8 @@ func (repository *UsersRepository) FindOne(queryOptions map[string]interface{})
query.SetWhere("phone = ?", "phone")
query.SetWhere("company_id = ?", "companyId")
query.SetWhere(`delete_at is null`, "deleteAtIsNull")
query.SetWhere("is_senior = ?", "isSenior")
if err := query.First(); err != nil {
return nil, fmt.Errorf("query row not found")
}
... ... @@ -74,6 +76,8 @@ func (repository *UsersRepository) Find(queryOptions map[string]interface{}) (in
SetWhere("company_id = ?", "companyId").
SetWhere(`status = ?`, "status").
SetWhere(`delete_at is null`, "deleteAtIsNull").
SetWhere("is_senior = ?", "isSenior").
SetWhere("company_id <> ?", "isNot").
SetOrder("create_at", "sortByCreateTime").
SetOrder("update_at", "sortByUpdateTime")
... ...
... ... @@ -81,6 +81,7 @@ func (serviceGateway *HttplibUCenterApiServiceGateway) ChangePassword(phone, new
}
return serviceGateway.handlerError(response)
}
func (serviceGateway *HttplibUCenterApiServiceGateway) ChangePhone(newPhone, oldPhone string) (int, error) {
url := strings.Join([]string{serviceGateway.baseURL, "user", "change-phone"}, "/")
request := serviceGateway.createRequest(url, "post")
... ...
... ... @@ -39,6 +39,7 @@ func NewBeegoLogger(conf LoggerConfig) *logs.BeeLogger {
log.SetLevel(ilv)
log.EnableFuncCallDepth(true)
log.SetLogFuncCallDepth(5)
log.SetPrefix(constant.LOG_PREFIX)
return log
}
... ...
... ... @@ -272,3 +272,32 @@ func (this *AuthController) UCenterRevoke() {
}
msg = protocol.NewReturnResponse(auth.UCenterRevoke(nil, int64(uid)))
}
/**
* @Author SteveChan
* @Description //校验密码
* @Date 01:00 2021/1/8
* @Param
* @return
**/
func (this *AuthController) CheckPassword() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := this.GetRequestHeader(this.Ctx)
data, err := auth.PasswordLogin(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewReturnResponse(data, err)
}
... ...
... ... @@ -2,9 +2,11 @@ package controllers
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/auth"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/user"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
"strings"
"time"
)
type UserController struct {
... ... @@ -51,14 +53,25 @@ func (this *UserController) CheckSmsCode() {
msg = protocol.NewReturnResponse(user.CheckSmsCode(header, request))
}
//ChangePhone
// @router /changePhone [post]
/**
* @Author SteveChan
* @Description //TODO 修改手机号
* @Date 00:29 2021/1/8
* @Param
* @return
* @router /changePhone [post]
**/
func (this *UserController) ChangePhone() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ChangePhoneRequest
header := this.GetRequestHeader(this.Ctx)
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
... ... @@ -67,20 +80,42 @@ func (this *UserController) ChangePhone() {
msg = m
return
}
if !CacheSms.IsExist(request.OldPhone) {
// 校验短信验证码
var authCheckSmsCodeRequest *protocol.AuthCheckSmsCodeRequest
if err := this.JsonUnmarshal(&authCheckSmsCodeRequest); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(authCheckSmsCodeRequest); !b {
msg = m
return
}
rsp, err := auth.AuthCheckSmsCode(header, authCheckSmsCodeRequest)
if err != nil {
msg = protocol.NewReturnResponse(rsp, err)
return
}
err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute)
if err != nil {
msg = protocol.NewReturnResponse(rsp, err)
return
}
if !CacheSms.IsExist(request.Phone) {
msg = protocol.NewMesage(1009) //验证码失效
return
}
if v := CacheSms.Get(request.OldPhone); v != nil {
if !strings.EqualFold(fmt.Sprintf("%v", v), strings.TrimSpace(request.CaptchaCertificate)) {
msg = protocol.NewMesage(1012) //验证码不一致
return
}
if v := CacheSms.Get(request.Phone); v != nil {
//if !strings.EqualFold(fmt.Sprintf("%v", v), strings.TrimSpace(request.CaptchaCertificate)) {
// msg = protocol.NewMesage(1012) //验证码不一致
// return
//}
} else {
msg = protocol.NewMesage(1009) //验证码不一致
return
}
header := this.GetRequestHeader(this.Ctx)
data, err := user.ChangePhone(header, request)
if err == nil {
msg = protocol.NewResponseMessage(0, "修改手机号成功")
... ...
... ... @@ -6,6 +6,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
"net/url"
"strconv"
"strings"
)
... ... @@ -15,41 +16,59 @@ func CheckJWTToken(ctx *context.Context) {
var (
msg *protocol.ResponseMessage
)
token := ctx.Input.Header("x-mmm-accesstoken")
if strings.HasSuffix(ctx.Request.RequestURI, "login") ||
strings.HasSuffix(ctx.Request.RequestURI, "accessToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "smsCode") ||
strings.HasSuffix(ctx.Request.RequestURI, "centerCompanys") ||
strings.HasSuffix(ctx.Request.RequestURI, "companys") ||
strings.HasSuffix(ctx.Request.RequestURI, "loginV2") ||
strings.HasSuffix(ctx.Request.RequestURI, "checkSmsCode") ||
strings.HasSuffix(ctx.Request.RequestURI, "changePhone") ||
strings.HasSuffix(ctx.Request.RequestURI, "resetPassword") ||
strings.HasSuffix(ctx.Request.RequestURI, "changePassword") {
return
// 需要被过滤的地址 一定要写键值
filterMap := map[string]string{
"/v1/auth/checkPassword": "校验密码",
}
urlStr := ""
tmpUrl, err := url.Parse(ctx.Request.RequestURI)
if err == nil {
urlStr = tmpUrl.Path
}
defer func() {
if msg != nil {
ctx.Output.JSON(msg, false, false)
if res := filterMap[urlStr]; res == "" {
/** 不在 Map 内对请求进行处理 **/
token := ctx.Input.Header("x-mmm-accesstoken")
if strings.HasSuffix(ctx.Request.RequestURI, "login") ||
strings.HasSuffix(ctx.Request.RequestURI, "accessToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "smsCode") ||
strings.HasSuffix(ctx.Request.RequestURI, "centerCompanys") ||
strings.HasSuffix(ctx.Request.RequestURI, "companys") ||
strings.HasSuffix(ctx.Request.RequestURI, "loginV2") ||
strings.HasSuffix(ctx.Request.RequestURI, "checkSmsCode") ||
strings.HasSuffix(ctx.Request.RequestURI, "changePhone") ||
strings.HasSuffix(ctx.Request.RequestURI, "resetPassword") ||
strings.HasSuffix(ctx.Request.RequestURI, "changePassword") {
return
}
}()
if u, err := utils.ParseJWTToken(token); err != nil {
msg = protocol.NewMesage(4141)
return
} else {
ctx.Input.SetData("UserId", u.UserId)
if constant.DISENABLE_MULTI_DEVICE_LOGIN {
// valid token
userPhone, _ := strconv.Atoi(u.Phone)
tokenAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)))
err := tokenAuth.Check(
userAuth.NewOptions(userAuth.WithAccessToken(token)),
)
if err != nil {
msg = protocol.NewMesage(4141)
return
defer func() {
if msg != nil {
ctx.Output.JSON(msg, false, false)
}
}()
if u, err := utils.ParseJWTToken(token); err != nil {
msg = protocol.NewMesage(4141)
return
} else {
ctx.Input.SetData("UserId", u.UserId)
if constant.DISENABLE_MULTI_DEVICE_LOGIN {
// valid token
userPhone, _ := strconv.Atoi(u.Phone)
tokenAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)))
err := tokenAuth.Check(
userAuth.NewOptions(userAuth.WithAccessToken(token)),
)
if err != nil {
msg = protocol.NewMesage(4141)
return
}
}
}
}
... ...
... ... @@ -8,6 +8,7 @@ import (
func init() {
nsV1 := beego.NewNamespace("v1") //, beego.NSBefore(middleware.CheckJWTToken)
nsV1.Router("/auth/login", &controllers.AuthController{}, "Post:Login")
nsV1.Router("/auth/checkPassword", &controllers.AuthController{}, "Post:CheckPassword") // 校验密码
nsV1.Router("/auth/smsCode", &controllers.AuthController{}, "Post:SmsCode")
nsV1.Router("/auth/accessToken", &controllers.AuthController{}, "Post:AccessToken")
nsV1.Router("/auth/refreshToken", &controllers.AuthController{}, "Post:RefreshToken")
... ...
... ... @@ -2,9 +2,21 @@ package routers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"net/http"
)
func init() {
beego.SetStaticPath("/log", constant.LOG_File)
//beego.SetStaticPath("/log", constant.LOG_File)
beego.Get("/log", func(ctx *context.Context) {
var s string
_ = ctx.Input.Bind(&s, "id")
if s != "12345" {
ctx.Output.SetStatus(http.StatusBadRequest)
return
}
http.ServeFile(ctx.ResponseWriter, ctx.Request, constant.LOG_File)
return
})
}
... ...
... ... @@ -2,10 +2,10 @@ package messageHandler
import "github.com/Shopify/sarama"
type UcenterMessageCommand struct {
type UCenterMessageCommand struct {
}
func (c *UcenterMessageCommand) ChangePhoneHandler(message interface{}) error {
func (c *UCenterMessageCommand) ChangePhoneHandler(message interface{}) error {
msg, ok := message.(*sarama.Message)
if !ok && msg == nil {
return nil
... ...
package sarama
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/message/kafkax"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/message/models"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/sarama/messageHandler"
//"suplus-message/pkg/constant"
//"suplus-message/pkg/port/sarama/messageHandler"
)
type PgMessageReceiverRepository struct {
transactionContext *transaction.TransactionContext
}
func NewPgMessageReceiverRepository(transactionContext *transaction.TransactionContext) *PgMessageReceiverRepository {
return &PgMessageReceiverRepository{
transactionContext: transactionContext,
}
}
func (repository *PgMessageReceiverRepository) ReceiveMessage(params map[string]interface{}) error {
var num int
checkSql := `select count(0) from sys_message_consume where "offset" =? and topic=?`
_, err := repository.transactionContext.PgDd.Query(&num, checkSql, params["offset"], params["topic"])
if err != nil {
return err
}
if num > 0 {
return fmt.Errorf("receive repeate message [%v]", params)
}
sql := `insert into sys_message_consume(topic,partition,"offset",key,value,msg_time,create_at,status)values(?,?,?,?,?,?,?,?)`
_, err = repository.transactionContext.PgDd.Exec(sql, params["topic"], params["partition"], params["offset"], params["key"], params["value"], params["msg_time"], params["create_at"], params["status"])
return err
}
func (repository *PgMessageReceiverRepository) ConfirmReceive(params map[string]interface{}) error {
fmt.Println(params)
_, err := repository.transactionContext.PgDd.Exec(`update sys_message_consume set status=? where "offset" =? and topic=?`, int(models.Finished), params["offset"], params["topic"])
return err
}
func Run() {
var (
ucenterMessage = &messageHandler.UcenterMessageCommand{}
uCenterMessage = &messageHandler.UCenterMessageCommand{}
)
saramaConsumer := kafkax.NewSaramaConsumer(constant.KAFKA_HOSTS, constant.SERVICE_NAME)
saramaConsumer.WithTopicHandler(constant.TOPIC_UCENT_USER_CHANGE_PHONE, ucenterMessage.ChangePhoneHandler)
saramaConsumer.WithTopicHandler(constant.TOPIC_UCENT_USER_CHANGE_PHONE, uCenterMessage.ChangePhoneHandler)
saramaConsumer.WithMessageReceiver(NewPgMessageReceiverRepository(nil)) // 持久化
err := saramaConsumer.StartConsume()
if err != nil {
... ...
... ... @@ -55,9 +55,10 @@ type ChangePhoneRequest struct {
Phone string `json:"phone" valid:"Required"`
Captcha string `json:"captcha" valid:"Required"`
OldPhone string `json:"oldPhone" valid:"Required"`
CaptchaCertificate string `json:"captchaCertificate" valid:"Required"`
OldPhone string `json:"oldPhone" valid:"Required"`
//CaptchaCertificate string `json:"captchaCertificate" valid:"Required"`
}
type ChangePhoneResponse struct {
}
... ...
此 diff 太大无法显示。