feat: handle error in ApiFilter

This commit is contained in:
Yang Luo 2024-08-23 21:50:48 +08:00
parent 7d3920fb1f
commit 986dcbbda1
2 changed files with 25 additions and 12 deletions

View File

@ -56,7 +56,7 @@ func getSubject(ctx *context.Context) (string, string) {
return util.GetOwnerAndNameFromId(username)
}
func getObject(ctx *context.Context) (string, string) {
func getObject(ctx *context.Context) (string, string, error) {
method := ctx.Request.Method
path := ctx.Request.URL.Path
@ -65,13 +65,13 @@ func getObject(ctx *context.Context) (string, string) {
if ctx.Input.Query("id") == "/" {
adapterId := ctx.Input.Query("adapterId")
if adapterId != "" {
return util.GetOwnerAndNameFromIdNoCheck(adapterId)
return util.GetOwnerAndNameFromIdWithError(adapterId)
}
} else {
// query == "?id=built-in/admin"
id := ctx.Input.Query("id")
if id != "" {
return util.GetOwnerAndNameFromIdNoCheck(id)
return util.GetOwnerAndNameFromIdWithError(id)
}
}
}
@ -80,34 +80,33 @@ func getObject(ctx *context.Context) (string, string) {
// query == "?id=built-in/admin"
id := ctx.Input.Query("id")
if id != "" {
return util.GetOwnerAndNameFromIdNoCheck(id)
return util.GetOwnerAndNameFromIdWithError(id)
}
}
owner := ctx.Input.Query("owner")
if owner != "" {
return owner, ""
return owner, "", nil
}
return "", ""
return "", "", nil
} else {
if path == "/api/add-policy" || path == "/api/remove-policy" || path == "/api/update-policy" {
id := ctx.Input.Query("id")
if id != "" {
return util.GetOwnerAndNameFromIdNoCheck(id)
return util.GetOwnerAndNameFromIdWithError(id)
}
}
body := ctx.Input.RequestBody
if len(body) == 0 {
return ctx.Request.Form.Get("owner"), ctx.Request.Form.Get("name")
return ctx.Request.Form.Get("owner"), ctx.Request.Form.Get("name"), nil
}
var obj Object
err := json.Unmarshal(body, &obj)
if err != nil {
// panic(err)
return "", ""
return "", "", err
}
if path == "/api/delete-resource" {
@ -117,7 +116,7 @@ func getObject(ctx *context.Context) (string, string) {
}
}
return obj.Owner, obj.Name
return obj.Owner, obj.Name, nil
}
}
@ -183,7 +182,12 @@ func ApiFilter(ctx *context.Context) {
objOwner, objName := "", ""
if urlPath != "/api/get-app-login" && urlPath != "/api/get-resource" {
objOwner, objName = getObject(ctx)
var err error
objOwner, objName, err = getObject(ctx)
if err != nil {
responseError(ctx, err.Error())
return
}
}
if strings.HasPrefix(urlPath, "/api/notify-payment") {

View File

@ -131,6 +131,15 @@ func GetOwnerAndNameFromId(id string) (string, string) {
return tokens[0], tokens[1]
}
func GetOwnerAndNameFromIdWithError(id string) (string, string, error) {
tokens := strings.Split(id, "/")
if len(tokens) != 2 {
return "", "", errors.New("GetOwnerAndNameFromId() error, wrong token count for ID: " + id)
}
return tokens[0], tokens[1], nil
}
func GetOwnerFromId(id string) string {
tokens := strings.Split(id, "/")
if len(tokens) != 2 {