作者 yangfu

1.基础修改 2.权限认证

... ... @@ -27,6 +27,7 @@ require (
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
)
replace gitlab.fjmaimaimai.com/mmm-go/partner => ../partner
... ...
... ... @@ -3,7 +3,7 @@ package main
import (
"github.com/astaxie/beego"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr"
)
func main() {
... ...
... ... @@ -8,7 +8,8 @@ import (
type GetPartnerInfoQuery struct {
// 合伙人ID
Id int `json:"id" valid:"Required"`
Id int `json:"id,omitempty"`
Account string `json:"account,omitempty"`
}
func (q *GetPartnerInfoQuery) ValidateQuery() error {
... ...
... ... @@ -7,6 +7,8 @@ import (
)
type ListPartnerInfoQuery struct {
//账号
Account string `json:"account,omitempty"`
//状态
Status int `json:"status,omitempty"`
// 合伙人类别
... ...
... ... @@ -8,6 +8,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/command"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"time"
)
... ... @@ -16,7 +17,7 @@ type PartnerInfoService struct {
}
// 创建客户价值
func (PartnerInfoService *PartnerInfoService) CreatePartnerInfo(command *command.CreatePartnerInfoCommand) (data interface{}, err error) {
func (PartnerInfoService *PartnerInfoService) CreatePartnerInfo(command *command.CreatePartnerInfoCommand) (data *domain.PartnerInfo, err error) {
var (
count int64
transactionContext, _ = factory.CreateTransactionContext(nil)
... ... @@ -56,7 +57,7 @@ func (PartnerInfoService *PartnerInfoService) CreatePartnerInfo(command *command
}
// 返回客户价值
func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetPartnerInfoQuery) (data interface{}, err error) {
func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetPartnerInfoQuery) (data *domain.PartnerInfo, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
)
... ... @@ -75,7 +76,7 @@ func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetP
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
data, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": command.Id})
data, err = PartnerInfoRepository.FindOne(utils.ObjectJsonToMap(command))
if err != nil {
return nil, err
}
... ... @@ -87,12 +88,12 @@ func (PartnerInfoService *PartnerInfoService) GetPartnerInfo(command *query.GetP
}
// 更新客户价值
func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInfoCommand *command.UpdatePartnerInfoCommand) (data interface{}, err error) {
func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(command *command.UpdatePartnerInfoCommand) (data *domain.PartnerInfo, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfo *domain.PartnerInfo
)
if err = updatePartnerInfoCommand.ValidateCommand(); err != nil {
if err = command.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
... ... @@ -107,12 +108,12 @@ func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInf
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": updatePartnerInfoCommand.Id})
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": command.Id})
if err != nil {
return nil, err
}
if PartnerInfo == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updatePartnerInfoCommand.Id)))
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(command.Id)))
}
//if count, PartnerInfos, err := PartnerInfoRepository.Find(map[string]interface{}{
// "PartnerInfoName": updatePartnerInfoCommand.PartnerInfoName,
... ... @@ -124,7 +125,7 @@ func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInf
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "标签不可重复名称")
// }
//}
if err := PartnerInfo.Update(tool_funs.SimpleStructToMap(updatePartnerInfoCommand)); err != nil {
if err := PartnerInfo.Update(tool_funs.SimpleStructToMap(command)); err != nil {
return nil, err
}
... ... @@ -136,12 +137,12 @@ func (PartnerInfoService *PartnerInfoService) UpdatePartnerInfo(updatePartnerInf
}
// 移除客户价值
func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(removePartnerInfoCommand *command.RemovePartnerInfoCommand) (data interface{}, err error) {
func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(command *command.RemovePartnerInfoCommand) (data *domain.PartnerInfo, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfo *domain.PartnerInfo
)
if err = removePartnerInfoCommand.ValidateCommand(); err != nil {
if err = command.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err = transactionContext.StartTransaction(); err != nil {
... ... @@ -156,12 +157,12 @@ func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(removePartnerInf
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": removePartnerInfoCommand.Id})
PartnerInfo, err = PartnerInfoRepository.FindOne(map[string]interface{}{"Id": command.Id})
if err != nil {
return nil, err
}
if PartnerInfo == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removePartnerInfoCommand.Id)))
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(command.Id)))
}
if data, err = PartnerInfoRepository.Remove(PartnerInfo); err != nil {
return nil, err
... ... @@ -171,13 +172,13 @@ func (PartnerInfoService *PartnerInfoService) RemovePartnerInfo(removePartnerInf
}
// 返回客户价值列表
func (PartnerInfoService *PartnerInfoService) ListPartnerInfo(listPartnerInfoQuery *query.ListPartnerInfoQuery) (data interface{}, err error) {
func (PartnerInfoService *PartnerInfoService) ListPartnerInfo(command *query.ListPartnerInfoQuery) (data interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfos []*domain.PartnerInfo
count int64
)
if err = listPartnerInfoQuery.ValidateQuery(); err != nil {
if err = command.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
... ... @@ -192,7 +193,7 @@ func (PartnerInfoService *PartnerInfoService) ListPartnerInfo(listPartnerInfoQue
if PartnerInfoRepository, err = factory.CreatePartnerInfoRepository(map[string]interface{}{"transactionContext": transactionContext}); err != nil {
return nil, err
}
if count, PartnerInfos, err = PartnerInfoRepository.Find(tool_funs.SimpleStructToMap(listPartnerInfoQuery)); err != nil {
if count, PartnerInfos, err = PartnerInfoRepository.Find(tool_funs.SimpleStructToMap(command)); err != nil {
return nil, err
}
if err = transactionContext.CommitTransaction(); err != nil {
... ...
package domain
//Order 订单信息
type Order struct {
//id
OrderId int64 `json:"orderId"`
//账号
OrderName string `json:"orderName"`
//密码
OrderCount int `json:"orderCount"`
//管理员名称
OrderAmount string `json:"admin_name"`
//是否是默认系统账号
IsDefault bool `json:"is_default"`
//账号是否可用
IsUsable bool `json:"is_userable"`
//创建时间
CreateAt string `json:"create_at"`
//用户权限
Permission []string `json:"permission"`
}
... ...
... ... @@ -23,6 +23,10 @@ type PartnerInfo struct {
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `json:"partnerCategory"`
//所属区域信息
RegionInfo *RegionInfo `json:"regionId"`
//合作时间
CooperateTime time.Time `json:"cooperateTime"`
//创建时间
CreateAt time.Time `json:"createAt"`
//更新时间
... ...
package domain
type RegionInfo struct {
RegionId int `json:"regionId"`
RegionName string `json:"regionName"`
}
... ...
... ... @@ -7,7 +7,7 @@ import (
)
type PartnerInfo struct {
tableName struct{} `pg:"partner_infos,alias:partner_info"`
tableName struct{} `pg:"partner_info"`
// 合伙人ID
Id int64 `pg:",pk"`
// 合伙人姓名
... ... @@ -21,6 +21,10 @@ type PartnerInfo struct {
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `pg:",notnull,default:1"`
//所属区域信息
RegionInfo *domain.RegionInfo
//合作时间
CooperateTime time.Time
//创建时间
CreateAt time.Time
//更新时间
... ...
... ... @@ -20,10 +20,10 @@ func (repository *PartnerInfoRepository) Save(dm *domain.PartnerInfo) (*domain.P
return nil, err
}
if dm.Identify() == nil {
if dm.Id, err = NewSnowflakeId(); err != nil {
return dm, err
}
m.Id = dm.Id
//if dm.Id, err = NewSnowflakeId(); err != nil {
// return dm, err
//}
//m.Id = dm.Id
if err = tx.Insert(m); err != nil {
return nil, err
}
... ... @@ -51,6 +51,7 @@ func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interfa
PartnerInfoModel := new(models.PartnerInfo)
query := NewQuery(tx.Model(PartnerInfoModel), queryOptions)
query.SetWhere("partner_info.id = ?", "id")
query.SetWhere("partner_info.account = ?", "account")
if err := query.First(); err != nil {
return nil, query.HandleError(err, "没有此合伙人")
}
... ...
package utils
import (
"github.com/dgrijalva/jwt-go"
"time"
)
type UserTokenClaims struct {
UserId int64 `json:"userId"`
jwt.StandardClaims
}
var jwtSecret = []byte("123456")
//解析 UserTokenClaims
func ParseJWTToken(token string) (*UserTokenClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &UserTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
return nil, err
}
if tokenClaims != nil {
if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
return claim, nil
}
}
return nil, err
}
//生成token
//@uid 用户变化
//@password 密码
//@expire 过期时长
func GenerateToken(uid int64, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
... ...
package utils
import (
"bytes"
"encoding/json"
)
func ObjectJsonToMap(obj interface{}) (v map[string]interface{}) {
var data bytes.Buffer
enc := json.NewEncoder(&data)
enc.Encode(obj)
decoder := json.NewDecoder(&data)
decoder.UseNumber()
decoder.Decode(&v)
return
}
... ...
package beego
package appsvr
import (
"github.com/astaxie/beego"
"github.com/linmadan/egglib-go/web/beego/filters"
. "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/routers"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/routers/manage"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/routers"
)
func init() {
... ...
package controllers
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/services/auth"
)
type AuthController struct {
BaseController
}
// Login
// @router /login [post]
func (this *AuthController) Login() {
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)
msg = protocol.NewReturnResponse(auth.Login(header, request))
}
//SmsCode
// @router /smsCode [post]
func (this *AuthController) SmsCode() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.SmsCodeRequest
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.SmsCode(request))
}
//AccessToken
// @router /accessToken [post]
func (this *AuthController) AccessToken() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.AccessTokenRequest
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.AccessToken(request))
}
//RefreshToken
// @router /refreshToken [post]
func (this *AuthController) RefreshToken() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.RefreshTokenRequest
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.RefreshToken(request))
}
//Revoke
//@router /revoke [post]
func (this *AuthController) Revoke() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
//var request *protocol.RevokeRequest
//if err := json.Unmarshal(this.ByteBody, &request); err != nil {
// log.Error(err)
// msg = protocol.BadRequestParam(1)
// return
//}
//if b, m := this.Valid(request); !b {
// msg = m
// return
//}
//header := controllers.GetRequestHeader(this.Ctx)
//msg = protocol.NewReturnResponse(auth.Revoke(header, request))
}
//UpdateDevice
//@router /updateDevice [post]
func (this *AuthController) UpdateDevice() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
//var request *protocol.UpdateDeviceRequest
//if err := json.Unmarshal(this.ByteBody, &request); err != nil {
// log.Error(err)
// msg = protocol.BadRequestParam(1)
// return
//}
//if b, m := this.Valid(request); !b {
// msg = m
// return
//}
//header := controllers.GetRequestHeader(this.Ctx)
//msg = protocol.NewReturnResponse(auth.UpdateDevice(header, request))
}
... ...
... ... @@ -3,8 +3,13 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/validation"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego/utils"
comm "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"strconv"
)
type BaseController struct {
... ... @@ -30,6 +35,11 @@ func (controller BaseController) HandlerResponse(data interface{}, err error) {
if _, ok := err.(*application.ServiceError); !ok {
err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if x, ok := err.(protocol.CustomErrParse); ok {
m := x.ParseToMessage()
response = ResponseCustomData(controller.Ctx, data, m)
return
}
response = utils.ResponseError(controller.Ctx, err)
}
... ... @@ -38,3 +48,63 @@ func (controller BaseController) GetLimitInfo() (offset int, limit int) {
limit, _ = controller.GetInt("limit")
return
}
func ResponseCustomData(ctx *context.Context, data interface{}, msg *protocol.ResponseMessage) utils.JsonResponse {
jsonResponse := utils.JsonResponse{}
jsonResponse["code"] = 0
jsonResponse["msg"] = "ok"
jsonResponse["data"] = data
ctx.Input.SetData("outputData", jsonResponse)
return jsonResponse
}
//Valid valid struct
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) Resp(msg *protocol.ResponseMessage) {
this.Data["json"] = msg
this.Ctx.Input.SetData("outputData", msg)
this.ServeJSON()
}
func (this *BaseController) RespH5(msg *protocol.ResponseMessage) {
if msg.Errno != 0 {
msg.Errno = -1
}
this.Data["json"] = msg
this.Ctx.Input.SetData("outputData", msg)
this.ServeJSON()
}
//获取请求头信息
func (this *BaseController) GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.AccessToken = ctx.Input.Header("x-mmm-accesstoken")
h.AppProject = ctx.Input.Header("x-mmm-appproject")
h.DeviceType, _ = strconv.Atoi(ctx.Input.Header("x-mmm-devicetype"))
h.Sign = ctx.Input.Header("x-mmm-sign")
h.Uuid = ctx.Input.Header("x-mmm-uuid")
h.TimeStamp = ctx.Input.Header("x-mmm-timestamp")
h.Version = ctx.Input.Header("x-mmm-version")
h.UserId, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-id"), 10, 64)
if len(h.AccessToken) > 0 {
if claim, err := comm.ParseJWTToken(h.AccessToken); err == nil {
h.UserId = claim.UserId
}
}
return h
}
... ...
package controllers
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/services/user"
)
type UserController struct {
BaseController
}
//UserInfo
//@router /userInfo [post]
func (this *UserController) UserInfo() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.UserInfoRequest
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)
msg = protocol.NewReturnResponse(user.UserInfo(header, request))
}
... ...
package middleware
import (
"github.com/astaxie/beego/context"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"strings"
)
//检查access_token
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") {
return
}
defer func() {
if msg != nil {
ctx.Output.JSON(msg, false, false)
}
}()
if _, err := utils.ParseJWTToken(token); err != nil {
msg = protocol.NewMesage(4141)
return
}
return
}
... ...
package protocol
const (
LoginByPassword = iota + 1
LoginBySmsCode
)
const AuthCodeExpire = 60 * 15
const TokenExpire = 60 * 15
const RefreshTokenExipre = 3600 * 24 * 30 * 3 //刷新token 三个月过期
/*Login */
type LoginRequest struct {
Phone string `json:"phone" valid:"Required;"`
Password string `json:"password"`
SmsCode string `json:"smsCode"`
Type int `json:"type"` // 登录类型 1:密码 2:验证码
}
type LoginResponse struct {
AuthCode string `json:"authCode"`
}
//JWT用户信息
type JWTUserInfo struct {
UserId string `json:"id"` //用户id
PassWord string `json:"passWord"` //密码
}
/*SmsCode*/
type SmsCodeRequest struct {
Phone string `json:"phone" valid:"Required;Mobile"`
Content string `json:"-"`
SendType string `json:"send_type"` //sms_login_code sms_change_mobile
}
type SmsCodeResponse struct {
Code string `json:"-"`
}
/*UpdateDevice*/
type UpdateDeviceRequest struct {
ClientId string `json:"clientId" valid:"Required"`
DeviceToken string `json:"deviceToken"`
}
type UpdateDeviceResponse struct {
}
/*AccessToken */
type AccessTokenRequest struct {
//ClientId string `json:"clientId" valid:"Required"`
//ClientSecret string `json:"clientSecret" valid:"Required"`
AuthCode string `json:"authCode" valid:"Required"`
}
type AccessTokenResponse struct {
RefreshToken string `json:"refreshToken"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
}
/*RefreshToken */
type RefreshTokenRequest struct {
ClientId string `json:"clientId" valid:"Required"`
ClientSecret string `json:"clientSecret" valid:"Required"`
RefreshToken string `json:"refreshToken" valid:"Required"`
//Uid int64 `json:"-"`
//LoginType string `json:"-"`
}
type RefreshTokenResponse struct {
RefreshToken string `json:"refreshToken"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
}
/*Revoke */
type RevokeRequest struct {
}
type RevokeResponse struct {
}
... ...
package protocol
import (
"encoding/json"
"fmt"
)
var (
ERR_DB_NOT_FOUND = fmt.Errorf("db:not found")
)
//CustomErrParse 解析自定义错误结构体
type CustomErrParse interface {
ParseToMessage() *ResponseMessage
}
//ErrorMap 统一消息错误编码
type ErrorMap map[int]string
//Search 搜索错误描述
func (m ErrorMap) Search(code int) ErrorCode {
if v, ok := m[code]; ok {
return ErrorCode{
Errno: code,
Errmsg: v,
}
}
return ErrorCode{Errno: code, Errmsg: "错误码未定义"}
}
//ErrorCode 统一错误结构
type ErrorCode struct {
Errno int `json:"code"`
Errmsg string `json:"msg"`
}
//ResponseMessage 统一返回消息结构体
type ResponseMessage struct {
ErrorCode
Data interface{} `json:"data"`
}
func NewMesage(code int) *ResponseMessage {
return &ResponseMessage{
ErrorCode: SearchErr(code),
Data: nil,
}
}
//ErrWithMessage 自定义错误结构
type ErrWithMessage struct {
Err error `json:"-"`
ErrorCode
}
var (
_ CustomErrParse = new(ErrWithMessage)
_ error = new(ErrWithMessage)
)
//NewErrWithMessage 构建错误返回
//code:用于匹配统一消息错误编码 eRR:填充嵌套错误
func NewErrWithMessage(code int, eRR ...error) *ErrWithMessage {
r := &ErrWithMessage{
ErrorCode: SearchErr(code),
}
if len(eRR) > 0 {
r.Err = eRR[0]
}
return r
}
//Error 实现接口error 中的方法
//将ErrorCode转为json数据,建议用于日志记录
func (e ErrWithMessage) Error() string {
bt, _ := json.Marshal(e.ErrorCode)
return string(bt)
}
//Unwrap 接口实现
func (e ErrWithMessage) Unwrap() error {
return e.Err
}
//ParseToMessage 实现CustomErrParse的接口
func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
return &ResponseMessage{
ErrorCode: e.ErrorCode,
Data: nil,
}
}
func SearchErr(code int) ErrorCode {
return errmessge.Search(code)
}
func NewReturnResponse(data interface{}, eRR error) *ResponseMessage {
var msg *ResponseMessage
if eRR == nil {
msg = NewMesage(0)
msg.Data = data
return msg
}
// fmt.Println("日志:" + eRR.Error())
if x, ok := eRR.(CustomErrParse); ok {
msg = x.ParseToMessage()
msg.Data = data
return msg
}
return NewMesage(1)
}
func BadRequestParam(code int) *ResponseMessage {
return NewMesage(code)
}
func NewSuccessWithMessage(msg string) *ErrWithMessage {
return &ErrWithMessage{
Err: nil,
ErrorCode: ErrorCode{0, msg},
}
}
func NewCustomMessage(code int, msg string) *ErrWithMessage {
return &ErrWithMessage{
Err: nil,
ErrorCode: ErrorCode{code, msg},
}
}
... ...
package protocol
var errmessge ErrorMap = map[int]string{
0: "成功",
1: "系统异常",
2: "参数错误",
113: "签名验证失败",
502: "用户不存在",
4139: "authCode无效或过期",
4140: "refreshToken过期,需要重新登录授权",
4141: "accessToken过期或无效,需要进行重新获取令牌",
4142: "Uuid已存在,请求失败",
}
... ...
package protocol
type RequestHeader struct {
TimeStamp string
Version string
Uuid string
Sign string
DeviceType int
AppProject string
AccessToken string
Uid int64 //用户基本信息Id
CompanyId int64
UserId int64 //UserId 唯一标识,唯一关联所有用户信息(=user_company.id)
requestId string //请求编号 md5
reqIndex int64 //请求链序号
}
... ...
package protocol
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
)
/*用户信息 UserInfo */
type UserInfoRequest struct {
}
type UserInfoResponse struct {
User User `json:"user"`
}
type User struct {
Id int64 `json:"id"`
// 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
PartnerCategory int `json:"partnerCategory"`
PartnerName string `json:"partnerName"`
//所属区域信息
RegionInfo *domain.RegionInfo `json:"regionInfo"`
CooperateCompany Company `json:"cooperateCompany"`
CooperateTime int64 `json:"cooperateTime"`
Salesman *domain.Salesman `json:"salesman"`
}
type Company struct {
Id int `json:"id"`
Name string `json:"name"`
}
... ...
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/controllers"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/middleware"
)
func init() {
nsV1 := beego.NewNamespace("v1", beego.NSBefore(middleware.CheckJWTToken))//beego.NSNamespace("auth", beego.NSInclude(&controllers.AuthController{})),
nsV1.Router("auth/login", &controllers.AuthController{}, "Post:Login")
nsV1.Router("auth/smsCode", &controllers.AuthController{}, "Post:SmsCode")
nsV1.Router("auth/accessToken", &controllers.AuthController{}, "Post:AccessToken")
nsV1.Router("auth/refreshToken", &controllers.AuthController{}, "Post:RefreshToken")
nsV1.Router("auth/revoke", &controllers.AuthController{}, "Post:Revoke")
nsV1.Router("auth/updateDevice", &controllers.AuthController{}, "Post:UpdateDevice")
nsV1.Router("user/userInfo", &controllers.UserController{}, "Post:UserInfo")
beego.AddNamespace(nsV1)
}
... ...
package auth
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"strings"
"time"
)
func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
partnerInfo *domain.PartnerInfo
result bool = false
)
rsp = &protocol.LoginResponse{}
if partnerInfo, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Account: request.Phone}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
switch request.Type {
case protocol.LoginByPassword:
if len(partnerInfo.Password) == 0 {
err = protocol.NewCustomMessage(1, "密码不能为空!")
return
}
if result = strings.EqualFold(partnerInfo.Password, request.Password); result {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
break
case protocol.LoginBySmsCode:
break
}
rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, protocol.AuthCodeExpire*time.Second)
return
}
func SmsCode(request *protocol.SmsCodeRequest) (rsp *protocol.LoginResponse, err error) {
return
}
func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessTokenResponse, err error) {
var (
claim *utils.UserTokenClaims
)
rsp = &protocol.AccessTokenResponse{}
if claim, err = utils.ParseJWTToken(request.AuthCode); err != nil {
err = protocol.NewErrWithMessage(4139, err)
return
}
if claim.UserId <= 0 {
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.ExpiresIn = protocol.TokenExpire
return
}
func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
var (
claim *utils.UserTokenClaims
)
rsp = &protocol.RefreshTokenResponse{}
if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil {
err = protocol.NewErrWithMessage(4139, err)
return
}
if claim.UserId <= 0 {
err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken))
return
}
rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second)
rsp.ExpiresIn = protocol.TokenExpire
return
return
}
... ...
package user
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
)
//用户信息
func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest) (rsp *protocol.UserInfoResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
partnerInfo *domain.PartnerInfo
)
rsp = &protocol.UserInfoResponse{}
if partnerInfo, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Id: int(header.UserId)}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
rsp.User = protocol.User{
Id: partnerInfo.Id,
PartnerCategory: partnerInfo.PartnerCategory,
PartnerName: partnerInfo.PartnerName,
RegionInfo: partnerInfo.RegionInfo,
CooperateCompany: protocol.Company{
Id: 1,
Name: "福州素天下有限公司",
},
CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
}
if len(partnerInfo.Salesman) > 0 {
rsp.User.Salesman = partnerInfo.Salesman[0]
}
return
}
... ...
package middleware
import (
"github.com/astaxie/beego/context"
)
//PermissionCheck 根据权限编码检验请求是否可以执行
//permissionCode:权限编码
//excludeURL:跳过url
func AdminPermissionCheck(permissionCode string, excludeURL ...string) func(ctx *context.Context) {
return func(ctx *context.Context) {
//根据code检查权限数据,并排除excludeUrl指定的url
//获取user 数据
}
}
package manage
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/middleware"
)
func init() {
adminRouter := beego.NewNamespace("/admin_user",
//验证权限
beego.NSBefore(middleware.AdminPermissionCheck(domain.PERMINSSION_ADMIN_USER)),
//其余的路由
//...
)
beego.AddNamespace(adminRouter)
}
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/beego/controllers"
)
func init() {
beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Post:CreatePartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Put:UpdatePartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Get:GetPartnerInfo")
beego.Router("/partnerInfos/:id", &controllers.PartnerInfoController{}, "Delete:RemovePartnerInfo")
beego.Router("/partnerInfos/", &controllers.PartnerInfoController{}, "Get:ListPartnerInfo")
}