From 61b40fef55071a55896b1bfbd82db23672cb1a4a Mon Sep 17 00:00:00 2001 From: what Date: Sun, 23 Apr 2023 17:17:12 +0800 Subject: [PATCH] =?UTF-8?q?[fix]=20WithRolesCondition=20sql=20=E6=8B=BC?= =?UTF-8?q?=E6=8E=A5=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/resource.go | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/base/resource.go b/base/resource.go index d2d383d..116f93a 100644 --- a/base/resource.go +++ b/base/resource.go @@ -144,7 +144,16 @@ func (this Resource) GetDBDriver() string { } func (this Resource) GetAuthDBTable(u contracts.User, params ...any) *db.Builder { - return this.GetDBTable(append(params, u)...) + builder := this.GetDBTable(append(params, u)...) + + // 数据权限过滤 + builder.Before(func(b *db.Builder, t string, data ...map[string]any) { + if t == db.TYPE_SELECT || t == db.TYPE_UPDATE || t == db.TYPE_DELETE { + this.WithRolesCondition(b, t, u.Roles()...) + } + }) + + return builder } // GetDBTable("Test", contracts.User) @@ -180,8 +189,6 @@ func (this Resource) GetDBTable(params ...any) *db.Builder { // 填充保存数据 this.fillSaveValue(data[i], user, db.TYPE_INSERT) } - } else if user != nil { - this.WithRolesCondition(b, t, user.Roles()...) } }) @@ -255,7 +262,7 @@ func (this Resource) WithRolesCondition(b *db.Builder, t string, roles ...string isFullRight = true return db.ToSql() } else if conditions.IsNotEmpty() { - db.WhereRaw(string(conditions.ToSql(nil))) + db.Where(conditions.ToSql(nil)) // 如果前面是无权限的sql查看, 这直接返回本次查询 if isFullNot { @@ -268,23 +275,24 @@ func (this Resource) WithRolesCondition(b *db.Builder, t string, roles ...string carry += " UNION " } - carry += db.ToSql() - - return carry + return fmt.Sprintf("%s(%s)", carry, db.ToSql()) }, "") if isFullRight { return nil } - // select, delete, update if isFullNot { b.WhereRaw("false") } else if subTables != "" { if t == db.TYPE_SELECT { - b.Table(subTables, b.TableAlias) + b.FromSub(subTables, b.TableAlias) } else { - b.WhereRaw(fmt.Sprintf("id in (SELECT temp.id FROM (%s) as temp)", subTables)) + b.WhereRaw(fmt.Sprintf( + "`%s`.`id` in (SELECT `temp`.`id` FROM (%s) as `temp`)", + lo.Ternary(b.TableAlias != "", b.TableAlias, this.GetCode()), + subTables, + )) } }