跳转到主要内容

函数

matcher 中的函数​

你可以在 matcher 中使用内置函数,也可以注册自定义函数。内置的键匹配函数形式如下:

bool function_name(string url, string pattern)

它们返回 url 是否匹配 pattern。

可用的内置函数:

FunctionurlpatternExample
keyMatch类似 /alice_data/resource1 的 URL 路径URL 路径,或类似 /alice_data/* 的 * 模式keymatch_model.conf/keymatch_policy.csv
keyMatch2类似 /alice_data/resource1 的 URL 路径URL 路径,或类似 /alice_data/:resource 的 : 模式keymatch2_model.conf/keymatch2_policy.csv
keyMatch3类似 /alice_data/resource1 的 URL 路径URL 路径,或类似 /alice_data/{resource} 的 {} 模式https://github.com/apache/casbin/blob/277c1a2b85698272f764d71a94d2595a8d425915/util/builtin_operators_test.go#L171-L196
keyMatch4类似 /alice_data/123/book/123 的 URL 路径URL 路径,或类似 /alice_data/{id}/book/{id} 的 {} 模式https://github.com/apache/casbin/blob/277c1a2b85698272f764d71a94d2595a8d425915/util/builtin_operators_test.go#L208-L222
keyMatch5类似 /alice_data/123/?status=1 的 URL 路径URL 路径,或类似 /alice_data/{id}/* 的 {} 或 * 模式https://github.com/apache/casbin/blob/1cde2646d10ad1190c0d784c3a1c0e1ace1b5bc9/util/builtin_operators_test.go#L485-L526
regexMatch任意字符串正则表达式模式keymatch_model.conf/keymatch_policy.csv
ipMatch类似 192.168.2.123 的 IP 地址IP 地址,或类似 192.168.2.0/24 的 CIDRipmatch_model.conf/ipmatch_policy.csv
globMatch类似 /alice_data/resource1 的路径型路径类似 /alice_data/* 的 glob 模式https://github.com/apache/casbin/blob/277c1a2b85698272f764d71a94d2595a8d425915/util/builtin_operators_test.go#L426-L466

键提取函数接受三个参数(keyGet 除外,它接受两个):

bool function_name(string url, string pattern, string key_name)

当 URL 匹配 pattern 时,它们返回指定键的值,否则返回 ""。

示例:

  • KeyGet2("/resource1/action", "/:res/action", "res") → "resource1"
  • KeyGet3("/resource1_admin/action", "/{res}_admin/*", "res") → "resource1"
  • KeyGet("/resource1/action", "/*") → "resource1/action" (双参数形式)
Functionurlpatternkey_nameexample
keyGet类似 /proj/resource1 的 URL 路径URL 路径,或类似 /proj/* 的 * 模式\keyget_model.conf/keymatch_policy.csv
keyGet2类似 /proj/resource1 的 URL 路径URL 路径,或类似 /proj/:resource 的 : 模式pattern 中指定的键名keyget2_model.conf/keymatch2_policy.csv
keyGet3类似 /proj/res3_admin/ 的 URL 路径URL 路径,或类似 /proj/{resource}_admin/* 的 {} 模式pattern 中指定的键名https://github.com/apache/casbin/blob/7bd496f94f5a2739a392d333a9aaaa10ae397673/util/builtin_operators_test.go#L209-L247

完整的函数说明:https://github.com/apache/casbin/blob/master/util/builtin_operators_test.go

添加自定义函数​

  1. 实现一个接受所需参数并返回 bool 的函数:

    func KeyMatch(key1 string, key2 string) bool {
    i := strings.Index(key2, "*")
    if i == -1 {
    return key1 == key2
    }

    if len(key1) > i {
    return key1[:i] == key2[:i]
    }
    return key1 == key2[:i]
    }
  2. 为 Casbin 封装它(签名为 func(...interface{}) (interface{}, error)):

    func KeyMatchFunc(args ...interface{}) (interface{}, error) {
    name1 := args[0].(string)
    name2 := args[1].(string)

    return (bool)(KeyMatch(name1, name2)), nil
    }
  3. 在 enforcer 上注册它:

    e.AddFunction("my_func", KeyMatchFunc)
  4. 在你的 model 中使用它:

    [matchers]
    m = r.sub == p.sub && my_func(r.obj, p.obj) && r.act == p.act