From 7b0b426a76fd77b89817e0eafcccaed8d15b8cf4 Mon Sep 17 00:00:00 2001 From: Yixiang Zhao Date: Wed, 24 Aug 2022 17:21:05 +0800 Subject: [PATCH] feat: check model grammar when saving and provide a ACL model as init data (#1062) Signed-off-by: Yixiang Zhao Signed-off-by: Yixiang Zhao --- object/init.go | 29 +++++++++++++++++++++++++++++ object/model.go | 11 +++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/object/init.go b/object/init.go index 68a8695a..07fb320e 100644 --- a/object/init.go +++ b/object/init.go @@ -27,6 +27,7 @@ import ( func InitDb() { existed := initBuiltInOrganization() if !existed { + initBuiltInModel() initBuiltInPermission() initBuiltInProvider() initBuiltInUser() @@ -239,6 +240,33 @@ func initWebAuthn() { gob.Register(webauthn.SessionData{}) } +func initBuiltInModel() { + model := GetModel("built-in/model-built-in") + if model != nil { + return + } + + model = &Model{ + Owner: "built-in", + Name: "model-built-in", + CreatedTime: util.GetCurrentTime(), + DisplayName: "Built-in Model", + IsEnabled: true, + ModelText: `[request_definition] +r = sub, obj, act + +[policy_definition] +p = sub, obj, act + +[policy_effect] +e = some(where (p.eft == allow)) + +[matchers] +m = r.sub == p.sub && r.obj == p.obj && r.act == p.act`, + } + AddModel(model) +} + func initBuiltInPermission() { permission := GetPermission("built-in/permission-built-in") if permission != nil { @@ -253,6 +281,7 @@ func initBuiltInPermission() { Users: []string{"built-in/admin"}, Roles: []string{}, Domains: []string{}, + Model: "model-built-in", ResourceType: "Application", Resources: []string{"app-built-in"}, Actions: []string{"Read", "Write", "Admin"}, diff --git a/object/model.go b/object/model.go index b04872fc..9b03b46a 100644 --- a/object/model.go +++ b/object/model.go @@ -17,6 +17,7 @@ package object import ( "fmt" + "github.com/casbin/casbin/v2/model" "github.com/casdoor/casdoor/util" "xorm.io/core" ) @@ -85,13 +86,19 @@ func GetModel(id string) *Model { return getModel(owner, name) } -func UpdateModel(id string, model *Model) bool { +func UpdateModel(id string, modelObj *Model) bool { owner, name := util.GetOwnerAndNameFromId(id) if getModel(owner, name) == nil { return false } - affected, err := adapter.Engine.ID(core.PK{owner, name}).AllCols().Update(model) + // check model grammar + _, err := model.NewModelFromString(modelObj.ModelText) + if err != nil { + panic(err) + } + + affected, err := adapter.Engine.ID(core.PK{owner, name}).AllCols().Update(modelObj) if err != nil { panic(err) }