作者 yangfu

修改:登录v2版本修改

... ... @@ -5,10 +5,10 @@ go 1.14
require (
github.com/astaxie/beego v1.12.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.4.0
github.com/gin-gonic/gin v1.5.0
github.com/go-pg/pg/v10 v10.0.0-beta.2
github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/shopspring/decimal v1.2.0
github.com/tiptok/gocomm v1.0.0
github.com/tiptok/gocomm v1.0.1
)
... ...
... ... @@ -4,9 +4,12 @@ import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/domain_service"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"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"
)
... ... @@ -68,7 +71,7 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
}
rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, request.Phone, protocol.AuthCodeExpire*time.Second)
if err = InitOrUpdateUserIMInfo(partnerInfo, transactionContext); err != nil {
if _, err = InitOrUpdateUserIMInfo(partnerInfo.Id, partnerInfo.PartnerName, transactionContext); err != nil {
log.Error(err)
return
}
... ... @@ -220,3 +223,145 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs
//}
return
}
func CenterCompanys(header *protocol.RequestHeader, request *protocolx.CenterCompanysRequest) (rsp *protocolx.CenterCompanysResponse, 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()
}()
loginSvr.Init(request.Phone)
if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
switch request.GrantType {
case protocol.LoginByPassword:
if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
break
case protocol.LoginBySmsCode:
if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
return
}
break
default:
err = protocol.NewCustomMessage(1, "登录方式不支持!")
break
}
//获取统计信息
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
//没有有效人的时候
//if rsp.Partner ==nil && rsp.Manager ==nil{
// err = protocol.NewErrWithMessage(2002) //账号禁用
// return
//}
var nickName string
if len(loginSvr.Users) > 0 {
nickName = loginSvr.Users[0].Name
} else if len(loginSvr.PartnerInfo) > 0 {
nickName = loginSvr.PartnerInfo[0].PartnerName
}
//初始化im信息
if imInfo, err = InitOrUpdateUserIMInfo(int64(phoneId), nickName, transactionContext); err != nil {
log.Error(err)
return
}
rsp.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
rsp.ImToken = imInfo.ImToken
rsp.Accid, _ = strconv.Atoi(imInfo.ImId)
rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)
err = transactionContext.CommitTransaction()
return
}
func Companys(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(4139, err)
return
}
loginSvr.Init(claim.Phone)
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
err = transactionContext.CommitTransaction()
return
}
func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (rsp *protocol.LoginResponse, err error) {
var (
claim *utils.UserTokenClaims
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
userId int64
)
rsp = &protocol.LoginResponse{}
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
switch request.IdType {
case int(protocolx.AdminTypePartner):
if p, e := PartnerInfoRepository.FindOne(map[string]interface{}{"account": claim.Phone, "company_id": request.Cid, "status": 1}); e == nil {
userId = p.Id
}
break
case int(protocolx.AdminTypeManager):
if p, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "company_id": request.Cid, "status": 1}); e == nil {
userId = p.Id
}
break
default:
err = protocol.NewErrWithMessage(2, fmt.Errorf("idType :%v not in range (1,2)", request.IdType)) //用户类型有误
return
}
if userId == 0 {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
//根据simnum + cid
rsp.AuthCode, _ = utils.GenerateTokenWithAdminType(userId, claim.Phone, request.IdType, protocol.AuthCodeExpire*time.Second)
err = transactionContext.CommitTransaction()
return
}
... ...
... ... @@ -15,28 +15,29 @@ import (
)
// 更新用户 IM INFO
func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.TransactionContext) (err error) {
func InitOrUpdateUserIMInfo(userId int64, name string, ctx *transaction.TransactionContext) (imInfo *domain.ImInfo, err error) {
var (
ImInfoRepository, _ = factory.CreateImInfoRepository(ctx)
checkImRequest *protocol.CheckImRequest = &protocol.CheckImRequest{}
IsCreated = false
checkImResponse *protocol.CheckImResponse
)
imInfo, e := ImInfoRepository.FindOne(map[string]interface{}{"user_id": partnerInfo.Id})
var errFind error
imInfo, errFind = ImInfoRepository.FindOne(map[string]interface{}{"user_id": userId})
// 异常
if e != nil && e != domain.QueryNoRow {
err = e
if errFind != nil && errFind != domain.QueryNoRow {
err = errFind
return
}
// 不存在
if e == domain.QueryNoRow {
if errFind == domain.QueryNoRow {
imInfo = &domain.ImInfo{
UserId: partnerInfo.Id,
UserId: userId,
CreateTime: time.Now(),
}
}
// 已存在
if e == nil && imInfo != nil {
if errFind == nil && imInfo != nil {
IsCreated = true
}
... ... @@ -47,7 +48,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr
checkImRequest = &protocol.CheckImRequest{
UserId: imInfo.UserId,
ImId: imInfo.ImId,
Uname: partnerInfo.PartnerName,
Uname: name,
CustomerImId: fmt.Sprintf("%v", imInfo.CustomerImId),
IsCreated: IsCreated,
}
... ... @@ -55,7 +56,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr
return
}
if imInfo.CustomerImId == 0 {
imInfo.CustomerImId = getRandomCustomerAccount(partnerInfo.Id, ctx)
imInfo.CustomerImId = getRandomCustomerAccount(userId, ctx)
}
imInfo.ImToken = checkImResponse.ImToken
imInfo.UpdateTime = time.Now()
... ...
package order
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
... ... @@ -120,9 +119,9 @@ func Statistics(header *protocol.RequestHeader, request *protocol.OrderStatistic
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
partnerInfo *domain.PartnerInfo
orderBonus domain.OrderBonusResponse
//PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
//partnerInfo *domain.PartnerInfo
//orderBonus domain.OrderBonusResponse
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
... ... @@ -131,10 +130,10 @@ func Statistics(header *protocol.RequestHeader, request *protocol.OrderStatistic
transactionContext.RollbackTransaction()
}()
rsp = &protocol.OrderStatisticsResponse{Statistics: protocol.OrderStatics{}}
if partnerInfo, err := PartnerInfoRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
err = protocol.NewCustomMessage(1, fmt.Sprintf("%v %v", "用户不存在:", header.UserId))
return
}
//if partnerInfo, err := PartnerInfoRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
// err = protocol.NewCustomMessage(1, fmt.Sprintf("%v %v", "用户不存在:", header.UserId))
// return
//}
if rsp.Statistics.TodayRealQuantity, rsp.Statistics.TodayRealMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
BeginTime: utils.GetDayBegin().Unix() * 1000,
... ...
... ... @@ -25,6 +25,7 @@ type DividendOrdersQuery struct {
type OrderBonusQuery struct {
PartnerId int64 `json:"partnerId,omitempty"`
CompanyId int64 `json:"companyId,omitempty"`
InPartnerIds []int64 `json:"inPartnerIds,omitempty"`
}
// 订单分红统计-应答
... ...
package service
type LoginService interface {
}
... ...
... ... @@ -60,6 +60,9 @@ func (dao *OrderBaseDao) OrderBonusStatics(option domain.OrderBonusQuery) (rsp d
if option.CompanyId > 0 {
q.Where(`"order_base".company_id =?`, option.CompanyId)
}
if len(option.InPartnerIds) > 0 {
q.Where(`"order_base".partner_id in (?)`, option.InPartnerIds)
}
err = q.Select(&rsp.Total, &rsp.Bonus, &rsp.BonusExpense)
return
}
... ...
... ... @@ -25,6 +25,13 @@ func (dao *PartnerInfoDao) Update(queryOptions map[string]interface{}) error {
return err
}
//func(dao *PartnerInfoDao)PartnerCompanyInfo(queryOptions map[string]interface{})(values map[string]interface{},err error){
//// tx := dao.transactionContext.PgTx
//// m := new(models.PartnerInfo)
//// query := NewQuery(tx.Model(m), queryOptions)
//// query.SetWhere("status=?","status")
////}
func NewPartnerInfoDao(transactionContext *transaction.TransactionContext) (*PartnerInfoDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
package domain_service
import (
"github.com/tiptok/gocomm/xa/eda"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
"strings"
)
type PgLoginService struct {
Phone string
eda.EventCenterPublisher
PartnerInfo []*domain.PartnerInfo
Users []*domain.Users
transactionContext *transaction.TransactionContext
}
func (svr *PgLoginService) Init(phone string) (err error) {
var (
PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
)
svr.Phone = phone
_, svr.PartnerInfo, _ = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC"})
_, svr.Users, _ = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC"})
return nil
}
//合伙人登录
func (svr *PgLoginService) PartnerLogin(phone string, password string) (err error) {
if len(svr.PartnerInfo) == 0 {
//子账号
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if !strings.EqualFold(svr.PartnerInfo[0].Password, password) {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
return
}
//管理层登录
func (svr *PgLoginService) ManagerLogin(phone string, password string) (err error) {
if len(svr.Users) == 0 {
//子账号
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
return
}
//合伙人统计信息
func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
if len(svr.PartnerInfo) == 0 {
return nil, nil
}
var (
OrderDao, _ = dao.NewOrderBaseDao(svr.transactionContext)
PartnerCategoryInfoRepository, _ = repository.NewPartnerCategoryInfoRepository(svr.transactionContext)
companyList []*domain.Company
partnerCategory []*domain.PartnerCategoryInfo
)
doGetCompanyIds := func() []int64 {
var companies []int64
for i := range svr.PartnerInfo {
companies = append(companies, svr.PartnerInfo[i].CompanyId)
}
return companies
}
doGetPartnerIds := func() []int64 {
var array []int64
for i := range svr.PartnerInfo {
array = append(array, svr.PartnerInfo[i].Id)
}
return array
}
companyList = svr.GetCompanyList(doGetCompanyIds)
totalBonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds()})
if e != nil {
return nil, e
}
_, partnerCategory, _ = PartnerCategoryInfoRepository.Find(map[string]interface{}{"sortById": domain.ASC})
var companys = make([]*Company, 0)
for i := range companyList {
c := companyList[i]
var partner *domain.PartnerInfo
for j := range svr.PartnerInfo {
if svr.PartnerInfo[j].CompanyId == c.Id {
partner = svr.PartnerInfo[j]
break
}
}
if partner == nil {
continue
}
bonus, _ := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: partner.Id})
item := &Company{
CompanyBase: newCompanyBase(c),
IncomePercent: computeBonusPercent(totalBonus.Bonus, bonus.Bonus),
DividendMoney: bonus.Bonus,
JoinWays: svr.GetJoinWays(partnerCategory, partner, bonus.Bonus),
}
companys = append(companys, item)
}
response := make(map[string]interface{})
response["id"] = protocolx.AdminTypePartner
response["name"] = svr.PartnerInfo[0].PartnerName
response["companys"] = companys
return response, nil
}
func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
if len(svr.Users) == 0 {
return nil, nil
}
var (
companyList []*domain.Company
)
doGetCompanyIds := func() []int64 {
var companies []int64
for i := range svr.PartnerInfo {
companies = append(companies, svr.PartnerInfo[i].CompanyId)
}
return companies
}
companyList = svr.GetCompanyList(doGetCompanyIds)
var companys = make([]protocol.CompanyBase, 0)
for i := range companyList {
c := companyList[i]
//var user *domain.Users
//for j:=range svr.Users{
// if svr.Users[j].CompanyId==c.Id{
// user = svr.Users[j]
// break
// }
//}
item := newCompanyBase(c)
companys = append(companys, item)
}
response := make(map[string]interface{})
response["id"] = protocolx.AdminTypePartner
response["name"] = svr.PartnerInfo[0].PartnerName
response["companys"] = companys
return response, nil
}
func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*domain.Company {
var (
CompanyRepository, _ = repository.NewCompanyRepository(svr.transactionContext)
companyList []*domain.Company
)
var companies []int64 = funcGetCompanyIds()
if len(companies) == 0 {
return companyList
}
if _, v, e := CompanyRepository.Find(map[string]interface{}{"companies": companies, "status": 1, "sortByCreateTime": domain.ASC}); e != nil {
return companyList
} else {
companyList = v
}
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 {
if partnerCategory[i].Id == id {
return partnerCategory[i]
}
}
return nil
}
var (
totalBonus float64
businessBonus float64
BusinessBonusRepository, _ = repository.NewBusinessBonusRepository(svr.transactionContext)
)
for i := range partnerInfo.PartnerCategoryInfos {
c := partnerInfo.PartnerCategoryInfos[i]
switch c.Id {
case 1:
totalBonus += bonus
case 2:
if one, e := BusinessBonusRepository.FindOne(map[string]interface{}{"partner_id": partnerInfo.Id}); e == nil {
businessBonus = one.Bonus
totalBonus += businessBonus
}
}
}
var joinWays []joinWay
for i := range partnerCategory {
c := partnerCategory[i]
searchC := searchCategory(partnerInfo.PartnerCategoryInfos, c.Id)
if searchC != nil {
item := joinWay{
Type: int(c.Id),
Name: c.Name,
}
if c.Id == 1 {
item.Percent = computeBonusPercent(totalBonus, bonus) * 100
} else if c.Id == 2 {
item.Percent = computeBonusPercent(totalBonus, businessBonus) * 100
}
joinWays = append(joinWays, item)
}
}
return joinWays
}
func newCompanyBase(company *domain.Company) protocol.CompanyBase {
return protocol.CompanyBase{
Id: company.Id,
Name: company.Name,
ShortName: "TODO",
Image: protocol.NewImage(company.Logo),
Phone: company.Phone,
}
}
func computeBonusPercent(totalBonus float64, bonus float64) float64 {
if totalBonus == 0 {
return 0
}
return utils.Decimal(bonus / totalBonus)
}
type Company struct {
protocol.CompanyBase
// 收入占比
IncomePercent float64 `json:"incomePercent"`
// 分红金额
DividendMoney float64 `json:"dividendMoney"`
JoinWays []joinWay
}
type incomeInfo struct {
// 收入占比
IncomePercent float64 `json:"incomePercent"`
// 分红金额
DividendMoney float64 `json:"dividendMoney"`
}
type joinWay struct {
Type int `json:"type"`
Name string `json:"name"`
Percent float64 `json:"percent"`
}
func NewPgLoginService(ctx *transaction.TransactionContext) *PgLoginService {
return &PgLoginService{
transactionContext: ctx,
}
}
... ...
... ... @@ -49,6 +49,7 @@ func (repository *BusinessBonusRepository) FindOne(queryOptions map[string]inter
BusinessBonusModel := new(models.BusinessBonus)
query := NewQuery(tx.Model(BusinessBonusModel), queryOptions)
query.SetWhere("id = ?", "id")
query.SetWhere("partner_id = ?", "partner_id")
if err := query.First(); err != nil {
return nil, fmt.Errorf("query row not found")
}
... ...
... ... @@ -62,6 +62,11 @@ func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) (
var CompanyModels []*models.Company
Companys := make([]*domain.Company, 0)
query := NewQuery(tx.Model(&CompanyModels), queryOptions)
if companies, ok := queryOptions["companies"]; ok {
query.WhereIn("id in (?)", companies)
}
query.SetWhere("status = ?", "status")
query.SetOrder(`create_at`, "sortByCreateTime")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, Companys, err
... ...
... ... @@ -64,7 +64,8 @@ func (repository *PartnerCategoryInfoRepository) Find(queryOptions map[string]in
PartnerCategoryInfos := make([]*domain.PartnerCategoryInfo, 0)
query := NewQuery(tx.Model(&PartnerCategoryInfoModels), queryOptions).
SetOrder("create_time", "sortByCreateTime").
SetOrder("update_time", "sortByUpdateTime")
SetOrder("update_time", "sortByUpdateTime").
SetOrder("id", "sortById")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, PartnerCategoryInfos, err
... ...
... ... @@ -48,7 +48,7 @@ func (repository *UsersRepository) FindOne(queryOptions map[string]interface{})
tx := repository.transactionContext.PgTx
UsersModel := new(models.Users)
query := NewQuery(tx.Model(UsersModel), queryOptions)
query.SetWhere("id = ?", "id")
query.SetWhere("phone = ?", "phone")
if err := query.First(); err != nil {
return nil, fmt.Errorf("query row not found")
}
... ... @@ -63,8 +63,11 @@ func (repository *UsersRepository) Find(queryOptions map[string]interface{}) (in
var UsersModels []*models.Users
Userss := make([]*domain.Users, 0)
query := NewQuery(tx.Model(&UsersModels), queryOptions).
SetOrder("create_time", "sortByCreateTime").
SetOrder("update_time", "sortByUpdateTime")
SetWhere("phone = ?", "phone").
SetWhere("company_id = ?", "companyId").
SetWhere(`status = ?`, "status").
SetOrder("create_at", "sortByCreateTime").
SetOrder("update_at", "sortByUpdateTime")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, Userss, err
... ...
... ... @@ -54,3 +54,21 @@ func GenerateToken(uid int64, phone string, expire time.Duration) (string, error
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
func GenerateTokenWithAdminType(uid int64, phone string, adminType int, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
Phone: phone,
AdminType: adminType,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
... ...
... ... @@ -4,6 +4,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/auth"
"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"
"time"
)
... ... @@ -163,3 +164,83 @@ func (this *AuthController) AuthCheckSmsCode() {
err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute)
msg = protocol.NewReturnResponse(rsp, err)
}
// CenterCompanys
// 获取统一用户中心公司(登录凭证)
func (this *AuthController) CenterCompanys() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocolx.CenterCompanysRequest
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
if len(request.Password) == 0 {
msg = protocol.NewResponseMessage(1, "密码不能为空!")
return
}
header := this.GetRequestHeader(this.Ctx)
data, err := auth.CenterCompanys(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewReturnResponse(data, err)
}
// Companys
// 测试
func (this *AuthController) Companys() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocolx.CompanysRequest
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.Companys(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewReturnResponse(data, err)
}
// LoginV2
// @router /loginV2 [post]
func (this *AuthController) LoginV2() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.LoginRequestV2
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
if request.ClientId != clientId {
msg = protocol.NewResponseMessage(101, "clientId无效")
return
}
header := this.GetRequestHeader(this.Ctx)
data, err := auth.LoginV2(header, request)
if err != nil {
log.Error(err)
}
msg = protocol.NewReturnResponse(data, err)
}
... ...
... ... @@ -15,6 +15,8 @@ func init() {
nsV1.Router("/auth/revoke", &controllers.AuthController{}, "Post:Revoke")
nsV1.Router("/auth/updateDevice", &controllers.AuthController{}, "Post:UpdateDevice")
nsV1.Router("/auth/checkSmsCode", &controllers.AuthController{}, "Post:AuthCheckSmsCode")
nsV1.Router("/auth/centerCompanys", &controllers.AuthController{}, "post:CenterCompanys")
nsV1.Router("/auth/companys", &controllers.AuthController{}, "post:Companys")
nsV1.Router("/user/userInfo", &controllers.UserController{}, "Post:UserInfo")
nsV1.Router("/user/checkSmsCode", &controllers.UserController{}, "Post:CheckSmsCode")
... ... @@ -31,3 +33,9 @@ func init() {
nsV1.Router("/dividend/orders", &controllers.DividendController{}, "Post:DividendOrders")
beego.AddNamespace(nsV1)
}
func InitV2() {
nsV2 := beego.NewNamespace("v2", beego.NSBefore(middleware.CheckJWTToken))
nsV2.Router("/auth/login", &controllers.AuthController{}, "Post:LoginV2")
beego.AddNamespace(nsV2)
}
... ...
... ... @@ -25,6 +25,13 @@ type LoginResponse struct {
AuthCode string `json:"authCode"`
}
type LoginRequestV2 struct {
Cid int `json:"cid"`
IdType int `json:"idType"`
Credentials string `json:"credentials"` // 登录类型 1:密码 2:验证码
ClientId string `json:"clientId"`
}
//JWT用户信息
type JWTUserInfo struct {
UserId string `json:"id"` //用户id
... ...
package auth
import "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
type CenterCompanysRequest protocol.LoginRequest
... ...
package auth
type CenterCompanysResponse struct {
Accid int `json:"accid"` //网易云信ID
ImToken string `json:"imToken"` //网易云信Token
CsAccountID string `json:"csAccountID"` //系统分配客服ID
Credentials string `json:"credentials"` //登录凭证
Partner interface{} `json:"partner"` //合伙人对象
Manager interface{} `json:"manager"` //高管对象
}
... ...
package auth
type CompanysRequest struct {
// 客户端密钥
ClientId string `json:"clientId"`
// 登录凭证
Credentials string `json:"credentials"`
}
... ...
package auth
type CompanysResponse struct {
Partner interface{} `json:"partner"` //合伙人对象
Manager interface{} `json:"manager"` //高管对象
}
... ...
package auth
type AdminType int
var (
AdminTypePartner AdminType = 1
AdminTypeManager AdminType = 2
)
... ...
package protocol
type CompanyBase struct {
Id int64 `json:"id"`
Name string `json:"name"`
ShortName string `json:"shortName"`
Image interface{} `json:"image"`
Phone string `json:"phone"`
}
type Image struct {
Path string `json:"path"`
}
func NewImage(path string) Image {
return Image{
Path: path,
}
}
... ...