作者 yangfu

Merge branch 'test-gencode' into dev

... ... @@ -5,6 +5,7 @@ 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/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
... ...
... ... @@ -7,6 +7,7 @@ import (
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
//"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr"
)
... ... @@ -16,5 +17,6 @@ func main() {
}()
log.Info("app start!")
log.Info(constant.POSTGRESQL_DB_NAME)
//ginsvr.Run()
beego.Run()
}
... ...
... ... @@ -66,7 +66,7 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
err = protocol.NewCustomMessage(1, "登录方式不支持!")
break
}
rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, protocol.AuthCodeExpire*time.Second)
rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, request.Phone, protocol.AuthCodeExpire*time.Second)
if err = InitOrUpdateUserIMInfo(partnerInfo, transactionContext); err != nil {
log.Error(err)
... ... @@ -105,8 +105,8 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke
err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode))
return
}
rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second)
rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, claim.Phone, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, claim.Phone, protocol.RefreshTokenExipre*time.Second)
rsp.ExpiresIn = protocol.TokenExpire
//auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),
... ... @@ -121,8 +121,22 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke
func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
var (
claim *utils.UserTokenClaims
claim *utils.UserTokenClaims
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
PartnerSubAccountRepository, _ = factory.CreatePartnerSubAccountRepository(transactionContext)
partnerInfo *domain.PartnerInfo
partnerSubAccount *domain.PartnerSubAccount
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
rsp = &protocol.RefreshTokenResponse{}
if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil {
err = protocol.NewErrWithMessage(4140, err)
... ... @@ -132,14 +146,27 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken))
return
}
//验证用户有效
var e error
if partnerSubAccount, e = PartnerSubAccountRepository.FindOne(map[string]interface{}{"account": claim.Phone}); e == nil {
partnerInfo, e = PartnerInfoService.FindOne(map[string]interface{}{"id": partnerSubAccount.PartnerId})
} else {
partnerInfo, e = PartnerInfoService.FindOne(map[string]interface{}{"account": claim.Phone})
}
if e != nil || partnerInfo == nil || !partnerInfo.IsEnable() || partnerInfo.Id != claim.UserId {
err = protocol.NewErrWithMessage(4140) //账号禁用
return
}
//oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId))
//if err = oldAuth.Check(userAuth.NewOptions(userAuth.WithRefreshToken(request.RefreshToken))); err != nil {
// log.Error(err)
// err = protocol.NewErrWithMessage(4140, err)
// return
//}
rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second)
rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, claim.Phone, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, claim.Phone, protocol.RefreshTokenExipre*time.Second)
rsp.ExpiresIn = protocol.TokenExpire
//newAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),
... ... @@ -149,6 +176,7 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
// log.Error(err)
// return
//}
err = transactionContext.CommitTransaction()
return
}
... ...
... ... @@ -14,8 +14,6 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
OrderBaseResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
//beginTime = time.Unix(request.StartTime/1000, 0)
//endTime = time.Unix(request.EndTime/1000, 0)
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
... ...
... ... @@ -2,11 +2,11 @@ package constant
import "os"
var POSTGRESQL_DB_NAME = "partner_dev" //partner
var POSTGRESQL_USER = "postgres" //
var POSTGRESQL_PASSWORD = "postgres_15432" //pgsql@123
var POSTGRESQL_HOST = "101.37.68.23" //127.0.0.1
var POSTGRESQL_PORT = "15432" //5432
var POSTGRESQL_DB_NAME = "partner_dev" //partner
var POSTGRESQL_USER = "postgres" //
var POSTGRESQL_PASSWORD = "eagle1010" //pgsql@123
var POSTGRESQL_HOST = "114.55.200.59" //127.0.0.1
var POSTGRESQL_PORT = "31543" //5432
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
... ...
... ... @@ -6,7 +6,8 @@ import (
)
type UserTokenClaims struct {
UserId int64 `json:"userId"`
UserId int64 `json:"userId"`
Phone string `json:"phone"`
jwt.StandardClaims
}
... ... @@ -33,11 +34,12 @@ func ParseJWTToken(token string) (*UserTokenClaims, error) {
//@uid 用户变化
//@password 密码
//@expire 过期时长
func GenerateToken(uid int64, expire time.Duration) (string, error) {
func GenerateToken(uid int64, phone string, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
Phone: phone,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
... ...
package controllers
import (
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"github.com/tiptok/gocomm/pkg/mygin"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
"strconv"
)
type BaseController struct {
mygin.BaseController
}
func (this *BaseController) Resp(c *gin.Context, httpCode int, rsp *protocol.ResponseMessage) {
c.Set("outputData", rsp)
c.JSON(httpCode, rsp)
//c.Abort()
}
func (controller *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
/*校验*/
var err error
valid := validation.Validation{}
result, err = valid.Valid(obj)
if err != nil {
}
if !result {
msg = protocol.BadRequestParam(2)
return
}
return
}
//获取请求头信息
func (this *BaseController) GetRequestHeader(c *gin.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.AccessToken = c.Query("x-mmm-accesstoken")
h.AppProject = c.Query("x-mmm-appproject")
h.DeviceType, _ = strconv.Atoi(c.Query("x-mmm-devicetype"))
h.Sign = c.Query("x-mmm-sign")
h.Uuid = c.Query("x-mmm-uuid")
h.TimeStamp = c.Query("x-mmm-timestamp")
h.Version = c.Query("x-mmm-version")
h.UserId, _ = strconv.ParseInt(c.Query("x-mmm-id"), 10, 64)
if len(h.AccessToken) > 0 {
if claim, err := utils.ParseJWTToken(h.AccessToken); err == nil {
h.UserId = claim.UserId
}
}
return h
}
... ...
package controllers
import (
"github.com/gin-gonic/gin"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/order"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
"net/http"
"time"
)
type OrderController struct {
BaseController
}
//OrderStatistics 订单统计
// @router /statistics [post]
func (this *OrderController) Statistics(c *gin.Context) {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(c, http.StatusOK, msg)
}()
var request *protocol.OrderStatisticsRequest
if err := c.ShouldBind(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := this.GetRequestHeader(c)
msg = protocol.NewReturnResponse(order.Statistics(header, request))
}
//OrderDetail 订单详情
// @router /orderDetail [post]
func (this *OrderController) OrderDetail(c *gin.Context) {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(c, http.StatusOK, msg)
}()
var request *protocol.OrderDetailRequest
if err := c.ShouldBind(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := this.GetRequestHeader(c)
msg = protocol.NewReturnResponse(order.Detail(header, request))
}
//OrderList
func (this *OrderController) OrderList(c *gin.Context) {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(c, http.StatusOK, msg)
}()
var request *protocol.OrderListRequest
if err := c.ShouldBind(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
request.OrderType = domain.OrderReal
header := this.GetRequestHeader(c)
msg = protocol.NewReturnResponse(order.List(header, request))
}
//OrderList
func (this *OrderController) Intentions(c *gin.Context) {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(c, http.StatusOK, msg)
}()
var request *protocol.OrderListRequest
if err := c.ShouldBind(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
request.EndTime = time.Now().Unix() * 1000
request.OrderType = domain.OrderIntention
header := this.GetRequestHeader(c)
msg = protocol.NewReturnResponse(order.List(header, request))
}
... ...
package ginsvr
import (
"github.com/gin-gonic/gin/ginS"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/routers"
)
func Run() {
ginS.Run(":8080")
}
... ...
package middleware
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"io/ioutil"
"net/http"
"time"
)
func CreateRequstLogFilter() gin.HandlerFunc {
return func(ctx *gin.Context) {
requestId := fmt.Sprintf("%v.%v", ctx.Request.Method, ctx.Request.RequestURI)
ctx.Set("requestId", requestId)
var body string = "{}"
if _, ok := ctx.Get("requestBody"); ok {
data, _ := ctx.Get("requestBody")
body = string(data.([]byte))
}
start := time.Now()
ctx.Next()
end := time.Now()
latency := end.Sub(start)
v, _ := ctx.Get("outputData")
rspBody, _ := json.Marshal(v)
if len(rspBody) > 500 {
rspBody = rspBody[:500]
}
log.Debug(fmt.Sprintf("====>Recv User:%v | %v | %s | %v | \nAuth=%v \nReqBody:%s \nRspBody:%v", ctx.Query("UserId"), ctx.ClientIP(), requestId, latency, ctx.Query("x-mmm-accesstoken"), body, string(rspBody)))
}
}
func CreateResponseLogFilter() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
requestId, _ := ctx.Get("requestId")
v, _ := ctx.Get("outputData")
body, _ := json.Marshal(v)
if len(body) > 1000 {
body = body[:1000]
}
log.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
}
}
func CreateRequestBodyFilter() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
if ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut {
body, _ := ioutil.ReadAll(ctx.Request.Body)
if len(body) == 0 {
body = []byte("{}")
}
ctx.Set("requestBody", body)
ctx.Request.Body.Close()
}
}
}
... ...
package routers
import (
"github.com/gin-gonic/gin/ginS"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/controllers"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/middleware"
)
func init() {
//ginS.Use(middleware.CreateRequestBodyFilter())
ginS.Use(middleware.CreateRequstLogFilter())
order := &controllers.OrderController{}
ginS.POST("/order/statistics", order.Statistics)
ginS.POST("/order/details", order.OrderDetail)
ginS.POST("/order/list", order.OrderList)
ginS.POST("/order/intentions", order.Intentions)
}
... ...
... ... @@ -5,9 +5,9 @@ const (
LoginBySmsCode = "signInCaptcha"
)
const AuthCodeExpire = 60 * 15
const AuthCodeExpire = 60 * 15 //15分钟过期
const TokenExpire = 60 * 60 * 2
const TokenExpire = 60 * 60 * 2 //两个小时过期
const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期
//const TokenExpire = 30
... ...