ソースを参照

添加数据权限演示

yxh 4 年 前
コミット
3bedf02554

+ 102 - 0
app/demo/api/demo_data_auth.go

@@ -0,0 +1,102 @@
+// ==========================================================================
+// GFast自动生成控制器相关代码,只生成一次,按需修改,再次生成不会覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/api/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package api
+
+import (
+	"gfast/app/demo/dao"
+	"gfast/app/demo/model"
+	"gfast/app/demo/service"
+	sysApi "gfast/app/system/api"
+	systemService "gfast/app/system/service"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/net/ghttp"
+	"github.com/gogf/gf/util/gvalid"
+)
+
+type demoDataAuth struct {
+	sysApi.SystemBase
+}
+
+var DemoDataAuth = new(demoDataAuth)
+
+// List 列表
+func (c *demoDataAuth) List(r *ghttp.Request) {
+	var req *dao.DemoDataAuthSearchReq
+	//获取参数
+	if err := r.Parse(&req); err != nil {
+		c.FailJsonExit(r, err.(gvalid.Error).FirstString())
+	}
+	req.Ctx = r.GetCtx()
+	userInfo := c.GetCurrentUser(req.Ctx)
+	where, err := systemService.SysUser.GetDataWhere(userInfo, &model.DemoDataAuth{})
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	total, page, list, err := service.DemoDataAuth.GetList(req, where)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	result := g.Map{
+		"currentPage": page,
+		"total":       total,
+		"list":        list,
+	}
+	c.SusJsonExit(r, result)
+}
+
+// Add 添加
+func (c *demoDataAuth) Add(r *ghttp.Request) {
+	var req *dao.DemoDataAuthAddReq
+	//获取参数
+	err := r.Parse(&req)
+	if err != nil {
+		c.FailJsonExit(r, err.(gvalid.Error).FirstString())
+	}
+	req.CreatedBy = c.GetCurrentUser(r.GetCtx()).GetUserId()
+	err = service.DemoDataAuth.Add(r.GetCtx(), req)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	c.SusJsonExit(r, "添加成功")
+}
+
+// Get 获取
+func (c *demoDataAuth) Get(r *ghttp.Request) {
+	id := r.GetUint("id")
+	info, err := service.DemoDataAuth.GetInfoById(r.GetCtx(), id)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	c.SusJsonExit(r, info)
+}
+
+// Edit 修改
+func (c *demoDataAuth) Edit(r *ghttp.Request) {
+	var req *dao.DemoDataAuthEditReq
+	//获取参数
+	err := r.Parse(&req)
+	if err != nil {
+		c.FailJsonExit(r, err.(gvalid.Error).FirstString())
+	}
+	req.UpdatedBy = c.GetCurrentUser(r.GetCtx()).GetUserId() //获取登陆用户id
+	err = service.DemoDataAuth.Edit(r.GetCtx(), req)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	c.SusJsonExit(r, "修改成功")
+}
+
+// Delete 删除
+func (c *demoDataAuth) Delete(r *ghttp.Request) {
+	ids := r.GetInts("ids")
+	err := service.DemoDataAuth.DeleteByIds(r.GetCtx(), ids)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	c.SusJsonExit(r, "删除成功")
+}

+ 70 - 0
app/demo/dao/demo_data_auth.go

@@ -0,0 +1,70 @@
+// ==========================================================================
+// GFast自动生成dao操作代码,无需手动修改,重新生成不会自动覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/dao/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package dao
+
+import (
+	comModel "gfast/app/common/model"
+	"gfast/app/demo/dao/internal"
+	"github.com/gogf/gf/os/gtime"
+)
+
+// demoDataAuthDao is the manager for logic model data accessing and custom defined data operations functions management.
+// You can define custom methods on it to extend its functionality as you wish.
+type demoDataAuthDao struct {
+	*internal.DemoDataAuthDao
+}
+
+var (
+	// DemoDataAuth is globally public accessible object for table tools_gen_table operations.
+	DemoDataAuth = demoDataAuthDao{
+		internal.NewDemoDataAuthDao(),
+	}
+)
+
+// Fill with you ideas below.
+
+// DemoDataAuthSearchReq 分页请求参数
+type DemoDataAuthSearchReq struct {
+	Id        string `p:"id" v:"id@integer#ID需为整数"`                                     //ID
+	Title     string `p:"title"`                                                        //标题
+	CreatedBy string `p:"createdBy" v:"createdBy@integer#创建人需为整数"`                      //创建人
+	CreatedAt string `p:"createdAt" v:"createdAt@datetime#创建时间需为YYYY-MM-DD hh:mm:ss格式"` //创建时间
+	comModel.PageReq
+}
+
+// DemoDataAuthAddReq 添加操作请求参数
+type DemoDataAuthAddReq struct {
+	Title     string `p:"title" v:"required#标题不能为空"`
+	CreatedBy uint64
+}
+
+// DemoDataAuthEditReq 修改操作请求参数
+type DemoDataAuthEditReq struct {
+	Id        uint   `p:"id" v:"required#主键ID不能为空"`
+	Title     string `p:"title" v:"required#标题不能为空"`
+	UpdatedBy uint64
+}
+
+// DemoDataAuthListRes 列表返回结果
+type DemoDataAuthListRes struct {
+	Id        uint        `json:"id"`
+	Title     string      `json:"title"`
+	CreatedBy uint        `json:"createdBy"`
+	CreatedAt *gtime.Time `json:"createdAt"`
+}
+
+// DemoDataAuthInfoRes 数据返回结果
+type DemoDataAuthInfoRes struct {
+	Id        uint        `json:"id"`
+	Title     string      `json:"title"`
+	CreatedBy uint        `json:"createdBy"`
+	UpdatedBy uint        `json:"updatedBy"`
+	CreatedAt *gtime.Time `json:"createdAt"`
+	UpdatedAt *gtime.Time `json:"updatedAt"`
+	DeletedAt *gtime.Time `json:"deletedAt"`
+}

+ 72 - 0
app/demo/dao/internal/demo_data_auth.go

@@ -0,0 +1,72 @@
+// ==========================================================================
+// GFast自动生成dao internal操作代码,无需手动修改,重新生成会自动覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/dao/internal/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package internal
+
+import (
+	"context"
+	"gfast/app/demo/model"
+	"github.com/gogf/gf/database/gdb"
+	"github.com/gogf/gf/frame/g"
+)
+
+// DemoDataAuthDao is the manager for logic model data accessing and custom defined data operations functions management.
+type DemoDataAuthDao struct {
+	Table   string              // Table is the underlying table name of the DAO.
+	Group   string              // Group is the database configuration group name of current DAO.
+	Columns DemoDataAuthColumns // Columns is the short type for Columns, which contains all the column names of Table for convenient usage.
+}
+
+// DemoDataAuthColumns defines and stores column names for table demo_data_auth.
+type DemoDataAuthColumns struct {
+	Id        string // ID
+	Title     string // 标题
+	CreatedBy string // 创建人
+	UpdatedBy string // 修改人
+	CreatedAt string // 创建时间
+	UpdatedAt string // 修改时间
+	DeletedAt string // 删除时间
+}
+
+var demoDataAuthColumns = DemoDataAuthColumns{
+	Id:        "id",
+	Title:     "title",
+	CreatedBy: "created_by",
+	UpdatedBy: "updated_by",
+	CreatedAt: "created_at",
+	UpdatedAt: "updated_at",
+	DeletedAt: "deleted_at",
+}
+
+// NewDemoDataAuthDao creates and returns a new DAO object for table data access.
+func NewDemoDataAuthDao() *DemoDataAuthDao {
+	return &DemoDataAuthDao{
+		Group:   "default",
+		Table:   "demo_data_auth",
+		Columns: demoDataAuthColumns,
+	}
+}
+
+// DB retrieves and returns the underlying raw database management object of current DAO.
+func (dao *DemoDataAuthDao) DB() gdb.DB {
+	return g.DB(dao.Group)
+}
+
+// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
+func (dao *DemoDataAuthDao) Ctx(ctx context.Context) *gdb.Model {
+	return dao.DB().Model(model.DemoDataAuth{}).Safe().Ctx(ctx)
+}
+
+// Transaction wraps the transaction logic using function f.
+// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
+// It commits the transaction and returns nil if function f returns nil.
+//
+// Note that, you should not Commit or Rollback the transaction in function f
+// as it is automatically handled by this function.
+func (dao *DemoDataAuthDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {
+	return dao.Ctx(ctx).Transaction(ctx, f)
+}

+ 25 - 0
app/demo/model/demo_data_auth.go

@@ -0,0 +1,25 @@
+// ==========================================================================
+// GFast自动生成model代码,无需手动修改,重新生成会自动覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/model/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package model
+
+import (
+	"github.com/gogf/gf/os/gtime"
+	"github.com/gogf/gf/util/gmeta"
+)
+
+// DemoDataAuth is the golang structure for table demo_data_auth.
+type DemoDataAuth struct {
+	gmeta.Meta `orm:"table:demo_data_auth"`
+	Id         uint        `orm:"id,primary" json:"id"`        // ID
+	Title      string      `orm:"title" json:"title"`          // 标题
+	CreatedBy  uint        `orm:"created_by" json:"createdBy"` // 创建人
+	UpdatedBy  uint        `orm:"updated_by" json:"updatedBy"` // 修改人
+	CreatedAt  *gtime.Time `orm:"created_at" json:"createdAt"` // 创建时间
+	UpdatedAt  *gtime.Time `orm:"updated_at" json:"updatedAt"` // 修改时间
+	DeletedAt  *gtime.Time `orm:"deleted_at" json:"deletedAt"` // 删除时间
+}

+ 38 - 0
app/demo/router/demo_data_auth.go

@@ -0,0 +1,38 @@
+// ==========================================================================
+// GFast自动生成路由代码,只生成一次,按需修改,再次生成不会覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/router/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package router
+
+import (
+	"gfast/app/demo/api"
+	sysApi "gfast/app/system/api"
+	"gfast/middleware"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/net/ghttp"
+)
+
+//加载路由
+func init() {
+	s := g.Server()
+	s.Group("/", func(group *ghttp.RouterGroup) {
+		group.Group("/demo", func(group *ghttp.RouterGroup) {
+			group.Group("/demoDataAuth", func(group *ghttp.RouterGroup) {
+				//gToken拦截器
+				sysApi.GfToken.AuthMiddleware(group)
+				//context拦截器
+				group.Middleware(middleware.Ctx, middleware.Auth)
+				//后台操作日志记录
+				group.Hook("/*", ghttp.HookAfterOutput, sysApi.SysOperLog.OperationLog)
+				group.GET("list", api.DemoDataAuth.List)
+				group.GET("get", api.DemoDataAuth.Get)
+				group.POST("add", api.DemoDataAuth.Add)
+				group.PUT("edit", api.DemoDataAuth.Edit)
+				group.DELETE("delete", api.DemoDataAuth.Delete)
+			})
+		})
+	})
+}

+ 136 - 0
app/demo/service/demo_data_auth.go

@@ -0,0 +1,136 @@
+// ==========================================================================
+// GFast自动生成业务逻辑层相关代码,只生成一次,按需修改,再次生成不会覆盖.
+// 生成日期:2022-03-03 10:11:15
+// 生成路径: gfast/app/demo/service/demo_data_auth.go
+// 生成人:gfast
+// ==========================================================================
+
+package service
+
+import (
+	"context"
+	comModel "gfast/app/common/model"
+	"gfast/app/demo/dao"
+	"gfast/app/demo/model"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gconv"
+)
+
+type demoDataAuth struct {
+}
+
+var DemoDataAuth = new(demoDataAuth)
+
+// GetList 获取列表
+func (s *demoDataAuth) GetList(req *dao.DemoDataAuthSearchReq, where ...g.Map) (total, page int, list []*dao.DemoDataAuthListRes, err error) {
+	m := dao.DemoDataAuth.Ctx(req.Ctx).WithAll().As("demo").
+		Unscoped().
+		LeftJoin("sys_user user", "demo.created_by=user.id").
+		Where("demo.deleted_at is null")
+	if req.Id != "" {
+		m = m.Where("demo."+dao.DemoDataAuth.Columns.Id+" = ?", gconv.Uint(req.Id))
+	}
+	if req.Title != "" {
+		m = m.Where("demo."+dao.DemoDataAuth.Columns.Title+" = ?", req.Title)
+	}
+	if req.CreatedBy != "" {
+		m = m.Where("demo."+dao.DemoDataAuth.Columns.CreatedBy+" = ?", gconv.Uint(req.CreatedBy))
+	}
+	if req.BeginTime != "" {
+		m = m.Where("demo."+dao.DemoDataAuth.Columns.CreatedAt+" >=", req.BeginTime)
+	}
+	if req.EndTime != "" {
+		m = m.Where("demo."+dao.DemoDataAuth.Columns.CreatedAt+" <", req.EndTime)
+	}
+	if len(where) > 0 {
+		m = m.Where(where[0])
+	}
+	total, err = m.Count()
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取总行数失败")
+		return
+	}
+	if req.PageNum == 0 {
+		req.PageNum = 1
+	}
+	page = req.PageNum
+	if req.PageSize == 0 {
+		req.PageSize = comModel.PageSize
+	}
+	order := "demo.id asc"
+	if req.OrderBy != "" {
+		order = req.OrderBy
+	}
+	var res []*model.DemoDataAuth
+	err = m.Fields("demo.*").Page(page, req.PageSize).Order(order).Scan(&res)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取数据失败")
+	}
+	list = make([]*dao.DemoDataAuthListRes, len(res))
+	for k, v := range res {
+		list[k] = &dao.DemoDataAuthListRes{
+			Id:        v.Id,
+			Title:     v.Title,
+			CreatedBy: v.CreatedBy,
+			CreatedAt: v.CreatedAt,
+		}
+	}
+	return
+}
+
+// GetInfoById 通过id获取
+func (s *demoDataAuth) GetInfoById(ctx context.Context, id uint) (info *dao.DemoDataAuthInfoRes, err error) {
+	if id == 0 {
+		err = gerror.New("参数错误")
+		return
+	}
+	var data *model.DemoDataAuth
+	err = dao.DemoDataAuth.Ctx(ctx).WithAll().Where(dao.DemoDataAuth.Columns.Id, id).Scan(&data)
+	if err != nil {
+		g.Log().Error(err)
+	}
+	if data == nil || err != nil {
+		err = gerror.New("获取信息失败")
+		return
+	}
+	info = &dao.DemoDataAuthInfoRes{
+		Id:        data.Id,
+		Title:     data.Title,
+		CreatedBy: data.CreatedBy,
+		UpdatedBy: data.UpdatedBy,
+		CreatedAt: data.CreatedAt,
+		UpdatedAt: data.UpdatedAt,
+		DeletedAt: data.DeletedAt,
+	}
+	return
+}
+
+// Add 添加
+func (s *demoDataAuth) Add(ctx context.Context, req *dao.DemoDataAuthAddReq) (err error) {
+	_, err = dao.DemoDataAuth.Ctx(ctx).Insert(req)
+	return
+}
+
+// Edit 修改
+func (s *demoDataAuth) Edit(ctx context.Context, req *dao.DemoDataAuthEditReq) error {
+	_, err := dao.DemoDataAuth.Ctx(ctx).FieldsEx(dao.DemoDataAuth.Columns.Id, dao.DemoDataAuth.Columns.CreatedAt).Where(dao.DemoDataAuth.Columns.Id, req.Id).
+		Update(req)
+	return err
+}
+
+// DeleteByIds 删除
+func (s *demoDataAuth) DeleteByIds(ctx context.Context, ids []int) (err error) {
+	if len(ids) == 0 {
+		err = gerror.New("参数错误")
+		return
+	}
+	_, err = dao.DemoDataAuth.Ctx(ctx).Delete(dao.DemoDataAuth.Columns.Id+" in (?)", ids)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("删除失败")
+	}
+	return
+}

+ 10 - 0
app/system/api/sys_user.go

@@ -103,6 +103,16 @@ func (c *user) EditUser(r *ghttp.Request) {
 	c.SusJsonExit(r, "修改管理员成功")
 }
 
+// UsersGet 获取用户信息列表
+func (c *user) UsersGet(r *ghttp.Request) {
+	ids := r.GetInts("ids")
+	res, err := service.SysUser.GetUsers(ids)
+	if err != nil {
+		c.FailJsonExit(r, err.Error())
+	}
+	c.SusJsonExit(r, res)
+}
+
 // GetInfo 获取登陆用户信息
 func (c *user) GetInfo(r *ghttp.Request) {
 	userInfo := c.GetCurrentUser(r.Context())

+ 6 - 0
app/system/model/sys_user.go

@@ -112,3 +112,9 @@ type ProfileUpdatePwdReq struct {
 	OldPassword string `p:"oldPassword" v:"required#旧密码不能为空"`
 	NewPassword string `p:"newPassword" v:"required#新密码不能为空"`
 }
+
+// SysUserRes 用于查询用户信息对象
+type SysUserRes struct {
+	Id           uint64 `json:"id" orm:"id"`
+	UserNickname string `json:"userNickname" orm:"user_nickname"`
+}

+ 1 - 0
app/system/router/router.go

@@ -115,6 +115,7 @@ func init() {
 				//用户管理
 				group.GET("userList", api.User.UserList)
 				group.GET("userGet", api.User.Get)
+				group.GET("usersGet", api.User.UsersGet)
 				group.POST("addUser", api.User.AddUser)
 				group.GET("getEditUser", api.User.GetEditUser)
 				group.PUT("editUser", api.User.EditUser)

+ 75 - 0
app/system/service/sys_user.go

@@ -18,6 +18,7 @@ import (
 	"github.com/gogf/gf/util/gconv"
 	"github.com/gogf/gf/util/grand"
 	"github.com/mssola/user_agent"
+	"reflect"
 )
 
 type sysUser struct {
@@ -773,3 +774,77 @@ func (s *sysUser) ProfileUpdatePwd(req *model.ProfileUpdatePwdReq) error {
 	})
 	return err
 }
+
+// GetDataWhere 获取数据权限判断条件
+func (s *sysUser) GetDataWhere(userInfo *dao.CtxUser, entity interface{}) (where g.Map, err error) {
+	t := reflect.TypeOf(entity)
+	for i := 0; i < t.Elem().NumField(); i++ {
+		if t.Elem().Field(i).Name == "CreatedBy" {
+			//若存在用户id的字段,则生成判断数据权限的条件
+			//1、获取当前用户所属角色
+			allRoles := ([]*model.SysRole)(nil)
+			allRoles, err = SysRole.GetRoleList()
+			if err != nil {
+				return nil, err
+			}
+			roles := ([]*model.SysRole)(nil)
+			roles, err = s.GetAdminRole(userInfo.Id, allRoles)
+			if err != nil {
+				return nil, err
+			}
+			//2获取角色对应数据权限
+			deptIdArr := gset.New()
+			for _, role := range roles {
+				switch role.DataScope {
+				case 1: //全部数据权限
+					return
+				case 2: //自定数据权限
+					var deptIds []int64
+					deptIds, err = Dept.GetRoleDepts(gconv.Int64(role.Id))
+					if err != nil {
+						return
+					}
+					deptIdArr.Add(gconv.Interfaces(deptIds)...)
+				case 3: //本部门数据权限
+					deptIdArr.Add(gconv.Int64(userInfo.DeptId))
+				case 4: //本部门及以下数据权限
+					deptIdArr.Add(gconv.Int64(userInfo.DeptId))
+					//获取正常状态部门数据
+					depts := ([]*model.SysDept)(nil)
+					depts, err = Dept.GetList(&dao.SysDeptSearchParams{Status: "1"})
+					if err != nil {
+						return
+					}
+					var dList g.List
+					for _, d := range depts {
+						m := g.Map{
+							"id":    d.DeptId,
+							"pid":   d.ParentId,
+							"label": d.DeptName,
+						}
+						dList = append(dList, m)
+					}
+					l := library.FindSonByParentId(dList, gconv.Int(userInfo.DeptId), "pid", "id")
+					for _, li := range l {
+						deptIdArr.Add(gconv.Int64(li["id"]))
+					}
+				}
+			}
+			if deptIdArr.Size() > 0 {
+				where = g.Map{"user.dept_id": deptIdArr.Slice()}
+			}
+		}
+	}
+	return
+}
+
+// GetUsers 通过用户ids查询多个用户信息
+func (s *sysUser) GetUsers(ids []int) (users []*model.SysUserRes, err error) {
+	if len(ids) == 0 {
+		return
+	}
+	idsSet := gset.NewIntSetFrom(ids).Slice()
+	err = dao.SysUser.Where(dao.SysUser.Columns.Id+" in(?)", idsSet).Fields(model.SysUserRes{}).
+		Order(dao.SysUser.Columns.Id + " ASC").Scan(&users)
+	return
+}

+ 3 - 0
router/demo.go

@@ -0,0 +1,3 @@
+package router
+
+import _ "gfast/app/demo/router"