作者 tangxvhui

更新

... ... @@ -3,6 +3,7 @@ module gitlab.fjmaimaimai.com/mmm-go/partnermg
go 1.14
require (
github.com/GeeTeam/gt3-golang-sdk v0.0.0-20200116043922-446ca8a507d2
github.com/ajg/form v1.5.1 // indirect
github.com/astaxie/beego v1.12.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
... ...
package query
//ListAdminUserQuery 获取用户列表
type ListAdminPermissionQuery struct {
NotCode []string
ParentId interface{}
}
... ...
package service
import (
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/query"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)
//AdminUserService 管理员相关服务
type AdminPermissionService struct {
}
func NewAdminPermissionService(option map[string]interface{}) *AdminPermissionService {
newAdminPermissionService := new(AdminPermissionService)
return newAdminPermissionService
}
func (adminPermissionSrv AdminPermissionService) ListAdminPermission(queryOption query.ListAdminPermissionQuery) ([]domain.AdminPermission, error) {
//实际业务
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
permissionRepository domain.AdminPermissionRepository
permissions []domain.AdminPermission
)
if value, err := factory.CreateAdminPermissionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
permissionRepository = value
}
permissions, err = permissionRepository.Find(domain.AdminPermissionFindQuery{
NotCode: queryOption.NotCode,
ParentId: queryOption.ParentId,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return permissions, nil
}
... ...
package command
type SaveAdminUserCommand struct {
Id int64 `json:"id"`
// 员工姓名
Name string `json:"name"`
// 员工账号
Account string `json:"account" `
//密码
Password string `json:"password"`
// 员工角色
PermissionId []int `json:"PermissionId"`
IsUsable bool `json:"isUsable"`
}
... ...
package query
type GetAdminUserQuery struct {
Id int64 `json:"id"`
Admin_Account string `json:"admin_account"`
Id int64 `json:"id"`
AdminAccount string `json:"adminAccount"`
}
... ...
... ... @@ -3,9 +3,9 @@ package query
//ListAdminUserQuery 获取用户列表
type ListAdminUserQuery struct {
//账号匹配
AdminAccountMatch string `json:"admin_account_match" form:"account_match"`
AdminAccountMatch string `json:"adminAccountMatch" `
// 查询偏离量
Offset int `json:"offset" form:"offset"`
Offset int `json:"offset" `
// 查询限制
Limit int `json:"limit" form:"limit"`
Limit int `json:"limit"`
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/command"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)
//AdminUserService 管理员相关服务
... ... @@ -15,12 +17,155 @@ func NewAdminUserService(option map[string]interface{}) *AdminUserService {
return newAdminUserService
}
func (adminUserSrv AdminUserService) GetAdminUser(getAdminUserQuery *query.GetAdminUserQuery) (interface{}, error) {
func (adminUserSrv AdminUserService) GetAdminUser(getAdminUserQuery *query.GetAdminUserQuery) (*domain.AdminUser, error) {
//实际业务
var err error
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "业务逻辑错误")
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
adminuserRepository domain.AdminUserRepository
adminuser *domain.AdminUser
)
if value, err := factory.CreateAdminUserRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
adminuserRepository = value
}
adminuser, err = adminuserRepository.FindOne(domain.AdminUserFindOneQuery{
AccountEqual: getAdminUserQuery.AdminAccount,
AdminUserId: getAdminUserQuery.Id,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return adminuser, nil
}
func (adminUserSrv AdminUserService) SaveAdminUser(saveUserCmd *command.SaveAdminUserCommand) (*domain.AdminUser, error) {
//实际业务
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
adminuserRepository domain.AdminUserRepository
adminuser *domain.AdminUser
)
if value, err := factory.CreateAdminUserRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
adminuserRepository = value
}
//获取权限
var (
permissionRepository domain.AdminPermissionRepository
permissions []domain.AdminPermission
)
if value, err := factory.CreateAdminPermissionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
permissionRepository = value
}
permissions, err = permissionRepository.Find(domain.AdminPermissionFindQuery{
IdsIn: saveUserCmd.PermissionId,
})
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return domain.AdminUser{}, nil
permissionBases := []domain.AdminPermissionBase{}
for i := range permissions {
p := domain.AdminPermissionBase{
Id: permissions[i].Id, Code: permissions[i].Code,
}
permissionBases = append(permissionBases, p)
}
if saveUserCmd.Id > 0 {
adminuser, err = adminuserRepository.FindOne(domain.AdminUserFindOneQuery{
AdminUserId: saveUserCmd.Id,
})
if err != nil {
return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
adminuser.Account = saveUserCmd.Account
adminuser.AdminName = saveUserCmd.Name
adminuser.IsUsable = saveUserCmd.IsUsable
adminuser.Permission = permissionBases
} else {
adminuser = &domain.AdminUser{
Id: saveUserCmd.Id,
Account: saveUserCmd.Account,
Password: saveUserCmd.Password,
AdminName: saveUserCmd.Name,
IsUsable: saveUserCmd.IsUsable,
Permission: permissionBases,
}
}
adminuser, err = adminuserRepository.Save(adminuser)
if err != nil {
return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return adminuser, nil
}
func (adminUserSrv AdminUserService) PageListAdminUser(listAdminUserQuery *query.ListAdminUserQuery) ([]domain.AdminUser, int, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, 0, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, 0, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var (
adminuserRepository domain.AdminUserRepository
adminusers []domain.AdminUser
cnt int
)
if value, err := factory.CreateAdminUserRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
} else {
adminuserRepository = value
}
adminusers, err = adminuserRepository.Find(domain.AdminUserFindQuery{
AccountLike: listAdminUserQuery.AdminAccountMatch,
Offset: listAdminUserQuery.Offset,
Limit: listAdminUserQuery.Limit,
})
if err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
cnt, err = adminuserRepository.CountAll(domain.AdminUserFindQuery{
AccountLike: listAdminUserQuery.AdminAccountMatch,
})
if err != nil {
return nil, 0, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
}
return adminusers, cnt, nil
}
... ...
... ... @@ -7,19 +7,28 @@ import (
)
//CreatePartnerInfoRepository 合伙人信息
func CreatePartnerInfoRepository(options map[string]interface{}) (domain.PartnerInfoRepository, error) {
// func CreatePartnerInfoRepository(options map[string]interface{}) (domain.PartnerInfoRepository, error) {
// var transactionContext *transaction.TransactionContext
// if value, ok := options["transactionContext"]; ok {
// transactionContext = value.(*transaction.TransactionContext)
// }
// return repository.NewPartnerInfoRepository(transactionContext)
// }
//CreateAdminUserRepository 管理员信息
func CreateAdminUserRepository(options map[string]interface{}) (domain.AdminUserRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewPartnerInfoRepository(transactionContext)
return repository.NewAdminUserRepository(transactionContext)
}
//CreateAdminUserRepository 管理员信息
func CreateAdminUserRepository(options map[string]interface{}) (domain.AdminUserRepository, error) {
func CreateAdminPermissionRepository(options map[string]interface{}) (domain.AdminPermissionRepository, error) {
var transactionContext *transaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*transaction.TransactionContext)
}
return repository.NewAdminUserRepository(transactionContext)
return repository.NewAdminPermissionRepository(transactionContext)
}
... ...
package domain
//权限代码
//权限配置 1合作管理人 2订单管理 3分红管理 4管理员管理
const (
PERMINSSION_ADMIN_USER string = "ADMIN_USER"
PERMINSSION_PARTNER string = "PARTNER"
PERMINSSION_PARTNER string = "1合作管理人" //1合作管理人
PERMISSION_ORDER string = "2订单管理" //2订单管理
PERMISSION_DIVIDEND string = "3分红管理" //3分红管理
PERMINSSION_ADMIN_USER string = "4管理员管理" //4管理员管理
)
//权限数据
var ConstAdminPermissions = map[string]AdminPermission{
PERMINSSION_ADMIN_USER: AdminPermission{
Code: PERMINSSION_ADMIN_USER,
Name: "管理员管理",
},
PERMINSSION_PARTNER: AdminPermission{
Code: PERMINSSION_PARTNER,
Name: "合伙人管理",
},
type AdminPermissionBase struct {
Id int `json:"id"`
Code string `json:"code"`
}
// 权限结构
type AdminPermission struct {
Code string `json:"code"`
Name string `json:"name"`
Id int `json:"id"`
ParentId int `json:"parentId"`
Code string `json:"code"`
Name string `json:"name"`
Sort int `json:"sort"`
Icon string `json:"icon"`
}
type AdminPermissionFindQuery struct {
IdsIn []int
NotCode []string
ParentId interface{}
}
func (permission AdminPermission) GetPermissions(codes []string) []AdminPermission {
newPermissions := []AdminPermission{}
if len(codes) == 0 {
return newPermissions
}
for i := range codes {
code := codes[i]
if _, ok := ConstAdminPermissions[code]; ok {
newPermissions = append(newPermissions, ConstAdminPermissions[code])
}
}
return newPermissions
type AdminPermissionRepository interface {
Find(queryOptions AdminPermissionFindQuery) ([]AdminPermission, error)
}
... ...
package domain
import "time"
//AdminUser 管理员
type AdminUser struct {
//id
... ... @@ -9,15 +11,15 @@ type AdminUser struct {
//密码
Password string `json:"password"`
//管理员名称
AdminName string `json:"admin_name"`
AdminName string `json:"adminName"`
//是否是默认系统账号
IsDefault bool `json:"is_default"`
IsDefault bool `json:"isDefault"`
//账号是否可用
IsUsable bool `json:"is_userable"`
IsUsable bool `json:"isUserable"`
//创建时间
CreateAt string `json:"create_at"`
//用户权限
Permission []AdminPermission `json:"permission"`
CreateAt time.Time `json:"createAt"`
//用户权限id
Permission []AdminPermissionBase `json:"permission"`
}
type AdminUserFindQuery struct {
... ... @@ -32,8 +34,8 @@ type AdminUserFindOneQuery struct {
}
type AdminUserRepository interface {
// Save(*AdminUser) (*AdminUser, error)
// Remove(user *AdminUser) (*AdminUser, error)
Save(*AdminUser) (*AdminUser, error)
FindOne(qureyOptions AdminUserFindOneQuery) (*AdminUser, error)
// Find(queryOptions AdminUserFindQuery) (int, []*AdminUser, error)
Find(queryOptions AdminUserFindQuery) ([]AdminUser, error)
CountAll(queryOption AdminUserFindQuery) (int, error)
}
... ...
package models
type AdminPermission struct {
tableName struct{} `pg:"admin_permisssion"`
//id
Id int `pg:",pk"`
//权限名称、菜单名称
Name string
//权限编码
Code string
//父级id
ParentId int
//排序编号
Sort int
//图标
Icon string
}
... ...
... ... @@ -4,6 +4,8 @@ import (
"context"
"time"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"github.com/go-pg/pg/v10"
)
... ... @@ -12,7 +14,7 @@ type AdminUser struct {
//id
Id int64 `pg:",pk"`
//用户账号
AdminAccount string `pg:",unique"`
Account string `pg:",unique"`
//用户名称
AdminName string
//账号密码
... ... @@ -20,7 +22,9 @@ type AdminUser struct {
//是否是默认账号
IsDefault bool `pg:",use_zero"`
//账号是否可用
IsUsable bool `json:"is_userable"`
IsUsable bool
//用户的权限
Permission []domain.AdminPermissionBase
CreateAt time.Time
UpdateAt time.Time
... ...
package repository
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
)
type AdminPermissionRepository struct {
transactionContext *transaction.TransactionContext
}
var (
_ domain.AdminPermissionRepository = (*AdminPermissionRepository)(nil)
)
func NewAdminPermissionRepository(transactionContext *transaction.TransactionContext) (*AdminPermissionRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
}
return &AdminPermissionRepository{transactionContext: transactionContext}, nil
}
func (reponsitory AdminPermissionRepository) transformPgModelToDomainModel(permissionModel *models.AdminPermission) (domain.AdminPermission, error) {
result := domain.AdminPermission{
Id: permissionModel.Id,
ParentId: permissionModel.ParentId,
Name: permissionModel.Name,
Icon: permissionModel.Icon,
Code: permissionModel.Code,
}
return result, nil
}
func (reponsitory AdminPermissionRepository) Find(queryOptions domain.AdminPermissionFindQuery) ([]domain.AdminPermission, error) {
db := reponsitory.transactionContext.PgDd
permissionModels := make([]models.AdminPermission, 0)
query := db.Model(&permissionModels)
if queryOptions.ParentId != nil {
query = query.Where("parent_id=?", queryOptions.ParentId)
}
if len(queryOptions.NotCode) > 0 {
query = query.WhereIn("code not in (?) ", queryOptions.NotCode)
}
if len(queryOptions.IdsIn) > 0 {
query = query.WhereIn(" id in (?) ", queryOptions.IdsIn)
}
if err := query.Select(); err != nil {
return nil, err
}
var result []domain.AdminPermission
for i := range permissionModels {
v, _ := reponsitory.transformPgModelToDomainModel(&permissionModels[i])
result = append(result, v)
}
return result, nil
}
... ...
package repository
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
... ... @@ -16,12 +18,21 @@ var (
func NewAdminUserRepository(transactionContext *transaction.TransactionContext) (*AdminUserRepository, error) {
if transactionContext == nil {
return nil, ERR_EMPTY_TC
return nil, fmt.Errorf("transactionContext参数不能为nil")
}
return &AdminUserRepository{transactionContext: transactionContext}, nil
}
func (reponsitory AdminUserRepository) transformPgModelToDomainModel(adminuserModel *models.AdminUser) (domain.AdminUser, error) {
result := domain.AdminUser{}
result := domain.AdminUser{
Id: adminuserModel.Id,
Account: adminuserModel.Account,
AdminName: adminuserModel.AdminName,
IsDefault: adminuserModel.IsDefault,
CreateAt: adminuserModel.CreateAt,
IsUsable: adminuserModel.IsUsable,
Password: adminuserModel.Password,
Permission: adminuserModel.Permission,
}
return result, nil
}
... ... @@ -43,3 +54,94 @@ func (reponsitory AdminUserRepository) FindOne(queryOption domain.AdminUserFindO
adminUser, err := reponsitory.transformPgModelToDomainModel(adminuserModel)
return &adminUser, err
}
func (reponsitory AdminUserRepository) updateAdminUser(adminuser *domain.AdminUser) (*domain.AdminUser, error) {
tx := reponsitory.transactionContext.PgTx
adminUserModel := &models.AdminUser{
Id: adminuser.Id,
AdminName: adminuser.AdminName,
Password: adminuser.Password,
IsUsable: adminuser.IsUsable,
Permission: adminuser.Permission,
}
_, err := tx.Model(adminUserModel).
Where("id=?", adminUserModel.Id).
Column("admin_name", "password", "is_usable", "permission").
Update()
if err != nil {
return nil, fmt.Errorf("更新用户数据失败:%s", err)
}
return adminuser, nil
}
func (reponsitory AdminUserRepository) addAdminUser(adminuser *domain.AdminUser) (*domain.AdminUser, error) {
tx := reponsitory.transactionContext.PgTx
adminuserModel := &models.AdminUser{
Account: adminuser.Account,
AdminName: adminuser.AdminName,
Password: adminuser.Password,
IsDefault: false,
IsUsable: true,
Permission: adminuser.Permission,
}
//添加用户数据
_, err := tx.Model(adminuserModel).Insert()
if err != nil {
return nil, err
}
return nil, nil
}
func (reponsitory AdminUserRepository) Save(adminuser *domain.AdminUser) (*domain.AdminUser, error) {
if adminuser.Id == 0 {
return reponsitory.addAdminUser(adminuser)
} else {
return reponsitory.updateAdminUser(adminuser)
}
return adminuser, nil
}
func (reponsitory AdminUserRepository) Find(queryOption domain.AdminUserFindQuery) ([]domain.AdminUser, error) {
db := reponsitory.transactionContext.PgDd
adminuserModels := []models.AdminUser{}
query := db.Model(&adminuserModels)
if len(queryOption.AccountLike) > 0 {
query = query.Where("admin_account like ?", "%"+queryOption.AccountLike)
}
if queryOption.Offset > -1 {
query = query.Offset(queryOption.Offset)
}
if queryOption.Limit > 0 {
query = query.Limit(queryOption.Limit)
} else {
query = query.Limit(20)
}
var (
err error
adminuserReturn = make([]domain.AdminUser, 0)
)
err = query.Order("id DESC").Select()
if err != nil {
return adminuserReturn, err
}
for i := range adminuserModels {
domainAdminUser, err := reponsitory.transformPgModelToDomainModel(&adminuserModels[i])
if err != nil {
return adminuserReturn, err
}
adminuserReturn = append(adminuserReturn, domainAdminUser)
}
return adminuserReturn, nil
}
func (reponsitory AdminUserRepository) CountAll(queryOption domain.AdminUserFindQuery) (int, error) {
db := reponsitory.transactionContext.PgDd
adminuserModels := []models.AdminUser{}
query := db.Model(&adminuserModels)
if len(queryOption.AccountLike) > 0 {
query = query.Where("admin_account like ?", "%"+queryOption.AccountLike)
}
cnt, err := query.Count()
return cnt, err
}
... ...
... ... @@ -8,16 +8,18 @@ import (
)
var (
key []byte = []byte("sx87sda0w7x7sd")
key []byte = []byte("sx87sda0w7x7sd")
JWtExpiresSecond int64 = 60 * 60 * 3
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
UID int `json:"uid"` //管理员的id
UID int64 `json:"uid"` //管理员的id
}
func NewMyToken(id int) *MyToken {
func NewMyToken(id int64) *MyToken {
return &MyToken{UID: id}
}
... ... @@ -27,7 +29,7 @@ func (mytoken *MyToken) CreateJWTToken() (string, error) {
mytoken.StandardClaims = jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: 60 * 60 * 3,
ExpiresAt: JWtExpiresSecond,
Issuer: "mmm_partnermg",
}
... ...
package lib
import "strings"
const (
INTERNAL_SERVER_ERROR = iota + 1
BAD_GATEWAY_ERROR
TRANSACTION_ERROR
ARG_ERROR
RES_NO_FIND_ERROR
BUSINESS_ERROR
)
type ServiceError struct {
Prefix string
Code int
Message string
}
func (serviceError ServiceError) Error() string {
return serviceError.Message
}
func ThrowError(serviceErrorNo int, attachMessages ...string) error {
switch serviceErrorNo {
case INTERNAL_SERVER_ERROR:
return ServiceError{
Prefix: "内部服务出错:",
Code: INTERNAL_SERVER_ERROR,
Message: strings.Join(attachMessages, ""),
}
case BAD_GATEWAY_ERROR:
return ServiceError{
Prefix: "服务网关错误:",
Code: BAD_GATEWAY_ERROR,
Message: strings.Join(attachMessages, ""),
}
case TRANSACTION_ERROR:
return ServiceError{
Prefix: "事务处理错误:",
Code: TRANSACTION_ERROR,
Message: strings.Join(attachMessages, ""),
}
case ARG_ERROR:
return ServiceError{
Prefix: "参数认证错误:",
Code: ARG_ERROR,
Message: strings.Join(attachMessages, ""),
}
case RES_NO_FIND_ERROR:
return ServiceError{
Prefix: "找不到相关资源:",
Code: RES_NO_FIND_ERROR,
Message: strings.Join(attachMessages, ""),
}
case BUSINESS_ERROR:
return ServiceError{
Prefix: "业务逻辑错误:",
Code: BUSINESS_ERROR,
Message: strings.Join(attachMessages, ""),
}
default:
return ServiceError{
Prefix: "未定义错误:",
Code: 500,
Message: strings.Join(attachMessages, ""),
}
}
}
... ...
package controllers
import (
"encoding/json"
"errors"
"fmt"
"time"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
"github.com/GeeTeam/gt3-golang-sdk/geetest"
"github.com/astaxie/beego/logs"
adminPermissionquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/query"
adminPermissionService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/service"
adminuserquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query"
adminuserservice "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/service"
)
type AdminLoginController struct {
BaseController
}
////Prepare 重写 BaseController 的Prepare方法
func (c *AdminLoginController) Prepare() {
c.BaseController.Prepare()
//排除登录 以及获取图形验证
urlIn := map[string]int{
"/v1/auth/captcha-init": 1,
"/v1/auth/login": 1,
}
nowUrl := c.Ctx.Input.URL()
if _, ok := urlIn[nowUrl]; ok {
//跳过校验
return
}
if ok := c.ValidJWTToken(); !ok {
return
}
}
//Login 用户登录
func (c *AdminLoginController) Login() {
type Paramter struct {
Username string `json:"username"`
Password string `json:"password"`
}
var (
param Paramter
err error
)
if err = c.BindJsonData(&param); err != nil {
c.ResponseError(fmt.Errorf("json解析失败:%s", err))
return
}
newAdminuserquery := adminuserquery.GetAdminUserQuery{AdminAccount: param.Username}
newAdminUserService := adminuserservice.NewAdminUserService(nil)
adminuser, err := newAdminUserService.GetAdminUser(&newAdminuserquery)
if err != nil {
logs.Error("获取用户数据失败:%s", err)
c.ResponseError(errors.New("用户不存在"))
return
}
if adminuser.Password != param.Password {
c.ResponseError(errors.New("账号或密码错误"))
return
}
newJwt := lib.NewMyToken(adminuser.Id)
newToken, err := newJwt.CreateJWTToken()
if err != nil {
logs.Error("生成jwt数据失败:%s", err)
c.ResponseError(errors.New("服务异常"))
return
}
rspdata := map[string]interface{}{
"access": map[string]interface{}{
"accessToken": newToken,
"expiresIn": lib.JWtExpiresSecond,
},
}
c.ResponseData(rspdata)
return
}
//CaptchaInit 极验初始化
func (c *AdminLoginController) CaptchaInit() {
const (
captchaID = "33a2abf9c5df0d6bc3b89fb39280114b"
privateKey = "13320fd2b10199e9a2440a4fbb4d46f7"
)
newGeetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
userip := c.Ctx.Input.IP()
_, responseBt := newGeetest.PreProcess("", userip)
// c.SetSession("geetest_status", status)
var geetestRsp geetest.FailbackRegisterRespnse
json.Unmarshal(responseBt, &geetestRsp)
//对前端定义的数据格式进行适配。。。
rspData := map[string]interface{}{
"success": geetestRsp.Success,
"gt": geetestRsp.GT,
"challenge": geetestRsp.Challenge,
"newCaptcha": geetestRsp.NewCaptcha,
}
c.ResponseData(rspData)
return
}
//AdminpPofile 获取登录用户的权限配置
func (c *AdminLoginController) AdminpPofile() {
adminId := c.GetUserId()
newAdminuserquery := adminuserquery.GetAdminUserQuery{Id: adminId}
newAdminUserService := adminuserservice.NewAdminUserService(nil)
adminuser, err := newAdminUserService.GetAdminUser(&newAdminuserquery)
if err != nil {
logs.Error("获取用户数据失败:%s", err)
c.ResponseError(errors.New("用户不存在"))
return
}
newPermissionSrv := adminPermissionService.NewAdminPermissionService(nil)
allPermission, err := newPermissionSrv.ListAdminPermission(adminPermissionquery.ListAdminPermissionQuery{})
if err != nil {
logs.Error("获取权限数据失败:%s", err)
c.ResponseError(errors.New("服务异常"))
return
}
//适配前端的数据格式
permissionSlice := make([]map[string]interface{}, 0)
for _, v := range allPermission {
m := map[string]interface{}{
"code": v.Code,
"icon": v.Icon,
"parentId": v.ParentId,
"sort": v.Sort,
"name": v.Name,
"id": v.Id,
"status": 0, //状态 1-启用 0-禁用,前端需要
}
permissionSlice = append(permissionSlice, m)
}
for index := range permissionSlice {
if adminuser.IsDefault {
permissionSlice[index]["status"] = 1
continue
}
for _, p := range adminuser.Permission {
if p == permissionSlice[index]["id"] {
permissionSlice[index]["status"] = 1
}
if p == permissionSlice[index]["parentId"] {
permissionSlice[index]["status"] = 1
}
}
}
userData := map[string]string{
"id": fmt.Sprint(adminuser.Id),
"name": adminuser.AdminName,
"adminType": "2", // 管理员类型 1-超级管理员 2-子管理员
}
if adminuser.IsDefault {
userData["adminType"] = "1"
}
respData := map[string]interface{}{
"user": userData,
"menus": permissionSlice,
}
c.ResponseData(respData)
}
... ...
... ... @@ -4,6 +4,11 @@ import (
"errors"
"github.com/astaxie/beego/logs"
adminPermissionquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/query"
adminPermissionService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/service"
adminuserCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/command"
adminuserquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query"
adminuserservice "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
)
... ... @@ -22,12 +27,53 @@ func (c *AdminUserController) Prepare() {
}
}
func (c *AdminUserController) Demo() {
type adminDetailParam struct {
Id int64 `json:"id"`
PermissionType []int `json:"permissionType"`
Status int `json:"status"`
Pwd string `json:"pwd"`
Account string `json:"account"`
}
func (c *AdminUserController) SaveAdminUser() {
//用与适配前端定义的数据结构
var (
param adminDetailParam
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
newAdminUserService := adminuserservice.NewAdminUserService(nil)
cmd := &adminuserCmd.SaveAdminUserCommand{
Id: param.Id,
Name: param.Account,
Account: param.Account,
Password: param.Pwd,
PermissionId: param.PermissionType,
IsUsable: false,
}
if param.Status == 1 {
cmd.IsUsable = true
}
_, err = newAdminUserService.SaveAdminUser(cmd)
if err != nil {
c.ResponseError(err)
return
}
c.ResponseData(nil)
return
}
func (c *AdminUserController) GetAdminUser() {
//用与适配前端定义的数据结构
type Paramer struct {
type Paramter struct {
Id int64 `json:"id"`
}
var (
param Paramer
param Paramter
err error
)
if err = c.BindJsonData(&param); err != nil {
... ... @@ -35,8 +81,91 @@ func (c *AdminUserController) Demo() {
c.ResponseError(errors.New("json数据解析失败"))
return
}
//Paramer转换为application要求的数据结构
//业务逻辑处理
newAdminUserService := adminuserservice.NewAdminUserService(nil)
adminuser, err := newAdminUserService.GetAdminUser(&adminuserquery.GetAdminUserQuery{
Id: param.Id,
})
if err != nil {
c.ResponseError(err)
return
}
rspData := adminDetailParam{
Id: adminuser.Id,
Account: adminuser.Account,
Status: 0,
}
for _, v := range adminuser.Permission {
rspData.PermissionType = append(rspData.PermissionType, v.Id)
}
if adminuser.IsUsable {
rspData.Status = 1
}
c.ResponseData(rspData)
return
}
c.ResponseData(nil)
func (c *AdminUserController) ListAdminUser() {
//用与适配前端定义的数据结构
type Paramter struct {
SearchText string `json:"searchText"`
PageSize int `json::"pageSize"`
PageNumber int `json:"pageNumber"`
}
var (
param Paramter
err error
)
if err = c.BindJsonData(&param); err != nil {
logs.Error(err)
c.ResponseError(errors.New("json数据解析失败"))
return
}
if param.PageSize == 0 {
param.PageSize = 20
}
if param.PageNumber == 0 {
param.PageNumber = 1
}
newAdminUserService := adminuserservice.NewAdminUserService(nil)
queryOption := &adminuserquery.ListAdminUserQuery{
AdminAccountMatch: param.SearchText,
Limit: param.PageSize,
Offset: param.PageSize * (param.PageNumber - 1),
}
adminusers, cnt, err := newAdminUserService.PageListAdminUser(queryOption)
if err != nil {
c.ResponseError(err)
return
}
newPermissionSrv := adminPermissionService.NewAdminPermissionService(nil)
allPermission, err := newPermissionSrv.ListAdminPermission(adminPermissionquery.ListAdminPermissionQuery{
ParentId: 0,
})
if err != nil {
logs.Error("获取权限数据失败:%s", err)
c.ResponseError(errors.New("服务异常"))
return
}
permissionMap := map[int]domain.AdminPermission{}
for i := range allPermission {
permissionMap[allPermission[i].Id] = allPermission[i]
}
listData := []map[string]interface{}{}
//前端数据格式适配
for i := range adminusers {
permissionTypes := []string{}
for _, vv := range adminusers[i].Permission {
if pm, ok := permissionMap[vv.Id]; ok {
permissionTypes = append(permissionTypes, pm.Name)
}
}
m := map[string]interface{}{
"id": adminusers[i].Id,
"account": adminusers[i].Account,
"permission": permissionTypes,
}
listData = append(listData, m)
}
c.ResponsePageList(listData, cnt, param.PageNumber)
return
}
... ...
... ... @@ -10,7 +10,9 @@ import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/prometheus/common/log"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/lib"
adminuserquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query"
adminuserservice "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/service"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/protocol"
)
... ... @@ -28,6 +30,18 @@ func (controller BaseController) BindJsonData(v interface{}) error {
}
func (controller BaseController) ResponseError(err error) {
if e, ok := err.(lib.ServiceError); ok {
if !(e.Code == lib.ARG_ERROR || e.Code == lib.BUSINESS_ERROR) {
controller.Data["json"] = protocol.ResponseData{
Code: "-1",
Msg: "服务异常",
Data: struct{}{},
}
controller.ServeJSON()
logs.Error(err)
return
}
}
controller.Data["json"] = protocol.ResponseData{
Code: "-1",
Msg: err.Error(),
... ... @@ -35,6 +49,7 @@ func (controller BaseController) ResponseError(err error) {
}
controller.ServeJSON()
logs.Error(err)
return
}
func (controller BaseController) ResponseData(data interface{}) {
... ... @@ -49,6 +64,24 @@ func (controller BaseController) ResponseData(data interface{}) {
controller.ServeJSON()
}
func (controller BaseController) ResponsePageList(data interface{}, totalRow int, pageNumber int) {
if data == nil {
data = []interface{}{}
}
controller.Data["json"] = protocol.ResponseData{
Code: "0",
Msg: "ok",
Data: map[string]map[string]interface{}{
"gridResult": map[string]interface{}{
"lists": data,
"totalRow": totalRow,
"pageNumber": pageNumber,
},
},
}
controller.ServeJSON()
}
//Finish 重写 beego.Controller 的Finish 方法
func (controller *BaseController) Finish() {
strByte, _ := json.Marshal(controller.Data["json"])
... ... @@ -80,19 +113,9 @@ func (controller *BaseController) GetHeaderToken() string {
return controller.Ctx.Input.Header("Authorization")
}
func (controller *BaseController) GetUserId() int {
idV := controller.Ctx.Input.GetData("admin_user_id")
uid, _ := strconv.Atoi(fmt.Sprint(idV))
return uid
}
func (controller *BaseController) setUserId(id int) {
controller.Ctx.Input.SetData("admin_user_id", id)
}
func (controller *BaseController) ValidJWTToken() bool {
headerToken := controller.GetHeaderToken()
mytoken := lib.NewMyToken(0)
mytoken := new(lib.MyToken)
err := mytoken.ValidJWTToken(headerToken)
if err != nil {
if mytoken.IsJwtErrorExpired(err) {
... ... @@ -117,7 +140,7 @@ func (controller *BaseController) ValidJWTToken() bool {
return true
}
func (controller *BaseController) ValidAdminPermission(code string, excludeURL ...string) bool {
func (controller *BaseController) ValidAdminPermission(permissionCode string, excludeURL ...string) bool {
//排除掉的请求
reqUrl := controller.Ctx.Input.URL()
for i := range excludeURL {
... ... @@ -126,15 +149,37 @@ func (controller *BaseController) ValidAdminPermission(code string, excludeURL .
}
}
//权限校验
//
var err error
userId := controller.GetUserId()
newAdminuserquery := adminuserquery.GetAdminUserQuery{Id: userId}
newAdminUserService := adminuserservice.NewAdminUserService(nil)
adminuser, err := newAdminUserService.GetAdminUser(&newAdminuserquery)
if err != nil {
controller.Data["json"] = protocol.ResponseData{
Code: "-1",
Msg: "没有操作权限",
Data: struct{}{},
logs.Error("获取用户数据失败:%s", err)
controller.ResponseError(errors.New("无操作权限"))
return false
}
if !adminuser.IsUsable {
controller.ResponseError(errors.New("用户被禁用"))
return false
}
if adminuser.IsDefault {
logs.Debug("用户是超级管理员")
return true
}
for _, v := range adminuser.Permission {
if v.Code == permissionCode {
return true
}
controller.ServeJSON()
}
return true
return false
}
func (controller *BaseController) GetUserId() int64 {
idV := controller.Ctx.Input.GetData("token:admin_user_id")
uid, _ := strconv.ParseInt(fmt.Sprint(idV), 10, 64)
return uid
}
func (controller *BaseController) setUserId(id int64) {
controller.Ctx.Input.SetData("token:admin_user_id", id)
}
... ...
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/controllers"
)
func init() {
adminRouter := beego.NewNamespace("/admin_user",
// 其余的路由
beego.NSRouter("/get", &controllers.AdminUserController{}, "POST:Demo"),
)
//...
beego.AddNamespace(adminRouter)
}
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/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")
}
package routers
import (
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/port/beego/controllers"
)
func init() {
adminRouter := beego.NewNamespace("/v1",
beego.NSNamespace("/auth",
beego.NSRouter("/login", &controllers.AdminLoginController{}, "POST:Login"),
beego.NSRouter("/captcha-init", &controllers.AdminLoginController{}, "POST:CaptchaInit"),
beego.NSRouter("/profile", &controllers.AdminLoginController{}, "POST:AdminpPofile"),
),
beego.NSNamespace("/admin",
beego.NSRouter("/update", &controllers.AdminUserController{}, "POST:SaveAdminUser"),
beego.NSRouter("/detail", &controllers.AdminUserController{}, "POST:GetAdminUser"),
beego.NSRouter("/list", &controllers.AdminUserController{}, "POST:ListAdminUser"),
),
)
beego.AddNamespace(adminRouter)
}
... ...