作者 yangfu

1.短信 权限认证修改

... ... @@ -52,6 +52,16 @@ spec:
- mountPath: /opt/logs
name: accesslogs
env:
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.ip
- name: REDIS_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.port
- name: POSTGRESQL_DB_NAME
value: "partner_test"
- name: POSTGRESQL_USER
... ...
... ... @@ -5,6 +5,7 @@ go 1.14
require (
github.com/ajg/form v1.5.1 // indirect
github.com/astaxie/beego v1.12.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/gavv/httpexpect v2.0.0+incompatible
... ... @@ -20,14 +21,15 @@ require (
github.com/onsi/gomega v1.7.1
github.com/sergi/go-diff v1.1.0 // indirect
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/tiptok/gocomm v0.0.0-20190919092013-c230743f8095
github.com/valyala/fasthttp v1.14.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
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
... ...
... ... @@ -23,3 +23,21 @@ func CreateAdminUserRepository(options map[string]interface{}) (domain.AdminUser
}
return repository.NewAdminUserRepository(transactionContext)
}
//CreateOrderRepository 订单
func CreateOrderRepository(options map[string]interface{}) (domain.OrderRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewOrderRepository(transactionContext)
}
//CreateOrderRepository 订单
func CreateOrderPaymentRepository(options map[string]interface{}) (domain.OrderPaymentRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewOrderPaymentRepository(transactionContext)
}
... ...
... ... @@ -7,6 +7,8 @@ const SERVICE_NAME = "partner"
var LOG_LEVEL = "debug"
var LOG_File = "app.log"
var MMM_SMS_SERVICE_HOST = "https://sms.fjmaimaimai.com:9897"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
... ...
... ... @@ -2,11 +2,11 @@ package constant
import "os"
var POSTGRESQL_DB_NAME = "partner"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "pgsql@123"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
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 DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
... ...
package constant
import "os"
var REDIS_HOST = "127.0.0.1"
var REDIS_PORT = "6379"
var REDIS_AUTH = "123456"
func init() {
if os.Getenv("REDIS_HOST") != "" {
REDIS_HOST = os.Getenv("REDIS_HOST")
}
if os.Getenv("REDIS_PORT") != "" {
REDIS_PORT = os.Getenv("REDIS_PORT")
}
if _, ok := os.LookupEnv("REDIS_AUTH"); ok {
REDIS_AUTH = os.Getenv("REDIS_AUTH")
}
}
... ...
package domain
//买家
type Buyer struct {
//买家姓名
BuyerName string `json:"buyerName"`
//联系方式
ContactInfo string `json:"contactInfo"`
//收获地址
ShippingAddress string `json:"shippingAddress"`
}
... ...
package domain
import "time"
const (
OrderStatusReserve = iota + 1 //预定中
OrderStatusDeliverSome //部分发货
OrderStatusDeliverAll //全部发货
)
type OrderRepository interface {
Save(dm *Order) (*Order, error)
Remove(dm *Order) (*Order, error)
FindOne(queryOptions map[string]interface{}) (*Order, error)
Find(queryOptions map[string]interface{}) (int64, []*Order, error)
}
//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"`
Id int64 `json:"Id,omitempty"`
//订单类型
OrderType int `json:"orderType,omitempty"`
//订单编号
OrderCode string `json:"orderCode,omitempty"`
//订单名称
OrderName string `json:"orderName,omitempty"`
//订单状态
OrderStatus int `json:"orderStatus,omitempty"`
//订单数量
OrderCount int `json:"orderCount,omitempty"`
//实际订单数量
OrderActualCount int `json:"orderActualCount,omitempty"`
//订单金额
OrderAmount float64 `json:"admin_name,omitempty"`
//订单实际金额
OrderActualAmount float64 `json:"orderActualAmount,omitempty"`
//订单已支付金额(货款)
OrderPaymentAmount float64 `json:"orderPaymentAmount,omitempty"`
//订单区域信息
OrderRegionInfo *RegionInfo `json:"orderRegionInfo,omitempty"`
Buyer *Buyer `json:"buyer,omitempty"`
//合伙人编号
PartnerId int64 `json:"partnerId,omitempty"`
//合伙人分红百分比
PartnerBonusPercent float64 `json:"partnerBonusPercent,omitempty"`
//业务员分红百分比
SalesmanBonusPercent float64 `json:"salesmanBonusPercent,omitempty"`
//创建时间
CreateAt string `json:"create_at"`
//用户权限
Permission []string `json:"permission"`
CreateAt time.Time `json:"createAt,omitempty"`
//更新时间
UpdateAt time.Time `json:"updateAt,omitempty"`
//上一次查看时间 已读情况
LastViewTime time.Time `json:"lastViewTime,omitempty"`
}
func (m *Order) Identify() interface{} {
if m.Id == 0 {
return nil
}
return m.Id
}
func (m *Order) Update(data map[string]interface{}) error {
if orderType, ok := data["orderType"]; ok && orderType != 0 {
m.OrderType = orderType.(int)
}
if orderCode, ok := data["orderCode"]; ok && orderCode != "" {
m.OrderCode = orderCode.(string)
}
if orderName, ok := data["orderName"]; ok && orderName != "" {
m.OrderName = orderName.(string)
}
if orderStatus, ok := data["orderStatus"]; ok && orderStatus != 0 {
m.OrderStatus = orderStatus.(int)
}
if lastViewTime, ok := data["lastViewTime"]; ok && lastViewTime != 0 {
m.LastViewTime = lastViewTime.(time.Time)
}
m.UpdateAt = time.Now()
return nil
}
... ...
package domain
import "time"
const (
BonusWaitPay = iota + 1 //等待支付分红
BonusPaid //已经支付分红
)
type OrderPaymentRepository interface {
Save(dm *OrderPayment) (*OrderPayment, error)
Remove(dm *OrderPayment) (*OrderPayment, error)
FindOne(queryOptions map[string]interface{}) (*OrderPayment, error)
Find(queryOptions map[string]interface{}) (int64, []*OrderPayment, error)
}
type OrderPayment struct {
//编号
Id int64 `json:"id"`
//订单编号
OrderId int64 `json:"orderId"`
//合伙人编号
PartnerId int64 `json:"partnerId"`
//支付货款
PaymentAmount float64 `json:"paymentAmount"`
//分红金额
BonusAmount float64 `json:"bonusAmount"`
//分红状态 1.等待支付分红 2.已支付分红
BonusStatus int `json:"bonusStatus"`
//创建时间
CreateAt time.Time `json:"createAt"`
//更新时间
UpdateAt time.Time `json:"updateAt"`
}
func (m *OrderPayment) Identify() interface{} {
if m.Id == 0 {
return nil
}
return m.Id
}
func (m *OrderPayment) Update(data map[string]interface{}) error {
if m.BonusStatus != BonusWaitPay {
return nil
}
if paymentAmount, ok := data["paymentAmount"]; ok && paymentAmount != 0 {
m.PaymentAmount = paymentAmount.(float64)
}
if bonusAmount, ok := data["bonusAmount"]; ok && bonusAmount != 0 {
m.BonusAmount = bonusAmount.(float64)
}
if bonusStatus, ok := data["bonusStatus"]; ok && bonusStatus != 0 {
m.BonusStatus = bonusStatus.(int)
}
m.UpdateAt = time.Now()
return nil
}
... ...
package domain
//业务员
type Salesman struct {
//Id int64 `json:"id"`
Name string `json:"name"`
... ...
... ... @@ -25,6 +25,8 @@ func init() {
for _, model := range []interface{}{
//(*models.Employee)(nil),
(*models.PartnerInfo)(nil),
(*models.Order)(nil),
(*models.OrderPayment)(nil),
} {
err := DB.CreateTable(model, &orm.CreateTableOptions{
Temp: false,
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"time"
)
type Order struct {
tableName struct{} `pg:"order"`
//id
Id int64 `pg:",pk"`
//订单类型 1:实际订单 2:意向订单
OrderType int `pg:",notnull,default:1"`
//订单编号
OrderCode string `pg:",notnull`
//订单名称
OrderName string
//订单状态
OrderStatus int `pg:",notnull,default:1"`
//订单数量
OrderCount int
//实际订单数量
OrderActualCount int
//订单金额
OrderAmount float64
//订单实际金额
OrderActualAmount float64
//订单已支付金额(货款)
OrderPaymentAmount float64
//订单区域信息
OrderRegionInfo *domain.RegionInfo
Buyer *domain.Buyer
//合伙人编号
PartnerId int64
//合伙人分红百分比
PartnerBonusPercent float64
//业务员分红百分比
SalesmanBonusPercent float64
//创建时间
CreateAt time.Time
//更新时间
UpdateAt time.Time
//上一次查看时间 已读情况
LastViewTime time.Time
}
... ...
package models
import "time"
type OrderPayment struct {
tableName struct{} `pg:"order_payment"`
//编号
Id int64 `pg:",pk"`
//订单编号
OrderId int64
//合伙人编号
PartnerId int64
//支付货款
PaymentAmount float64 `pg:",notnull,default:0"`
//分红金额
BonusAmount float64
//分红状态 1.等待支付分红 2.已支付分红
BonusStatus int `pg:",notnull,default:1"`
//创建时间
CreateAt time.Time
//更新时间
UpdateAt time.Time
}
... ...
package redis
import (
"fmt"
"github.com/tiptok/gocomm/pkg/redis"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
)
func init() {
redisSource := fmt.Sprintf("%v:%v", constant.REDIS_HOST, constant.REDIS_PORT)
err := redis.InitWithDb(100, redisSource, constant.REDIS_AUTH, "0")
if err != nil {
panic(err)
}
}
... ...
package repository
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
)
type OrderPaymentRepository struct {
transactionContext *transaction.TransactionContext
}
func (repository *OrderPaymentRepository) Save(dm *domain.OrderPayment) (*domain.OrderPayment, error) {
var (
err error
m = &models.OrderPayment{}
tx = repository.transactionContext.PgTx
)
if err = GobModelTransform(m, dm); err != nil {
return nil, err
}
if dm.Identify() == nil {
if dm.Id, err = NewSnowflakeId(); err != nil {
return dm, err
}
m.Id = dm.Id
if err = tx.Insert(m); err != nil {
return nil, err
}
return dm, nil
}
if err = tx.Update(m); err != nil {
return nil, err
}
return dm, nil
}
func (repository *OrderPaymentRepository) Remove(OrderPayment *domain.OrderPayment) (*domain.OrderPayment, error) {
var (
tx = repository.transactionContext.PgTx
OrderPaymentModel = &models.OrderPayment{Id: OrderPayment.Identify().(int64)}
)
if _, err := tx.Model(OrderPaymentModel).Where("id = ?", OrderPayment.Id).Delete(); err != nil {
return OrderPayment, err
}
return OrderPayment, nil
}
func (repository *OrderPaymentRepository) FindOne(queryOptions map[string]interface{}) (*domain.OrderPayment, error) {
tx := repository.transactionContext.PgTx
OrderPaymentModel := new(models.OrderPayment)
query := NewQuery(tx.Model(OrderPaymentModel), queryOptions)
query.SetWhere("order_payment.id = ?", "id")
query.SetWhere("order_payment.order_id = ?", "orderId")
if err := query.First(); err != nil {
return nil, query.HandleError(err, "没有此订单")
}
if OrderPaymentModel.Id == 0 {
return nil, nil
}
return repository.transformPgModelToDomainModel(OrderPaymentModel)
}
func (repository *OrderPaymentRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.OrderPayment, error) {
tx := repository.transactionContext.PgTx
var OrderPaymentModels []*models.OrderPayment
OrderPayments := make([]*domain.OrderPayment, 0)
query := NewQuery(tx.Model(&OrderPaymentModels), queryOptions)
query.
SetWhere("order_payment.partner_id = ?", "partnerId").
SetWhere("order_payment.order_id = ?", "orderId").
SetWhere(`order_payment.create_at >= ?`, "beginTime").
SetWhere(`order_payment.create_at < ?`, "endTime").
SetLimit().
SetOrder("order_payment.create_at", "sortByCreateTime").
SetOrder("order_payment.update_at", "sortByUpdateTime")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, OrderPayments, err
}
for _, OrderPaymentModel := range OrderPaymentModels {
if OrderPayment, err := repository.transformPgModelToDomainModel(OrderPaymentModel); err != nil {
return 0, OrderPayments, err
} else {
OrderPayments = append(OrderPayments, OrderPayment)
}
}
return int64(query.AffectRow), OrderPayments, nil
}
func (repository *OrderPaymentRepository) transformPgModelToDomainModel(OrderPaymentModel *models.OrderPayment) (*domain.OrderPayment, error) {
m := &domain.OrderPayment{}
err := GobModelTransform(m, OrderPaymentModel)
return m, err
}
func NewOrderPaymentRepository(transactionContext *transaction.TransactionContext) (*OrderPaymentRepository, error) {
if transactionContext == nil {
return nil, ERR_EMPTY_TC
}
return &OrderPaymentRepository{transactionContext: transactionContext}, nil
}
... ...
package repository
import (
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
)
type OrderRepository struct {
transactionContext *transaction.TransactionContext
}
func (repository *OrderRepository) Save(dm *domain.Order) (*domain.Order, error) {
var (
err error
m = &models.Order{}
tx = repository.transactionContext.PgTx
)
if err = GobModelTransform(m, dm); err != nil {
return nil, err
}
if dm.Identify() == nil {
//if dm.Id, err = NewSnowflakeId(); err != nil {
// return dm, err
//}
//m.Id = dm.Id
if err = tx.Insert(m); err != nil {
return nil, err
}
return dm, nil
}
if err = tx.Update(m); err != nil {
return nil, err
}
return dm, nil
}
func (repository *OrderRepository) Remove(Order *domain.Order) (*domain.Order, error) {
var (
tx = repository.transactionContext.PgTx
OrderModel = &models.Order{Id: Order.Identify().(int64)}
)
if _, err := tx.Model(OrderModel).Where("id = ?", Order.Id).Delete(); err != nil {
return Order, err
}
return Order, nil
}
func (repository *OrderRepository) FindOne(queryOptions map[string]interface{}) (*domain.Order, error) {
tx := repository.transactionContext.PgTx
OrderModel := new(models.Order)
query := NewQuery(tx.Model(OrderModel), queryOptions)
query.SetWhere("order.id = ?", "id")
query.SetWhere("order.order_code = ?", "orderCode")
if err := query.First(); err != nil {
return nil, query.HandleError(err, "没有此订单")
}
if OrderModel.Id == 0 {
return nil, nil
}
return repository.transformPgModelToDomainModel(OrderModel)
}
func (repository *OrderRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Order, error) {
tx := repository.transactionContext.PgTx
var OrderModels []*models.Order
Orders := make([]*domain.Order, 0)
query := NewQuery(tx.Model(&OrderModels), queryOptions)
query.
SetWhere("order.partner_id= ?", "partnerId").
SetWhere(`order.create_at >= ?`, "beginTime").
SetWhere(`order.create_at < ?`, "endTime").
SetLimit().
SetOrder("order.create_at", "sortByCreateTime").
SetOrder("order.update_at", "sortByUpdateTime")
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, Orders, err
}
for _, OrderModel := range OrderModels {
if Order, err := repository.transformPgModelToDomainModel(OrderModel); err != nil {
return 0, Orders, err
} else {
Orders = append(Orders, Order)
}
}
return int64(query.AffectRow), Orders, nil
}
func (repository *OrderRepository) transformPgModelToDomainModel(OrderModel *models.Order) (*domain.Order, error) {
m := &domain.Order{}
err := GobModelTransform(m, OrderModel)
return m, err
}
func NewOrderRepository(transactionContext *transaction.TransactionContext) (*OrderRepository, error) {
if transactionContext == nil {
return nil, ERR_EMPTY_TC
}
return &OrderRepository{transactionContext: transactionContext}, nil
}
... ...
package utils
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
// 此函数将指定的结构体成员值更新到结构体中
func SetStructValueByType(s interface{}, columnType string, columnValue interface{}) error {
columnValueV := reflect.ValueOf(columnValue)
var setValue reflect.Value
var flag = false
v := reflect.ValueOf(s)
for i, n := 0, v.Elem().NumField(); i < n; i++ {
if v.Elem().Type().Field(i).Name == columnType {
setValue = v.Elem().Field(i)
flag = true
break
}
}
if !flag {
return errors.New("struct is not type:")
} else if !setValue.CanSet() {
return errors.New("setValue.CanSet is false")
} else if setValue.Kind() != columnValueV.Kind() {
return errors.New("struct field and value of type is error")
}
switch columnValueV.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
setValue.SetInt(int64(columnValueV.Int()))
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
setValue.SetUint(uint64(columnValueV.Uint()))
case reflect.Float32, reflect.Float64:
setValue.SetFloat(float64(columnValueV.Float()))
case reflect.String:
setValue.SetString(columnValueV.String())
case reflect.Struct:
setValue.Set(columnValueV)
default:
return errors.New("columnValue err for:" + columnType)
}
return nil
}
func JoinInts(ids []int, spilt string) string {
var idStrings []string = make([]string, len(ids))
for i := 0; i < len(ids); i++ {
idStrings[i] = fmt.Sprintf("%v", ids[i])
}
return strings.Join(idStrings, spilt)
}
func JoinInt8s(ids []int8, spilt string) string {
var idStrings []string = make([]string, len(ids))
for i := 0; i < len(ids); i++ {
idStrings[i] = fmt.Sprintf("%v", ids[i])
}
return strings.Join(idStrings, spilt)
}
func JoinInt64s(ids []int64, spilt string) string {
var idStrings []string = make([]string, len(ids))
for i := 0; i < len(ids); i++ {
idStrings[i] = fmt.Sprintf("%v", ids[i])
}
return strings.Join(idStrings, spilt)
}
//判断是否为空
func IsNil(i interface{}) bool {
vi := reflect.ValueOf(i)
if vi.Kind() == reflect.Ptr {
return vi.IsNil()
}
return false
}
func JsonUnmarshal(jsonData string, v interface{}) {
if len(jsonData) == 0 {
return
}
if e := json.Unmarshal([]byte(jsonData), v); e != nil {
}
}
func JsonAssertString(v interface{}) string {
if data, e := json.Marshal(v); e == nil {
return string(data)
}
return ""
}
//深度拷贝
func DeepCopy(dst, src interface{}) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return gob.NewDecoder(&buf).Decode(dst)
}
//深度拷贝
func JsonDeepCopy(dst, src interface{}) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return json.NewDecoder(&buf).Decode(dst)
}
//检查版本信息
func ValidVersion(current, compare string) bool {
curVersions := strings.Split(current, ".")
comVersions := strings.Split(compare, ".")
for i := range curVersions {
//v1,v2:=strings.TrimSpace(curVersions[i]),""
v1, _ := strconv.ParseInt(strings.TrimSpace(curVersions[i]), 10, 64)
var v2 int64
if i < len(comVersions) {
v2, _ = strconv.ParseInt(strings.TrimSpace(comVersions[i]), 10, 64)
}
if v1 == 0 && v2 == 0 {
continue
}
if v1 >= v2 {
return true
}
if v1 < v2 {
return false
}
}
return false
}
// 统计某函数执行时间
// 使用方式
// defer utils.Profiling("test")()
//func Profiling(msg string) func() {
// start := time.Now()
// return func() {
// log.Info(fmt.Sprintf("%s[%s]:%s", msg, "use", time.Since(start)))
// }
//}
//合并字典
func MergeMap(to map[string]interface{}, from map[string]interface{}) {
for k, v := range from {
to[k] = v
}
}
func GetPageInfo(pageIndex, pageSize int) (offset, size int) {
if pageSize == 0 {
pageSize = 20
}
if pageIndex == 0 {
pageIndex = 1
}
offset = (pageIndex - 1) * pageSize
size = pageSize
return
}
... ...
package constant
package log
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"path/filepath"
... ... @@ -40,3 +41,16 @@ func NewBeegoLogger(conf LoggerConfig) *logs.BeeLogger {
log.SetLogFuncCallDepth(3)
return log
}
func Debug(args ...interface{}) {
beego.Debug(args...)
}
func Info(args ...interface{}) {
beego.Info(args...)
}
func Warn(args ...interface{}) {
beego.Warn(args...)
}
func Error(args ...interface{}) {
beego.Error(args...)
}
... ...
... ... @@ -4,11 +4,12 @@ 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/appsvr/middleware"
_ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/routers"
)
func init() {
beego.InsertFilter("/*", beego.BeforeExec, filters.CreateRequestBodyFilter())
beego.InsertFilter("/*", beego.BeforeExec, CreateRequstLogFilter(Logger))
beego.InsertFilter("/*", beego.AfterExec, CreateResponseLogFilter(Logger), false)
beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger))
beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false)
}
... ...
... ... @@ -28,3 +28,83 @@ func (this *UserController) UserInfo() {
header := this.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(user.UserInfo(header, request))
}
//CheckSmsCode
// @router /checkSmsCode [post]
func (this *UserController) CheckSmsCode() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.CheckSmsCodeRequest
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.CheckSmsCode(header, request))
}
//ChangePhone
// @router /changePhone [post]
func (this *UserController) ChangePhone() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ChangePhoneRequest
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.ChangePhone(header, request))
}
//ResetPassword
// @router /resetPassword [post]
func (this *UserController) ResetPassword() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ResetPasswordRequest
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.ResetPassword(header, request))
}
//ChangePassword
// @router /changePassword [post]
func (this *UserController) ChangePassword() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ChangePasswordRequest
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.ChangePassword(header, request))
}
... ...
package constant
package middleware
import (
"encoding/json"
... ...
package protocol
var errmessge ErrorMap = map[int]string{
0: "成功",
1: "系统异常",
2: "参数错误",
113: "签名验证失败",
502: "用户不存在",
0: "成功",
1: "系统异常",
2: "参数错误",
113: "签名验证失败",
502: "用户不存在",
1009: "验证码已失效",
1011: "获取验证码次数超出限制,请联系管理员",
1012: "请输入正确的验证码",
2021: "登录失败,手机号或密码错误",
2025: "短信验证码验证失败",
2026: "新密码与确认密码不一致",
2027: "密码必须至少有6个字符",
2028: "请输入正确的旧密码",
2029: "当前手机号已存在,请重新输入",
2030: "新密码与旧密码一致,请重新输入",
4139: "authCode无效或过期",
4140: "refreshToken过期,需要重新登录授权",
4141: "accessToken过期或无效,需要进行重新获取令牌",
... ...
... ... @@ -27,3 +27,35 @@ type Company struct {
Id int `json:"id"`
Name string `json:"name"`
}
/*修改手机号-验证旧手机验证码 */
type CheckSmsCodeRequest struct {
Captcha string `json:"captcha" valid:"Required"`
}
type CheckSmsCodeResponse struct {
}
/*修改手机号*/
type ChangePhoneRequest struct {
Phone string `json:"phone" valid:"Mobile"`
Captcha string `json:"captcha" valid:"Required"`
}
type ChangePhoneResponse struct {
}
/*ResetPassword */
type ResetPasswordRequest struct {
NewPwd string `json:"newPwd" valid:"Required"`
ConfirmPwd string `json:"confirmPwd" valid:"Required"`
}
type ResetPasswordResponse struct {
}
/*ChangePassword */
type ChangePasswordRequest struct {
NewPwd string `json:"newPwd" valid:"Required"`
ConfirmPwd string `json:"confirmPwd" valid:"Required"`
OldPwd string `json:"oldPwd" valid:"Required"`
}
type ChangePasswordResponse struct {
}
... ...
... ... @@ -7,7 +7,7 @@ import (
)
func init() {
nsV1 := beego.NewNamespace("v1", beego.NSBefore(middleware.CheckJWTToken))//beego.NSNamespace("auth", beego.NSInclude(&controllers.AuthController{})),
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")
... ... @@ -17,5 +17,9 @@ func init() {
nsV1.Router("auth/updateDevice", &controllers.AuthController{}, "Post:UpdateDevice")
nsV1.Router("user/userInfo", &controllers.UserController{}, "Post:UserInfo")
nsV1.Router("user/checkSmsCode", &controllers.UserController{}, "Post:CheckSmsCode")
nsV1.Router("user/ChangePhone", &controllers.UserController{}, "Post:ChangePhone")
nsV1.Router("user/resetPassword", &controllers.UserController{}, "Post:ResetPassword")
nsV1.Router("user/changePassword", &controllers.UserController{}, "Post:ChangePassword")
beego.AddNamespace(nsV1)
}
... ...
... ... @@ -5,6 +5,7 @@ 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/infrastructure/service_gateway"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"strings"
... ... @@ -41,6 +42,15 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
}
func SmsCode(request *protocol.SmsCodeRequest) (rsp *protocol.LoginResponse, err error) {
var data map[string]interface{}
sms := service_gateway.NewHttplibMmmSmsApiServiceGateway()
data, err = sms.SendSms(request.Phone)
if err != nil {
if msg, ok := data["msg"]; ok {
err = protocol.NewCustomMessage(1, msg.(string))
}
return
}
return
}
... ... @@ -82,3 +92,17 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
return
return
}
//验证短信验证码 T
func CheckSmsCode(phone, code string) (result bool, err error) {
sms := service_gateway.NewHttplibMmmSmsApiServiceGateway()
_, err = sms.CheckSmsCode(phone, code)
var data map[string]interface{}
if err != nil {
if msg, ok := data["msg"]; ok {
err = protocol.NewCustomMessage(1, msg.(string))
}
return
}
return
}
... ...
package user
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/application/partnerInfo/service"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/protocol"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/services/auth"
"strings"
)
//用户信息
... ... @@ -34,3 +38,102 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
}
return
}
//验证smscode
func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCodeRequest) (rsp *protocol.CheckSmsCodeResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
partnerInfo *domain.PartnerInfo
result bool
)
if partnerInfo, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Id: int(header.UserId)}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if result, err = auth.CheckSmsCode(strings.TrimSpace(partnerInfo.Account), request.Captcha); err != nil {
log.Error(err)
return
}
if !result {
err = protocol.NewErrWithMessage(1012)
}
return
}
//修改手机号
func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRequest) (rsp *protocol.ChangePhoneResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
)
if _, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Id: int(header.UserId)}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if _, err = auth.CheckSmsCode(request.Phone, request.Captcha); err != nil {
log.Error(err)
return
}
if _, err = PartnerInfoService.UpdatePartnerInfo(&command.UpdatePartnerInfoCommand{Account: request.Phone}); err == nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
return
}
//重置密码
func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswordRequest) (rsp *protocol.ResetPasswordResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
//partnerInfo *domain.PartnerInfo
)
if len(request.NewPwd) < 6 {
err = protocol.NewErrWithMessage(2027)
return
}
if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
err = protocol.NewErrWithMessage(2026)
return
}
if _, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Id: int(header.UserId)}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if _, err = PartnerInfoService.UpdatePartnerInfo(&command.UpdatePartnerInfoCommand{Password: request.ConfirmPwd}); err == nil {
return
}
return
}
//修改密码
func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) {
var (
PartnerInfoService = service.NewPartnerInfoService(nil)
partnerInfo *domain.PartnerInfo
)
rsp = &protocol.ChangePasswordResponse{}
if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
err = protocol.NewErrWithMessage(2026)
return
}
if strings.EqualFold(request.NewPwd, request.OldPwd) {
err = protocol.NewErrWithMessage(2030)
return
}
if len(request.NewPwd) < 6 {
err = protocol.NewErrWithMessage(2027)
return
}
if partnerInfo, err = PartnerInfoService.GetPartnerInfo(&query.GetPartnerInfoQuery{Id: int(header.UserId)}); err != nil {
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
if !strings.EqualFold(partnerInfo.Password, request.OldPwd) {
//密码不一致
err = protocol.NewErrWithMessage(2028, err) //账号不存在
return
}
if _, err = PartnerInfoService.UpdatePartnerInfo(&command.UpdatePartnerInfoCommand{Password: request.ConfirmPwd}); err == nil {
return
}
return
}
... ...