From 562e61cf4f5c40cb24640e2af76570a30bd4cff2 Mon Sep 17 00:00:00 2001 From: linwenxiang <991154416@qq.com> Date: Sat, 29 Aug 2020 22:22:52 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E4=BD=BF=E7=94=A8action=E4=BB=A3=E6=9B=BFa?= =?UTF-8?q?pi=E5=8D=95=E4=B8=AA=E6=93=8D=E4=BD=9C=20=E6=94=B9=E5=86=99job?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apis/actions/create.go | 39 ++++++++++++++++++++++++++++++++ apis/actions/delete.go | 42 ++++++++++++++++++++++++++++++++++ apis/actions/index.go | 51 ++++++++++++++++++++++++++++++++++++++++++ apis/actions/update.go | 39 ++++++++++++++++++++++++++++++++ apis/actions/view.go | 40 +++++++++++++++++++++++++++++++++ dto/pagination.go | 6 +++++ dto/sysjob.go | 22 ++++++++++++++++++ dto/type.go | 9 ++++++++ go.mod | 1 + middleware/db.go | 17 ++++++++++++++ models/sysjob.go | 15 +++++++++++++ router/initrouter.go | 2 ++ router/sysrouter.go | 20 ++++++++++++----- tools/dto.go | 25 ++++++++++++++++++++- tools/model/type.go | 10 +++++++++ 15 files changed, 332 insertions(+), 6 deletions(-) create mode 100644 apis/actions/create.go create mode 100644 apis/actions/delete.go create mode 100644 apis/actions/index.go create mode 100644 apis/actions/update.go create mode 100644 apis/actions/view.go create mode 100644 dto/pagination.go create mode 100644 dto/type.go create mode 100644 middleware/db.go create mode 100644 tools/model/type.go diff --git a/apis/actions/create.go b/apis/actions/create.go new file mode 100644 index 0000000..79212ac --- /dev/null +++ b/apis/actions/create.go @@ -0,0 +1,39 @@ +package actions + +import ( + "errors" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-admin/tools" + "go-admin/tools/app" + "go-admin/tools/model" +) + +// CreateAction 通用新增动作 +func CreateAction(m model.ActiveRecord) gin.HandlerFunc { + return func(c *gin.Context) { + object := m.Generate() + var err error + idb, exist := c.Get("db") + if !exist { + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + switch idb.(type) { + case *gorm.DB: + //新增操作 + db := idb.(*gorm.DB) + err = c.Bind(object) + tools.HasError(err, "参数验证失败", 422) + err = db.WithContext(c).Create(object).Error + tools.HasError(err, "创建失败", 500) + default: + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + app.OK(c, object.GetId(), "创建成功") + c.Next() + } +} diff --git a/apis/actions/delete.go b/apis/actions/delete.go new file mode 100644 index 0000000..522aa4c --- /dev/null +++ b/apis/actions/delete.go @@ -0,0 +1,42 @@ +package actions + +import ( + "errors" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-admin/tools" + "go-admin/tools/app" + "go-admin/tools/model" +) + +// DeleteAction 通用删除动作 +func DeleteAction(m model.ActiveRecord) gin.HandlerFunc { + return func(c *gin.Context) { + object := m.Generate() + var err error + idb, exist := c.Get("db") + if !exist { + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + switch idb.(type) { + case *gorm.DB: + //新增操作 + db := idb.(*gorm.DB) + var generalDelDto tools.GeneralDelDto + err = c.Bind(&generalDelDto) + tools.HasError(err, "参数验证失败", 422) + err = c.BindUri(&generalDelDto) + tools.HasError(err, "参数验证失败", 422) + err = db.WithContext(c).Where(generalDelDto.GetIds()).Delete(object).Error + tools.HasError(err, "更新失败", 500) + default: + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + app.OK(c, object.GetId(), "更新成功") + c.Next() + } +} diff --git a/apis/actions/index.go b/apis/actions/index.go new file mode 100644 index 0000000..5d070d0 --- /dev/null +++ b/apis/actions/index.go @@ -0,0 +1,51 @@ +package actions + +import ( + "errors" + "go-admin/dto" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-admin/tools" + "go-admin/tools/app" + "go-admin/tools/model" +) + +// IndexAction 通用查询动作 +func IndexAction(m model.ActiveRecord, d dto.Dtor) gin.HandlerFunc { + return func(c *gin.Context) { + object := m.Generate() + req := d.Generate() + var err error + idb, exist := c.Get("db") + if !exist { + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + list := object.GenerateList() + var count int64 + switch idb.(type) { + case *gorm.DB: + //新增操作 + db := idb.(*gorm.DB) + err = c.Bind(req) + tools.HasError(err, "参数验证失败", 422) + err = req.Validate() + tools.HasError(err, "参数验证失败", 422) + err = db.WithContext(c).Model(object). + Scopes(tools.MakeCondition(req.GetNeedSearch())). + Scopes(tools.Paginate(req.GetPageSize(), req.GetPageIndex())). + Find(list).Limit(-1).Offset(-1). + Count(&count).Error + if !errors.Is(err, gorm.ErrRecordNotFound) { + tools.HasError(err, "查询失败", 500) + } + default: + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功") + c.Next() + } +} diff --git a/apis/actions/update.go b/apis/actions/update.go new file mode 100644 index 0000000..0f5d44d --- /dev/null +++ b/apis/actions/update.go @@ -0,0 +1,39 @@ +package actions + +import ( + "errors" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-admin/tools" + "go-admin/tools/app" + "go-admin/tools/model" +) + +// UpdateAction 通用更新动作 +func UpdateAction(m model.ActiveRecord) gin.HandlerFunc { + return func(c *gin.Context) { + object := m.Generate() + var err error + idb, exist := c.Get("db") + if !exist { + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + switch idb.(type) { + case *gorm.DB: + //新增操作 + db := idb.(*gorm.DB) + err = c.Bind(object) + tools.HasError(err, "参数验证失败", 422) + err = db.WithContext(c).Updates(object).Error + tools.HasError(err, "更新失败", 500) + default: + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + app.OK(c, object.GetId(), "更新成功") + c.Next() + } +} diff --git a/apis/actions/view.go b/apis/actions/view.go new file mode 100644 index 0000000..5d98b51 --- /dev/null +++ b/apis/actions/view.go @@ -0,0 +1,40 @@ +package actions + +import ( + "errors" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-admin/tools" + "go-admin/tools/app" + "go-admin/tools/model" +) + +// ViewAction 通用详情动作 +func ViewAction(m model.ActiveRecord) gin.HandlerFunc { + return func(c *gin.Context) { + object := m.Generate() + var err error + idb, exist := c.Get("db") + if !exist { + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + switch idb.(type) { + case *gorm.DB: + //新增操作 + db := idb.(*gorm.DB) + var generalGetDto tools.GeneralGetDto + err = c.BindUri(&generalGetDto) + tools.HasError(err, "参数验证失败", 422) + err = db.WithContext(c).Where(generalGetDto.Id).First(object).Error + tools.HasError(err, "查看失败", 500) + default: + err = errors.New("db connect not exist") + tools.HasError(err, "", 500) + } + app.OK(c, object, "查看成功") + c.Next() + } +} diff --git a/dto/pagination.go b/dto/pagination.go new file mode 100644 index 0000000..37c2bc0 --- /dev/null +++ b/dto/pagination.go @@ -0,0 +1,6 @@ +package dto + +type Pagination struct { + PageIndex int `form:"pageIndex"` + PageSize int `form:"pageSize"` +} diff --git a/dto/sysjob.go b/dto/sysjob.go index 149ed54..d741475 100644 --- a/dto/sysjob.go +++ b/dto/sysjob.go @@ -1,6 +1,7 @@ package dto type SysJobSearch struct { + Pagination `search:"-"` JobId int `form:"jobId" search:"type:exact;column:job_id;table:sys_job"` JobName string `form:"jobName" search:"type:icontains;column:job_name;table:sys_job"` JobGroup string `form:"jobGroup" search:"type:exact;column:job_group;table:sys_job"` @@ -8,3 +9,24 @@ type SysJobSearch struct { InvokeTarget string `form:"invokeTarget" search:"type:exact;column:invoke_target;table:sys_job"` Status int `form:"status" search:"type:exact;column:status;table:sys_job"` } + +func (m *SysJobSearch) GetNeedSearch() interface{} { + return *m +} + +func (m *SysJobSearch) Validate() error { + return nil +} + +func (m *SysJobSearch) Generate() Dtor { + o := *m + return &o +} + +func (m *SysJobSearch) GetPageIndex() int { + return m.PageIndex +} + +func (m *SysJobSearch) GetPageSize() int { + return m.PageSize +} diff --git a/dto/type.go b/dto/type.go new file mode 100644 index 0000000..ba6fa63 --- /dev/null +++ b/dto/type.go @@ -0,0 +1,9 @@ +package dto + +type Dtor interface { + Validate() error + Generate() Dtor + GetPageIndex() int + GetPageSize() int + GetNeedSearch() interface{} +} diff --git a/go.mod b/go.mod index ebe51d7..d0f1955 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/unrolled/secure v1.0.8 go.uber.org/multierr v1.5.0 // indirect golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a + gopkg.in/ffmt.v1 v1.5.6 gorm.io/driver/mysql v0.3.2 gorm.io/driver/postgres v0.2.9 gorm.io/driver/sqlite v1.0.9 diff --git a/middleware/db.go b/middleware/db.go new file mode 100644 index 0000000..272ec3d --- /dev/null +++ b/middleware/db.go @@ -0,0 +1,17 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +func WithContextDb(dbMap map[string]*gorm.DB) gin.HandlerFunc { + return func(c *gin.Context) { + if db, ok := dbMap["*"]; ok { + c.Set("db", db) + } else { + c.Set("db", dbMap[c.Request.Host]) + } + c.Next() + } +} diff --git a/models/sysjob.go b/models/sysjob.go index 704ef74..5f9d1ca 100644 --- a/models/sysjob.go +++ b/models/sysjob.go @@ -3,6 +3,7 @@ package models import ( orm "go-admin/global" "go-admin/tools" + "go-admin/tools/model" ) type SysJob struct { @@ -27,6 +28,20 @@ func (SysJob) TableName() string { return "sys_job" } +func (e *SysJob) Generate() model.ActiveRecord { + o := *e + return &o +} + +func (e *SysJob) GenerateList() interface{} { + list := make([]SysJob, 0) + return &list +} + +func (e *SysJob) GetId() interface{} { + return e.JobId +} + // 创建SysJob func (e *SysJob) Create() (err error) { return orm.Eloquent.Table(e.TableName()).Create(e).Error diff --git a/router/initrouter.go b/router/initrouter.go index 87ec637..322e42f 100644 --- a/router/initrouter.go +++ b/router/initrouter.go @@ -8,6 +8,7 @@ import ( _ "go-admin/pkg/jwtauth" "go-admin/tools" config2 "go-admin/tools/config" + "gorm.io/gorm" ) func InitRouter() *gin.Engine { @@ -20,6 +21,7 @@ func InitRouter() *gin.Engine { if config2.SslConfig.Enable { r.Use(handler.TlsHandler()) } + r.Use(middleware.WithContextDb(map[string]*gorm.DB{"*": global.Eloquent})) middleware.InitMiddleware(r) // the jwt middleware authMiddleware, err := middleware.AuthInit() diff --git a/router/sysrouter.go b/router/sysrouter.go index e56f19a..f2b7104 100644 --- a/router/sysrouter.go +++ b/router/sysrouter.go @@ -1,6 +1,7 @@ package router import ( + "go-admin/apis/actions" log2 "go-admin/apis/log" "go-admin/apis/monitor" "go-admin/apis/public" @@ -9,8 +10,10 @@ import ( "go-admin/apis/system/dict" . "go-admin/apis/tools" _ "go-admin/docs" + "go-admin/dto" "go-admin/handler" "go-admin/middleware" + "go-admin/models" jwt "go-admin/pkg/jwtauth" "go-admin/pkg/ws" "mime" @@ -110,11 +113,18 @@ func registerSysJobRouter(v1 *gin.RouterGroup) { r := v1.Group("/sysjob") { - r.GET("", sysjob.GetSysJobList) - r.GET("/:id", sysjob.GetSysJob) - r.POST("", sysjob.InsertSysJob) - r.PUT("", sysjob.UpdateSysJob) - r.DELETE("/:id", sysjob.DeleteSysJob) + //r.GET("", sysjob.GetSysJobList) + //r.GET("/:id", sysjob.GetSysJob) + //r.POST("", sysjob.InsertSysJob) + //r.PUT("", sysjob.UpdateSysJob) + //r.DELETE("/:id", sysjob.DeleteSysJob) + + sysJob := &models.SysJob{} + r.GET("", actions.IndexAction(sysJob, new(dto.SysJobSearch))) + r.GET("/:id", actions.ViewAction(sysJob)) + r.POST("", actions.CreateAction(sysJob)) + r.PUT("", actions.UpdateAction(sysJob)) + r.DELETE("/:id", actions.DeleteAction(sysJob)) } v1.GET("/job/remove/:jobId", sysjob.RemoveJob) diff --git a/tools/dto.go b/tools/dto.go index 3f472ab..a50e561 100644 --- a/tools/dto.go +++ b/tools/dto.go @@ -1,6 +1,7 @@ package tools import ( + "github.com/google/uuid" "go-admin/tools/config" "github.com/matchstalk/go-admin-core/search" @@ -8,8 +9,30 @@ import ( ) type GeneralDelDto struct { - Id string `uri:"id" json:"id" validate:"required"` + Id string `uri:"id" json:"id" validate:"required"` + Ids []string `json:"ids"` } + +func (g GeneralDelDto) GetIds() []string { + ids := make([]string, 0) + if len(g.Ids) > 0 { + for _, id := range g.Ids { + if len(id) > 0 { + ids = append(ids, id) + } + } + } else { + if len(g.Id) > 0 { + ids = append(ids, g.Id) + } + } + if len(ids) <= 0 { + //方式全部删除 + ids = append(ids, uuid.New().String()) + } + return ids +} + type GeneralGetDto struct { Id string `uri:"id" json:"id" validate:"required"` } diff --git a/tools/model/type.go b/tools/model/type.go new file mode 100644 index 0000000..57f34d0 --- /dev/null +++ b/tools/model/type.go @@ -0,0 +1,10 @@ +package model + +import "gorm.io/gorm/schema" + +type ActiveRecord interface { + schema.Tabler + Generate() ActiveRecord + GetId() interface{} + GenerateList() interface{} +} From abc8b271c466d46a3e23fc7714d5fddc51905930 Mon Sep 17 00:00:00 2001 From: linwenxiang <991154416@qq.com> Date: Sun, 30 Aug 2020 00:21:03 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=9C=A8actions=E4=B8=AD=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apis/actions/index.go | 8 +++-- apis/actions/permission.go | 61 ++++++++++++++++++++++++++++++++++++++ models/role.go | 5 ++++ models/sysuser.go | 7 ++++- 4 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 apis/actions/permission.go diff --git a/apis/actions/index.go b/apis/actions/index.go index 5d070d0..637744e 100644 --- a/apis/actions/index.go +++ b/apis/actions/index.go @@ -33,9 +33,13 @@ func IndexAction(m model.ActiveRecord, d dto.Dtor) gin.HandlerFunc { tools.HasError(err, "参数验证失败", 422) err = req.Validate() tools.HasError(err, "参数验证失败", 422) + p, err := newDataPermission(db, tools.GetUserId(c)) err = db.WithContext(c).Model(object). - Scopes(tools.MakeCondition(req.GetNeedSearch())). - Scopes(tools.Paginate(req.GetPageSize(), req.GetPageIndex())). + Scopes( + tools.MakeCondition(req.GetNeedSearch()), + tools.Paginate(req.GetPageSize(), req.GetPageIndex()), + Permission(object.TableName(), p), + ). Find(list).Limit(-1).Offset(-1). Count(&count).Error if !errors.Is(err, gorm.ErrRecordNotFound) { diff --git a/apis/actions/permission.go b/apis/actions/permission.go new file mode 100644 index 0000000..7dc24f4 --- /dev/null +++ b/apis/actions/permission.go @@ -0,0 +1,61 @@ +package actions + +import ( + "errors" + "go-admin/models" + "go-admin/tools/config" + + "gorm.io/gorm" + + "go-admin/tools" +) + +type dataPermission struct { + DataScope string + UserId int + DeptId int + RoleId int +} + +func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error) { + var err error + p := &dataPermission{} + sysUser := new(models.SysUser) + sysRole := new(models.SysRole) + + err = sysUser.GetByUserId(tx, userId) + if err != nil { + err = errors.New("获取用户数据出错 msg:" + err.Error()) + return nil, err + } + p.UserId = sysUser.UserId + p.RoleId = sysUser.RoleId + p.DeptId = sysUser.DeptId + err = sysRole.GetById(tx, sysUser.RoleId) + if err != nil { + err = errors.New("获取用户数据出错 msg:" + err.Error()) + return nil, err + } + p.DataScope = sysRole.DataScope + return p, nil +} + +func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB { + return func(db *gorm.DB) *gorm.DB { + if !config.ApplicationConfig.EnableDP { + return db + } + switch p.DataScope { + case "2": + return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", p.RoleId) + case "3": + return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", p.DeptId) + case "4": + return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(p.DeptId)+"%") + case "5": + return db.Where(tableName+".create_by = ?", p.UserId) + default: + return db + } + } +} diff --git a/models/role.go b/models/role.go index 80d6c22..57703d9 100644 --- a/models/role.go +++ b/models/role.go @@ -2,6 +2,7 @@ package models import ( "github.com/pkg/errors" + "gorm.io/gorm" orm "go-admin/global" "go-admin/tools" @@ -33,6 +34,10 @@ type MenuIdList struct { MenuId int `json:"menuId"` } +func (role *SysRole) GetById(tx *gorm.DB, id interface{}) error { + return tx.First(role, id).Error +} + func (role *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error) { var doc []SysRole diff --git a/models/sysuser.go b/models/sysuser.go index e0baae3..5911959 100644 --- a/models/sysuser.go +++ b/models/sysuser.go @@ -2,6 +2,7 @@ package models import ( "errors" + "gorm.io/gorm" "log" "strings" @@ -224,7 +225,7 @@ func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, erro var count int64 - if err := table.Scopes(DataScopes(e.TableName(),userid)).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil { + if err := table.Scopes(DataScopes(e.TableName(), userid)).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil { return nil, 0, err } //table.Where("sys_user.deleted_at IS NULL").Count(&count) @@ -316,3 +317,7 @@ func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) { tools.HasError(err, "更新密码失败(代码202)", 500) return } + +func (e *SysUser) GetByUserId(tx *gorm.DB, id interface{}) error { + return tx.First(e, id).Error +} From b646ce9335214c70c210a21357f5492ddf675901 Mon Sep 17 00:00:00 2001 From: linwenxiang <991154416@qq.com> Date: Sun, 30 Aug 2020 00:22:21 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E5=9C=A8actions=E4=B8=AD=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apis/actions/index.go | 1 + 1 file changed, 1 insertion(+) diff --git a/apis/actions/index.go b/apis/actions/index.go index 637744e..bd0853e 100644 --- a/apis/actions/index.go +++ b/apis/actions/index.go @@ -34,6 +34,7 @@ func IndexAction(m model.ActiveRecord, d dto.Dtor) gin.HandlerFunc { err = req.Validate() tools.HasError(err, "参数验证失败", 422) p, err := newDataPermission(db, tools.GetUserId(c)) + tools.HasError(err, "权限范围鉴定错误", 500) err = db.WithContext(c).Model(object). Scopes( tools.MakeCondition(req.GetNeedSearch()),