controller.go 2.7 KB
package controllers

import (
	"github.com/beego/beego/v2/server/web/context"
	"github.com/linmadan/egglib-go/web/beego"
	"github.com/linmadan/egglib-go/web/beego/utils"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/api/authlib"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/cache"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
	"strconv"
)

func ResponseGrid(c beego.BaseController, total int64, data interface{}, err error) {
	var response utils.JsonResponse
	if err != nil {
		response = utils.ResponseError(c.Ctx, err)
	} else {
		response = ResponseGridData(c.Ctx, total, data)
	}
	c.Data["json"] = response
	c.ServeJSON()
}

func ResponseGridData(ctx *context.Context, total int64, data interface{}) utils.JsonResponse {
	jsonResponse := utils.JsonResponse{}
	jsonResponse["code"] = 0
	jsonResponse["msg"] = "ok"
	jsonResponse["data"] = map[string]interface{}{"grid": map[string]interface{}{
		"total": total,
		"list":  data,
	}}
	ctx.Input.SetData("outputData", jsonResponse)
	return jsonResponse
}

func Must(err error) {
	if err != nil {
		log.Logger.Error(err.Error())
	}
}

func ParseContext(c beego.BaseController) *domain.Context {
	var companyId int = 1
	var userId int = 1
	var userName string = "管理员"
	if token := c.Ctx.Input.GetData("UserToken"); token != nil {
		userToken, ok := token.(*domain.UserToken)
		if ok {
			// cache user info
			key := cache.KeyCompanyUser(companyId, userId)
			if userToken.UserId != 0 {
				if cacheItem, ok := cache.DefaultCache.Get(key); ok {
					v := cacheItem.(*authlib.DataUserMe)
					userName = v.User.NickName
				} else {
					requestToken, _ := userToken.GenerateToken()
					authLib := authlib.NewApiAuthLib(constant.AUTH_SERVER_HOST).WithToken(requestToken)
					userInfo, err := authLib.MeInfo(authlib.RequestUserMeQuery{})
					if err != nil || userInfo == nil || userInfo.User == nil {
						goto END
					}
					userName = userInfo.User.NickName
					cache.DefaultCache.SetDefault(key, userInfo)
				}
			}
			// assign user
			companyId = int(userToken.CompanyId)
			userId = int(userToken.UserId)
		}
	}
END:
	ctx := &domain.Context{
		CompanyId:    companyId,
		OperatorId:   userId,
		OperatorName: userName,
		TenantId:     1,
	}
	return ctx
}

func header(c beego.BaseController, key string) int {
	if len(c.Ctx.Input.Header(key)) == 0 {
		return 0
	}
	res, err := strconv.Atoi(c.Ctx.Input.Header(key))
	if err != nil {
		log.Logger.Error(err.Error())
		return 0
	}
	return res
}