作者 yangfu

修改: 1.系统功能模块 2.角色管理 3.用户管理 4.权限设置

... ... @@ -11,6 +11,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol/auth"
"time"
... ... @@ -36,7 +37,7 @@ func (svr *AuthService) Login(header *protocol.RequestHeader, request *protocolx
transactionContext.RollbackTransaction()
}()
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(map[string]interface{}{"phone": request.UserName}); err != nil || user == nil {
err = protocol.NewCustomMessage(1, "用户不存在!")
return
... ... @@ -97,7 +98,7 @@ func (svr *AuthService) Profile(header *protocol.RequestHeader, request *protoco
transactionContext.RollbackTransaction()
}()
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(map[string]interface{}{"id": request.UserId}); err != nil {
err = protocol.NewCustomMessage(1, "用户不存在")
return
... ... @@ -111,9 +112,8 @@ func (svr *AuthService) Profile(header *protocol.RequestHeader, request *protoco
"name": user.Name,
"id": user.Id,
"phone": user.Phone,
"address": user.Address,
"isAdmin": user.IsAdmin,
"roles": roles,
"adminType": user.AdminType,
"roles": utils.LoadCustomField(roles, "Id", "RoleName"),
}
accessIds, _ := RoleAccessDao.GetRoleAccess(user.Roles...)
... ...
... ... @@ -36,7 +36,7 @@ func (svr *CacheService) CacheUserAccess(userId int64) func() (interface{}, erro
transactionContext.RollbackTransaction()
}()
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(map[string]interface{}{"id": userId}); err != nil {
return []*domain.Access{}, nil
}
... ...
... ... @@ -34,6 +34,6 @@ func CreateRoleRepository(transactionContext *transaction.TransactionContext) (d
return repository.NewRoleRepository(transactionContext)
}
func CreateUserRepository(transactionContext *transaction.TransactionContext) (domain.UserRepository, error) {
func CreateUserRepository(transactionContext *transaction.TransactionContext) (domain.UsersRepository, error) {
return repository.NewUserRepository(transactionContext)
}
... ...
... ... @@ -31,7 +31,7 @@ func (svr *RbacService) Access(header *protocol.RequestHeader, request *protocol
var AccessRepository, _ = factory.CreateAccessRepository(transactionContext)
var access []*domain.Access
if _, access, err = AccessRepository.Find(map[string]interface{}{}); err != nil {
if _, access, err = AccessRepository.Find(map[string]interface{}{"sortByParentId": "ASC", "sortBySort": "ASC"}); err != nil {
return
}
var rspList []interface{}
... ...
... ... @@ -5,6 +5,7 @@ import (
"github.com/tiptok/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol/role"
"time"
... ... @@ -45,7 +46,7 @@ func (svr *RoleService) CreateRole(header *protocol.RequestHeader, request *prot
if m, err := RoleRepository.Save(newRole); err != nil {
return nil, err
} else {
rsp = m
rsp = utils.LoadCustomField(m, "Id", "RoleName", "ParentId")
}
err = transactionContext.CommitTransaction()
return
... ... @@ -73,13 +74,17 @@ func (svr *RoleService) UpdateRole(header *protocol.RequestHeader, request *prot
if role, err = RoleRepository.FindOne(common.ObjectToMap(request)); err != nil {
return
}
if role.Id == request.ParentId {
err = protocol.NewCustomMessage(1, "父角色不能设为自己")
return
}
if request.ParentId > 0 {
if role, e := RoleRepository.FindOne(map[string]interface{}{"id": request.ParentId}); e != nil || role == nil {
err = protocol.NewCustomMessage(1, "父角色不存在")
return
}
}
if err = role.Update(common.ObjectToMap(request)); err != nil {
if err = role.Update(map[string]interface{}{"roleName": request.RoleName, "parentId": request.ParentId}); err != nil {
return
}
if role, err = RoleRepository.Save(role); err != nil {
... ... @@ -111,7 +116,7 @@ func (svr *RoleService) GetRole(header *protocol.RequestHeader, request *protoco
if role, err = RoleRepository.FindOne(common.ObjectToMap(request)); err != nil {
return
}
rsp = map[string]interface{}{"role": role, "permission": ""}
rsp = map[string]interface{}{"role": utils.LoadCustomField(role, "Id", "RoleName", "ParentId"), "permission": ""}
err = transactionContext.CommitTransaction()
return
}
... ... @@ -145,7 +150,7 @@ func (svr *RoleService) DeleteRole(header *protocol.RequestHeader, request *prot
if role, err = RoleRepository.Remove(role); err != nil {
return
}
rsp = role
rsp = utils.LoadCustomField(role, "Id", "RoleName", "ParentId")
err = transactionContext.CommitTransaction()
return
}
... ... @@ -169,12 +174,12 @@ func (svr *RoleService) ListRole(header *protocol.RequestHeader, request *protoc
var RoleRepository, _ = factory.CreateRoleRepository(transactionContext)
var role []*domain.Role
var total int64
if total, role, err = RoleRepository.Find(common.ObjectToMap(request)); err != nil {
if _, role, err = RoleRepository.Find(map[string]interface{}{"orderById": "DESC"}); err != nil {
return
}
rsp = map[string]interface{}{
"total": total,
"list": role,
"list": utils.LoadCustomField(role, "Id", "RoleName", "ParentId"),
}
err = transactionContext.CommitTransaction()
return
... ...
... ... @@ -8,6 +8,7 @@ import (
"github.com/tiptok/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol/user"
)
... ... @@ -31,13 +32,12 @@ func (svr *UserService) CreateUser(header *protocol.RequestHeader, request *prot
defer func() {
transactionContext.RollbackTransaction()
}()
newUser := &domain.User{
newUser := &domain.Users{
Name: request.Name,
Address: request.Address,
Phone: request.Phone,
//Passwd: request.Passwd,
Roles: request.Roles,
IsAdmin: request.IsAdmin,
Status: 1,
AdminType: request.AdminType,
}
var UserRepository, _ = factory.CreateUserRepository(transactionContext)
... ... @@ -81,7 +81,7 @@ func (svr *UserService) UpdateUser(header *protocol.RequestHeader, request *prot
}()
var UserRepository, _ = factory.CreateUserRepository(transactionContext)
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(map[string]interface{}{"id": request.Id}); err != nil {
err = protocol.NewCustomMessage(1, "用户不存在")
return
... ... @@ -110,6 +110,7 @@ func (svr *UserService) UpdateUser(header *protocol.RequestHeader, request *prot
func (svr *UserService) GetUser(header *protocol.RequestHeader, request *protocolx.GetUserRequest) (rsp interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
RoleRepository, _ = factory.CreateRoleRepository(transactionContext)
)
rsp = &protocolx.GetUserResponse{}
if err = request.ValidateCommand(); err != nil {
... ... @@ -125,12 +126,18 @@ func (svr *UserService) GetUser(header *protocol.RequestHeader, request *protoco
}()
var UserRepository, _ = factory.CreateUserRepository(transactionContext)
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(common.ObjectToMap(request)); err != nil {
err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
return
}
rsp = user
retMap := map[string]interface{}{"id": user.Id, "name": user.Name, "phone": user.Phone, "adminType": user.AdminType, "status": user.Status}
if len(user.Roles) > 0 {
if _, roles, e := RoleRepository.Find(map[string]interface{}{"inRoleIds": user.Roles}); len(roles) > 0 && e == nil {
retMap["roles"] = utils.LoadCustomField(roles, "Id", "RoleName")
}
}
rsp = map[string]interface{}{"user": retMap}
if err = transactionContext.CommitTransaction(); err != nil {
err = application.ThrowError(application.TRANSACTION_ERROR, err.Error())
return
... ... @@ -156,7 +163,7 @@ func (svr *UserService) DeleteUser(header *protocol.RequestHeader, request *prot
}()
var UserRepository, _ = factory.CreateUserRepository(transactionContext)
var user *domain.User
var user *domain.Users
if user, err = UserRepository.FindOne(common.ObjectToMap(request)); err != nil {
err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
return
... ... @@ -191,15 +198,16 @@ func (svr *UserService) ListUser(header *protocol.RequestHeader, request *protoc
}()
var UserRepository, _ = factory.CreateUserRepository(transactionContext)
var user []*domain.User
var user []*domain.Users
var total int64
if total, user, err = UserRepository.Find(common.ObjectToMap(request)); err != nil {
if total, user, err = UserRepository.Find(map[string]interface{}{"offset": request.PageNumber * request.PageSize, "limit": request.PageSize, "sortById": "DESC"}); err != nil {
err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
return
}
rsp = map[string]interface{}{
"total": total,
"list": user,
"totalRow": total,
"pageNumber": request.PageNumber,
"list": utils.LoadCustomField(user, "Id", "Name", "Phone", "IsAdmin", "Status"),
}
if err = transactionContext.CommitTransaction(); err != nil {
err = application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ...
... ... @@ -7,9 +7,9 @@ type Access struct {
// 父级id
ParentId int64 `json:"parentId"`
// 权限名称
AccessName string `json:"accessName"`
AccessName string `json:"name"`
// 权限编码
AccessCode string `json:"accessCode"`
AccessCode string `json:"code"`
// 权限类型 menu button data
AccessType string `json:"accessType"`
// 排序
... ... @@ -20,6 +20,10 @@ type Access struct {
Action string `json:"action"`
// 所属功能模块
Module string `json:"module"`
// icon
Icon string `json:"icon"`
// 状态 1-启用 0-禁用
Status int `json:"status"`
}
type AccessRepository interface {
... ...
package domain
// User
type User struct {
// Users
type Users struct {
// 唯一标识
Id int64 `json:"id"`
// 名称
Name string `json:"name"`
// 地址
Address string `json:"address"`
//Address string `json:"address"`
// 手机号
Phone string `json:"phone"`
// 密码
Passwd string `json:"-"`
// 用户角色
Roles []int64 `json:"roles"`
// 是否是超级管理员 true:是 false:否
IsAdmin bool `json:"isAdmin"`
// 1启用 2禁用
Status int `json:"status"`
// 管理员类型
AdminType int `json:"adminType"`
}
type UserRepository interface {
Save(dm *User) (*User, error)
Remove(dm *User) (*User, error)
FindOne(queryOptions map[string]interface{}) (*User, error)
Find(queryOptions map[string]interface{}) (int64, []*User, error)
type UsersRepository interface {
Save(dm *Users) (*Users, error)
Remove(dm *Users) (*Users, error)
FindOne(queryOptions map[string]interface{}) (*Users, error)
Find(queryOptions map[string]interface{}) (int64, []*Users, error)
}
func (m *User) Identify() interface{} {
func (m *Users) Identify() interface{} {
if m.Id == 0 {
return nil
}
return m.Id
}
func (m *User) Update(data map[string]interface{}) error {
func (m *Users) Update(data map[string]interface{}) error {
if name, ok := data["name"]; ok {
m.Name = name.(string)
}
if address, ok := data["address"]; ok {
m.Address = address.(string)
}
if phone, ok := data["phone"]; ok {
m.Phone = phone.(string)
}
... ... @@ -48,8 +47,11 @@ func (m *User) Update(data map[string]interface{}) error {
if roles, ok := data["roles"]; ok {
m.Roles = roles.([]int64)
}
if isAdmin, ok := data["isAdmin"]; ok {
m.IsAdmin = isAdmin.(bool)
if adminType, ok := data["adminType"]; ok {
m.AdminType = adminType.(int)
}
if status, ok := data["status"]; ok {
m.Status = status.(int)
}
return nil
}
... ...
... ... @@ -33,7 +33,7 @@ func init() {
(*models.ProjectModuleVersion)(nil),
(*models.Role)(nil),
(*models.RoleAccess)(nil),
(*models.User)(nil),
(*models.Users)(nil),
} {
err := DB.CreateTable(model, &orm.CreateTableOptions{
Temp: false,
... ...
... ... @@ -21,4 +21,8 @@ type Access struct {
Action string
// 所属功能模块
Module string
// icon
Icon string
// 状态 1-启用 0-禁用
Status int
}
... ...
package models
// User
type User struct {
tableName struct{} `pg:"user"`
// Users
type Users struct {
tableName struct{} `pg:"users"`
// 唯一标识
Id int64
// 名称
Name string
// 地址
Address string
// 手机号
Phone string
// 密码
Passwd string
// 用户角色
Roles []int64
// 是否是超级管理员 true:是 false:否
IsAdmin bool
// 1启用 2禁用
Status int
// 管理员类型 1:超级管理员 2:普通账号
AdminType int
}
... ...
... ... @@ -66,8 +66,9 @@ func (repository *AccessRepository) Find(queryOptions map[string]interface{}) (i
Accesss := make([]*domain.Access, 0)
query := NewQuery(tx.Model(&AccessModels), queryOptions).
SetOrder("create_time", "sortByCreateTime").
SetOrder("update_time", "sortByUpdateTime")
SetOrder("update_time", "sortByUpdateTime").
SetOrder("parent_id", "sortByParentId").
SetOrder("sort", "sortBySort")
if inAccessIds, ok := queryOptions["inAccessIds"]; ok {
query.Where("id in (?)", pg.In(inAccessIds))
}
... ...
... ... @@ -27,9 +27,10 @@ func (repository *RoleRepository) Save(dm *domain.Role) (*domain.Role, error) {
if err = tx.Insert(m); err != nil {
return nil, err
}
dm.Id = m.Id
return dm, nil
}
if err = tx.Update(m); err != nil {
if _, err = tx.Exec(`update role set role_name=?,parent_id=?,update_time=now() where id = ?`, m.RoleName, m.ParentId, m.Id); err != nil {
return nil, err
}
return dm, nil
... ... @@ -67,7 +68,9 @@ func (repository *RoleRepository) Find(queryOptions map[string]interface{}) (int
query := NewQuery(tx.Model(&RoleModels), queryOptions).
SetWhere("parent_id=?", "parentId").
SetOrder("create_time", "sortByCreateTime").
SetOrder("update_time", "sortByUpdateTime")
SetOrder("update_time", "sortByUpdateTime").
SetOrder("id", "orderById")
var err error
if inRoleIds, ok := queryOptions["inRoleIds"]; ok {
query.Where("id in (?)", pg.In(inRoleIds))
... ...
... ... @@ -9,14 +9,14 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/pg/transaction"
)
type UserRepository struct {
type UsersRepository struct {
transactionContext *transaction.TransactionContext
}
func (repository *UserRepository) Save(dm *domain.User) (*domain.User, error) {
func (repository *UsersRepository) Save(dm *domain.Users) (*domain.Users, error) {
var (
err error
m = &models.User{}
m = &models.Users{}
tx = repository.transactionContext.PgTx
)
if err = common.GobModelTransform(m, dm); err != nil {
... ... @@ -35,10 +35,10 @@ func (repository *UserRepository) Save(dm *domain.User) (*domain.User, error) {
return dm, nil
}
func (repository *UserRepository) Remove(User *domain.User) (*domain.User, error) {
func (repository *UsersRepository) Remove(User *domain.Users) (*domain.Users, error) {
var (
tx = repository.transactionContext.PgTx
UserModel = &models.User{Id: User.Identify().(int64)}
UserModel = &models.Users{Id: User.Identify().(int64)}
)
if _, err := tx.Model(UserModel).Where("id = ?", User.Id).Delete(); err != nil {
return User, err
... ... @@ -46,9 +46,9 @@ func (repository *UserRepository) Remove(User *domain.User) (*domain.User, error
return User, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
func (repository *UsersRepository) FindOne(queryOptions map[string]interface{}) (*domain.Users, error) {
tx := repository.transactionContext.PgTx
UserModel := new(models.User)
UserModel := new(models.Users)
query := NewQuery(tx.Model(UserModel), queryOptions)
query.SetWhere("id = ?", "id")
query.SetWhere("phone = ?", "phone")
... ... @@ -61,13 +61,15 @@ func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (
return repository.transformPgModelToDomainModel(UserModel)
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
func (repository *UsersRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Users, error) {
tx := repository.transactionContext.PgTx
var UserModels []*models.User
Users := make([]*domain.User, 0)
var UserModels []*models.Users
Users := make([]*domain.Users, 0)
query := NewQuery(tx.Model(&UserModels), queryOptions).
SetOrder("create_time", "sortByCreateTime").
SetOrder("update_time", "sortByUpdateTime")
SetOrder("update_time", "sortByUpdateTime").
SetOrder("id", "sortById").
SetLimit()
var err error
if query.AffectRow, err = query.SelectAndCount(); err != nil {
return 0, Users, err
... ... @@ -82,15 +84,15 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
return int64(query.AffectRow), Users, nil
}
func (repository *UserRepository) transformPgModelToDomainModel(UserModel *models.User) (*domain.User, error) {
m := &domain.User{}
func (repository *UsersRepository) transformPgModelToDomainModel(UserModel *models.Users) (*domain.Users, error) {
m := &domain.Users{}
err := common.GobModelTransform(m, UserModel)
return m, err
}
func NewUserRepository(transactionContext *transaction.TransactionContext) (*UserRepository, error) {
func NewUserRepository(transactionContext *transaction.TransactionContext) (*UsersRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
}
return &UserRepository{transactionContext: transactionContext}, nil
return &UsersRepository{transactionContext: transactionContext}, nil
}
... ...
package utils
import (
"github.com/tiptok/gocomm/common"
"reflect"
)
func LoadCustomField(src interface{}, fields ...string) interface{} {
typeSrc := reflect.TypeOf(src)
valueSrc := reflect.ValueOf(src)
if v, ok := src.(reflect.Value); ok {
valueSrc = v
typeSrc = v.Type()
}
if typeSrc.Kind() == reflect.Ptr {
valueSrc = valueSrc.Elem()
}
k := valueSrc.Kind()
switch k {
case reflect.Array, reflect.Slice:
len := valueSrc.Len()
retSliceMap := make([]map[string]interface{}, 0)
if len == 0 {
return retSliceMap
}
for i := 0; i < len; i++ {
v := valueSrc.Index(i)
//if v.Kind()==reflect.Ptr
//item :=make(map[string]interface{})
//for _,filed :=range fields{
// f:= v.FieldByName(filed)
// item[common.CamelCase(filed, false)] = f.Interface()
//}
retSliceMap = append(retSliceMap, (LoadCustomField(v, fields...)).(map[string]interface{}))
}
return retSliceMap
case reflect.Struct:
retSliceMap := make(map[string]interface{})
for _, filed := range fields {
f := valueSrc.FieldByName(filed)
retSliceMap[common.CamelCase(filed, false)] = f.Interface()
}
return retSliceMap
default:
return src
}
return src
}
... ...
package utils
import (
"github.com/tiptok/gocomm/common"
"testing"
)
func TestLoadCustomField(t *testing.T) {
type User struct {
Name string
Id int
}
v := []struct {
Name string
Id int
}{{Name: "c1", Id: 1}, {Name: "c2", Id: 2}, {Name: "c3", Id: 3}}
ret := LoadCustomField(&v, "Name")
t.Log(common.JsonAssertString(ret))
v2 := struct {
Name string
Id int
}{Name: "c1", Id: 1}
ret2 := LoadCustomField(v2, "Name", "Id")
t.Log(common.JsonAssertString(ret2))
v3 := []*User{&User{Name: "c1", Id: 1}, &User{Name: "c2", Id: 2}, &User{Name: "c3", Id: 3}}
ret3 := LoadCustomField(&v3, "Name")
t.Log(common.JsonAssertString(ret3))
}
... ...
... ... @@ -3,6 +3,7 @@ package beego
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/plugins/cors"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/port/beego/middleware"
_ "gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/port/beego/routers"
)
... ... @@ -15,10 +16,11 @@ func init() {
AllowCredentials: true,
}))
//beego.InsertFilter("/user/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
//beego.InsertFilter("/role/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
//beego.InsertFilter("/project_module/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
//beego.InsertFilter("/project_module_version/*", beego.BeforeExec, middleware.InspectRoleAccess("/project_module/*"))
//beego.InsertFilter("/project_module_files/*", beego.BeforeExec, middleware.InspectRoleAccess("/project_module/*"))
//beego.InsertFilter("/rbac/*", beego.BeforeExec, middleware.InspectRoleAccess("/role/*"))
beego.InsertFilter("/auth/profile", beego.BeforeExec, middleware.CheckAuthorization)
beego.InsertFilter("/user/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
beego.InsertFilter("/role/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
beego.InsertFilter("/project_module/*", beego.BeforeExec, middleware.InspectRoleAccess(""))
beego.InsertFilter("/project_module_version/*", beego.BeforeExec, middleware.InspectRoleAccess("/project_module/*"))
beego.InsertFilter("/project_module_files/*", beego.BeforeExec, middleware.InspectRoleAccess("/project_module/*"))
beego.InsertFilter("/rbac/*", beego.BeforeExec, middleware.InspectRoleAccess("/role/*"))
}
... ...
... ... @@ -13,20 +13,20 @@ type AuthController struct {
// Login
// 登录
func (this *AuthController) Login() {
func (controller *AuthController) Login() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request *protocolx.LoginRequest
)
defer func() {
this.Resp(msg)
controller.Resp(msg)
}()
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.NewResponseMessage(2, "")
if err := controller.JsonUnmarshal(&request); err != nil {
msg = protocol.NewResponseMessage(2, err.Error())
return
}
header := this.GetRequestHeader(this.Ctx)
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.Login(header, request)
if err != nil {
log.Error(err)
... ... @@ -36,20 +36,20 @@ func (this *AuthController) Login() {
// Logout
// 测试
func (this *AuthController) Logout() {
func (controller *AuthController) Logout() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request *protocolx.LogoutRequest
)
defer func() {
this.Resp(msg)
controller.Resp(msg)
}()
if err := this.JsonUnmarshal(&request); err != nil {
if err := controller.JsonUnmarshal(&request); err != nil {
msg = protocol.NewResponseMessage(2, "")
return
}
header := this.GetRequestHeader(this.Ctx)
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.Logout(header, request)
if err != nil {
log.Error(err)
... ... @@ -59,20 +59,17 @@ func (this *AuthController) Logout() {
// Profile
// 获取当前用户数据
func (this *AuthController) Profile() {
func (controller *AuthController) Profile() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request *protocolx.ProfileRequest
request = &protocolx.ProfileRequest{}
)
defer func() {
this.Resp(msg)
controller.Resp(msg)
}()
if err := this.JsonUnmarshal(&request); err != nil {
msg = protocol.NewResponseMessage(2, "")
return
}
header := this.GetRequestHeader(this.Ctx)
header := controller.GetRequestHeader(controller.Ctx)
request.UserId = header.UserId
data, err := svr.Profile(header, request)
if err != nil {
log.Error(err)
... ... @@ -82,17 +79,17 @@ func (this *AuthController) Profile() {
// CaptchaInit
// 图形验证码初始化
func (this *AuthController) CaptchaInit() {
func (controller *AuthController) CaptchaInit() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request = &protocolx.CaptchaInitRequest{}
)
defer func() {
this.Resp(msg)
controller.Resp(msg)
}()
request.UserIp = this.Ctx.Input.IP()
header := this.GetRequestHeader(this.Ctx)
request.UserIp = controller.Ctx.Input.IP()
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.CaptchaInit(header, request)
if err != nil {
log.Error(err)
... ... @@ -102,20 +99,20 @@ func (this *AuthController) CaptchaInit() {
// ChangePassword
// 修改密码
func (this *AuthController) ChangePassword() {
func (controller *AuthController) ChangePassword() {
var (
msg *protocol.ResponseMessage
svr = auth.NewAuthService(nil)
request *protocolx.ChangePasswordRequest
)
defer func() {
this.Resp(msg)
controller.Resp(msg)
}()
if err := this.JsonUnmarshal(&request); err != nil {
if err := controller.JsonUnmarshal(&request); err != nil {
msg = protocol.NewResponseMessage(2, "")
return
}
header := this.GetRequestHeader(this.Ctx)
header := controller.GetRequestHeader(controller.Ctx)
data, err := svr.ChangePassword(header, request)
if err != nil {
log.Error(err)
... ...
... ... @@ -6,7 +6,6 @@ import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
"strconv"
)
type BaseController struct {
... ... @@ -42,6 +41,9 @@ func (controller BaseController) GetLimitInfo() (offset int, limit int) {
//获取请求头信息
func (controller *BaseController) GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.UserId, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-id"), 10, 64)
if ctx.Input.GetData("x-mmm-id") != nil {
v := ctx.Input.GetData("x-mmm-id")
h.UserId = int64(v.(int))
}
return h
}
... ...
... ... @@ -118,5 +118,5 @@ func (controller *UserController) ListUser() {
if err != nil {
log.Error(err)
}
msg = protocol.NewResponseMessageData(data, err)
msg = protocol.NewResponseMessageListData(data, err)
}
... ...
... ... @@ -26,7 +26,7 @@ func CheckAuthorization(ctx *context.Context) {
}()
authorization := ctx.Input.Header("Authorization")
if len(authorization) == 0 {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
msg = protocol.NewResponseMessage(-1, errAuthorization.Error())
return
}
var token string
... ... @@ -38,7 +38,7 @@ func CheckAuthorization(ctx *context.Context) {
}
claim, err := common.ParseJWTToken(token)
if err != nil {
msg = protocol.NewResponseMessage(1, errAuthorizationExpire.Error())
msg = protocol.NewResponseMessage(-1, errAuthorizationExpire.Error())
return
}
userId, _ := strconv.Atoi(claim.Username)
... ... @@ -57,12 +57,12 @@ func CheckRoleAccess(ctx *context.Context, object, method string) {
}()
userId := ctx.Input.GetData("x-mmm-id")
if userId == nil {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
msg = protocol.NewResponseMessage(-1, errAuthorization.Error())
return
}
validUserRole := cachex.CacheService{}
if ok, _ := validUserRole.ValidUserAccess(int64(userId.(int)), object, method); !ok {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
msg = protocol.NewResponseMessage(-1, errAuthorization.Error())
return
}
return
... ...
... ... @@ -9,6 +9,6 @@ func init() {
beego.Router("/auth/login", &controllers.AuthController{}, "post:Login")
beego.Router("/auth/logout", &controllers.AuthController{}, "post:Logout")
beego.Router("/auth/profile", &controllers.AuthController{}, "post:Profile")
beego.Router("/auth/captchaInit", &controllers.AuthController{}, "get:CaptchaInit")
beego.Router("/auth/captcha-init", &controllers.AuthController{}, "post:CaptchaInit")
beego.Router("/auth/changePassword", &controllers.AuthController{}, "post:ChangePassword")
}
... ...
... ... @@ -83,6 +83,11 @@ func NewResponseMessageData(data interface{}, err error) *ResponseMessage {
return NewMesage(1)
}
func NewResponseMessageListData(data interface{}, err error) *ResponseMessage {
mapData := map[string]interface{}{"gridResult": data}
return NewResponseMessageData(mapData, err)
}
func NewResponseMessage(code int, err string) *ResponseMessage {
return &ResponseMessage{
ErrorCode: ErrorCode{
... ...
... ... @@ -16,8 +16,8 @@ type CreateUserRequest struct {
Passwd string `json:"passwd,omitempty"`
// 用户角色
Roles []int64 `json:"roles,omitempty"`
// 是否是超级管理员 true:是 false:否
IsAdmin bool `json:"isAdmin,omitempty"`
// 管理员类型 1:超级管理员 2:普通账号
AdminType int `json:"adminType"`
}
func (CreateUserRequest *CreateUserRequest) ValidateCommand() error {
... ...
... ... @@ -17,8 +17,10 @@ type UpdateUserRequest struct {
Passwd string `json:"passwd,omitempty"`
// 用户角色
Roles []int64 `json:"roles,omitempty"`
// 是否是超级管理员 true:是 false:否
IsAdmin bool `json:"isAdmin,omitempty"`
// 1启用 2禁用
Status int `json:"status,omitempty"`
// 管理员类型 1:超级管理员 2:普通账号
AdminType int `json:"adminType"`
}
func (UpdateUserRequest *UpdateUserRequest) ValidateCommand() error {
... ...
... ... @@ -6,10 +6,15 @@ import (
)
type ListUserRequest struct {
PageSize int `json:"pageSize"`
PageNumber int `json:"pageNumber"`
}
func (ListUserRequest *ListUserRequest) ValidateCommand() error {
valid := validation.Validation{}
if ListUserRequest.PageNumber == 0 {
ListUserRequest.PageNumber = 20
}
b, err := valid.Valid(ListUserRequest)
if err != nil {
return err
... ...