Functions
매처의 함수
Enhance matcher capabilities by incorporating functions. Use built-in functions or define custom ones. Built-in key-matching functions follow this signature:
bool function_name(string url, string pattern)
These functions return booleans indicating whether url matches pattern.
Available built-in functions:
Key-getting functions generally accept three parameters (except keyGet):
bool function_name(string url, string pattern, string key_name)
These return the key_name value when matching the pattern, otherwise returning "".
Examples: KeyGet2("/resource1/action", "/:res/action", "res") returns "resource1", while KeyGet3("/resource1_admin/action", "/{res}_admin/*", "res") returns "resource1".
For KeyGet with two parameters: KeyGet("/resource1/action", "/*") returns "resource1/action".
| 함수 | url | 패턴 | key_name | 예시 |
|---|---|---|---|---|
| keyGet | /proj/resource1과 같은 URL 경로 | /proj/*와 같은 URL 경로 또는 * 패턴 | \ | keyget_model.conf/keymatch_policy.csv |
| keyGet2 | /proj/resource1과 같은 URL 경로 | /prooj/:resource와 같은 URL 경로 또는 : 패턴 | 패턴에 지정된 키 이름 | keyget2_model.conf/keymatch2_policy.csv |
| keyGet3 | /proj/res3_admin/과 같은 URL 경로 | /proj/{resource}_admin/*와 같은 URL 경로 또는 {} 패턴 | 패턴에 지정된 키 이름 | https://github.com/casbin/casbin/blob/7bd496f94f5a2739a392d333a9aaaa10ae397673/util/builtin_operators_test.go#L209-L247 |
Complete function details: https://github.com/casbin/casbin/blob/master/util/builtin_operators_test.go
사용자 정의 함수 추가 방법
Start by creating your function, accepting multiple parameters and returning a 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]
}
Next, create an interface{} wrapper:
func KeyMatchFunc(args ...interface{}) (interface{}, error) {
name1 := args[0].(string)
name2 := args[1].(string)
return (bool)(KeyMatch(name1, name2)), nil
}
Register the function with the Casbin enforcer:
e.AddFunction("my_func", KeyMatchFunc)
Use the function in your model CONF:
[matchers]
m = r.sub == p.sub && my_func(r.obj, p.obj) && r.act == p.act