### Casbin Go Installation Source: https://github.com/apache/casbin/blob/master/README.md The command to install the Casbin Go library using the go get command. ```go go get github.com/casbin/casbin/v3 ``` -------------------------------- ### ACL Policy Example Source: https://github.com/apache/casbin/blob/master/README.md An example policy for the ACL model, illustrating how to define permissions for subjects on objects with specific actions. ```plaintext p, alice, data1, read p, bob, data2, write ``` -------------------------------- ### Get Implicit Roles for User in Go Source: https://context7.com/apache/casbin/llms.txt Demonstrates how to retrieve all roles for a user, including those inherited through a role hierarchy, using GetImplicitRolesForUser. This is useful for understanding a user's full set of privileges. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") // Add role hierarchy: alice -> admin -> superadmin e.AddRoleForUser("alice", "admin") e.AddRoleForUser("admin", "superadmin") // GetRolesForUser only returns direct roles directRoles, _ := e.GetRolesForUser("alice") fmt.Printf("Alice's direct roles: %v\n", directRoles) // [admin data2_admin] // GetImplicitRolesForUser returns all inherited roles implicitRoles, _ := e.GetImplicitRolesForUser("alice") fmt.Printf("Alice's implicit roles: %v\n", implicitRoles) // [admin data2_admin superadmin] // Add permissions for superadmin e.AddPolicy("superadmin", "all_data", "manage") // GetImplicitPermissionsForUser returns all permissions including inherited ones permissions, _ := e.GetImplicitPermissionsForUser("alice") fmt.Println("Alice's implicit permissions:") for _, p := range permissions { fmt.Printf(" %v\n", p) } // Output includes permissions from alice, admin, and superadmin roles } ``` -------------------------------- ### Get User Roles at Runtime Source: https://github.com/apache/casbin/blob/master/README.md Retrieve all roles implicitly assigned to a user at runtime. This is useful for dynamic permission management. ```go roles, _ := e.GetImplicitRolesForUser(sub) ``` -------------------------------- ### ABAC Model with 'in' Operator Source: https://github.com/apache/casbin/blob/master/README.md An example of using the 'in' operator within the matchers for an ABAC (Attribute-Based Access Control) model in the Casbin Go edition. Ensure the array length is greater than 1 to avoid panics. ```ini # Matchers [matchers] m = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3') ``` -------------------------------- ### RBAC with Domains in Go Source: https://context7.com/apache/casbin/llms.txt Illustrates multi-tenant RBAC using Casbin, where users can have different roles and permissions across various domains. It covers adding roles in domains, checking access, and retrieving domain-specific information. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { // Model with domains: r = sub, dom, obj, act // g = _, _, _ e, _ := casbin.NewEnforcer("examples/rbac_with_domains_model.conf", "examples/rbac_with_domains_policy.csv") // Add role for user in specific domain added, _ := e.AddRoleForUserInDomain("alice", "admin", "domain1") fmt.Printf("Role added in domain1: %v\n", added) // Add policy for admin in domain1 e.AddPolicy("admin", "domain1", "data1", "read") e.AddPolicy("admin", "domain1", "data1", "write") // Check access - alice is admin in domain1 allowed, _ := e.Enforce("alice", "domain1", "data1", "read") fmt.Printf("alice can read data1 in domain1: %v\n", allowed) // true // alice is not admin in domain2 allowed, _ = e.Enforce("alice", "domain2", "data1", "read") fmt.Printf("alice can read data1 in domain2: %v\n", allowed) // false // Get roles for user in specific domain roles := e.GetRolesForUserInDomain("alice", "domain1") fmt.Printf("Alice's roles in domain1: %v\n", roles) // [admin] // Get all users in a domain users, _ := e.GetAllUsersByDomain("domain1") fmt.Printf("Users in domain1: %v\n", users) // Get all domains domains, _ := e.GetAllDomains() fmt.Printf("All domains: %v\n", domains) // Delete role for user in domain deleted, _ := e.DeleteRoleForUserInDomain("alice", "admin", "domain1") fmt.Printf("Role deleted from domain1: %v\n", deleted) } ``` -------------------------------- ### Retrieve Policies and Subjects in Go Source: https://context7.com/apache/casbin/llms.txt Shows how to fetch all policies, filter them, and extract unique subjects, objects, or actions from the policy store. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") // Get all policies policies, err := e.GetPolicy() if err != nil { fmt.Printf("Error getting policies: %v\n", err) return } fmt.Println("All policies:") for _, p := range policies { fmt.Printf(" %v\n", p) } // Output: // [alice data1 read] // [bob data2 write] // [data2_admin data2 read] // [data2_admin data2 write] // Get filtered policies - all policies for alice (subject at index 0) filtered, _ := e.GetFilteredPolicy(0, "alice") fmt.Println("\nPolicies for alice:") for _, p := range filtered { fmt.Printf(" %v\n", p) } // Get all subjects in policy subjects, _ := e.GetAllSubjects() fmt.Printf("\nAll subjects: %v\n", subjects) // [alice bob data2_admin] // Get all objects in policy objects, _ := e.GetAllObjects() fmt.Printf("All objects: %v\n", objects) // [data1 data2] // Get all actions in policy actions, _ := e.GetAllActions() fmt.Printf("All actions: %v\n", actions) // [read write] } ``` -------------------------------- ### Manage Policies with Enforcer API Source: https://context7.com/apache/casbin/llms.txt Demonstrates enabling auto-save, manual policy persistence, reloading, and clearing policies in memory. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Enable auto-save (automatically saves after each policy change) e.EnableAutoSave(true) // Add a new policy - will be automatically saved if auto-save is enabled e.AddPolicy("newuser", "newdata", "read") // Or manually save all policies e.EnableAutoSave(false) // Disable auto-save e.AddPolicy("anotheruser", "anotherdata", "write") e.AddPolicy("anotheruser", "anotherdata", "read") // Save all changes at once err := e.SavePolicy() if err != nil { fmt.Printf("Error saving policy: %v\n", err) return } fmt.Println("Policy saved successfully") // Reload policy from file/database err = e.LoadPolicy() if err != nil { fmt.Printf("Error loading policy: %v\n", err) return } fmt.Println("Policy reloaded successfully") // Clear all policy in memory e.ClearPolicy() policies, _ := e.GetPolicy() fmt.Printf("Policies after clear: %d\n", len(policies)) // 0 } ``` -------------------------------- ### Initialize Casbin Enforcer Source: https://github.com/apache/casbin/blob/master/README.md Create a new Casbin enforcer instance using a model configuration file and a policy file. Ensure the paths to these files are correct. ```go e, _ := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv") ``` -------------------------------- ### Adding Custom Matching Functions in Casbin Source: https://context7.com/apache/casbin/llms.txt Demonstrates how to add a custom matching function to Casbin using `AddFunction`. This allows for complex authorization logic beyond built-in capabilities, such as prefix matching for object resources. ```go package main import ( "fmt" "strings" "github.com/casbin/casbin/v3" "github.com/casbin/casbin/v3/model" ) func main() { // Create model from string 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 && myCustomFunc(r.obj, p.obj) && r.act == p.act ` m, _ := model.NewModelFromString(modelText) e, _ := casbin.NewEnforcer(m, "examples/basic_policy.csv") // Add a custom function - checks if request object starts with policy object customFunc := func(args ...interface{}) (interface{}, error) { requestObj := args[0].(string) policyObj := args[1].(string) return strings.HasPrefix(requestObj, policyObj), nil } e.AddFunction("myCustomFunc", customFunc) // Update policy to use prefix matching e.RemovePolicy("alice", "data1", "read") e.AddPolicy("alice", "data", "read") // alice can read anything starting with "data" // Test the custom function allowed, _ := e.Enforce("alice", "data1", "read") fmt.Printf("alice can read data1: %v\n", allowed) // true allowed, _ = e.Enforce("alice", "data999", "read") fmt.Printf("alice can read data999: %v\n", allowed) // true allowed, _ = e.Enforce("alice", "other", "read") fmt.Printf("alice can read other: %v\n", allowed) // false } ``` -------------------------------- ### Manage User Permissions in Go Source: https://context7.com/apache/casbin/llms.txt Shows how to add, retrieve, and delete permissions for a user using Casbin's AddPermissionForUser, GetPermissionsForUser, and DeletePermissionForUser methods. It also demonstrates checking for specific permissions with HasPermissionForUser. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") // Add permission directly to a user added, err := e.AddPermissionForUser("eve", "data5", "read") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Permission added: %v\n", added) // true // Add multiple permissions at once permissions := [][]string{ {"data5", "write"}, {"data6", "read"}, } added, _ = e.AddPermissionsForUser("eve", permissions...) fmt.Printf("Multiple permissions added: %v\n", added) // Get direct permissions for a user perms, _ := e.GetPermissionsForUser("eve") fmt.Println("Eve's direct permissions:") for _, p := range perms { fmt.Printf(" %v\n", p) } // Check if user has a specific permission hasPerm, _ := e.HasPermissionForUser("eve", "data5", "read") fmt.Printf("Eve has read permission on data5: %v\n", hasPerm) // true // Delete a specific permission deleted, _ := e.DeletePermissionForUser("eve", "data5", "read") fmt.Printf("Permission deleted: %v\n", deleted) // true // Delete all permissions for a user deleted, _ = e.DeletePermissionsForUser("eve") fmt.Printf("All permissions deleted: %v\n", deleted) } ``` -------------------------------- ### ACL Model with Multi-line Matchers Source: https://github.com/apache/casbin/blob/master/README.md Demonstrates how to use multi-line syntax in the matchers section of the Casbin model configuration by appending '\' to continue the line. ```ini # Matchers [matchers] m = r.sub == p.sub && r.obj == p.obj \ && r.act == p.act ``` -------------------------------- ### Enforcement with Explanation using EnforceEx Source: https://context7.com/apache/casbin/llms.txt EnforceEx provides the enforcement decision along with the specific policy rule that was matched. This is invaluable for debugging and understanding access control logic, especially with complex RBAC or ABAC models. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") // EnforceEx returns the decision and the matched rule allowed, matchedRule, err := e.EnforceEx("alice", "data1", "read") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Allowed: %v\n", allowed) // Output: true fmt.Printf("Matched rule: %v\n", matchedRule) // Output: [alice data1 read] // Check access through role inheritance // Policy: g, alice, data2_admin // p, data2_admin, data2, read allowed, matchedRule, _ = e.EnforceEx("alice", "data2", "read") fmt.Printf("Allowed: %v\n", allowed) // Output: true fmt.Printf("Matched rule: %v\n", matchedRule) // Output: [data2_admin data2 read] } ``` -------------------------------- ### Casbin Built-in Matching Functions in Go Source: https://context7.com/apache/casbin/llms.txt Demonstrates various built-in Casbin utility functions for pattern matching, including KeyMatch, KeyMatch2, KeyMatch3, KeyMatch4, KeyMatch5, RegexMatch, IPMatch, and GlobMatch. These functions are useful for matching URLs, RESTful paths, and IP addresses. ```go package main import ( "fmt" "github.com/casbin/casbin/v3/util" ) func main() { // KeyMatch - simple wildcard matching with * fmt.Println("KeyMatch examples:") fmt.Printf(" /foo/bar matches /foo/*: %v\n", util.KeyMatch("/foo/bar", "/foo/*")) // true fmt.Printf(" /foo/bar matches /foo: %v\n", util.KeyMatch("/foo/bar", "/foo")) // false // KeyMatch2 - RESTful path matching with :param fmt.Println("\nKeyMatch2 examples:") fmt.Printf(" /foo/bar matches /foo/*: %v\n", util.KeyMatch2("/foo/bar", "/foo/*")) // true fmt.Printf(" /resource1 matches /:resource: %v\n", util.KeyMatch2("/resource1", "/:resource")) // true // KeyMatch3 - RESTful path matching with {param} fmt.Println("\nKeyMatch3 examples:") fmt.Printf(" /resource1 matches /{resource}: %v\n", util.KeyMatch3("/resource1", "/{resource}")) // true // KeyMatch4 - like KeyMatch3 but enforces consistent parameter values fmt.Println("\nKeyMatch4 examples:") fmt.Printf(" /parent/123/child/123 matches /parent/{id}/child/{id}: %v\n", util.KeyMatch4("/parent/123/child/123", "/parent/{id}/child/{id}")) // true (same id) fmt.Printf(" /parent/123/child/456 matches /parent/{id}/child/{id}: %v\n", util.KeyMatch4("/parent/123/child/456", "/parent/{id}/child/{id}")) // false (different ids) // KeyMatch5 - strips query parameters before matching fmt.Println("\nKeyMatch5 examples:") fmt.Printf(" /foo/bar?status=1 matches /foo/bar: %v\n", util.KeyMatch5("/foo/bar?status=1&type=2", "/foo/bar")) // true // RegexMatch - regular expression matching fmt.Println("\nRegexMatch examples:") fmt.Printf(" /topic/create matches /topic/.*: %v\n", util.RegexMatch("/topic/create", "/topic/.*")) // true // IPMatch - IP address and CIDR matching fmt.Println("\nIPMatch examples:") fmt.Printf(" 192.168.2.123 matches 192.168.2.0/24: %v\n", util.IPMatch("192.168.2.123", "192.168.2.0/24")) // true fmt.Printf(" 192.168.3.123 matches 192.168.2.0/24: %v\n", util.IPMatch("192.168.3.123", "192.168.2.0/24")) // false // GlobMatch - glob pattern matching fmt.Println("\nGlobMatch examples:") result, _ := util.GlobMatch("/foo/bar", "/foo/*") fmt.Printf(" /foo/bar matches /foo/*: %v\n", result) // true } ``` -------------------------------- ### Create Casbin Enforcer from Files Source: https://context7.com/apache/casbin/llms.txt Use NewEnforcer to create an enforcer by providing paths to the model configuration and policy files. Alternatively, a database adapter can be used for policy storage. ```go package main import ( "fmt" "log" "github.com/casbin/casbin/v3" ) func main() { // Create enforcer from model and policy files e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv") if err != nil { log.Fatalf("Failed to create enforcer: %v", err) } // Or create with a database adapter // a := mysqladapter.NewDBAdapter("mysql", "user:password@tcp(127.0.0.1:3306)/") // e, err := casbin.NewEnforcer("path/to/model.conf", a) // Check if alice can read data1 allowed, err := e.Enforce("alice", "data1", "read") if err != nil { log.Fatalf("Enforcement error: %v", err) } if allowed { fmt.Println("Access granted: alice can read data1") } else { fmt.Println("Access denied: alice cannot read data1") } } ``` -------------------------------- ### Remove Authorization Policies in Go Source: https://context7.com/apache/casbin/llms.txt Demonstrates removing individual policies, filtering policies by field, and batch removing multiple policies. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Check initial access allowed, _ := e.Enforce("alice", "data1", "read") fmt.Printf("Before removal - alice can read data1: %v\n", allowed) // true // Remove a specific policy removed, err := e.RemovePolicy("alice", "data1", "read") if err != nil { fmt.Printf("Error removing policy: %v\n", err) return } fmt.Printf("Policy removed: %v\n", removed) // true // Check access after removal allowed, _ = e.Enforce("alice", "data1", "read") fmt.Printf("After removal - alice can read data1: %v\n", allowed) // false // Remove policies by filter - remove all policies for a specific subject removed, _ = e.RemoveFilteredPolicy(0, "bob") // field index 0 = subject fmt.Printf("Filtered policies removed: %v\n", removed) // Remove multiple specific policies rules := [][]string{ {"alice", "data2", "read"}, {"alice", "data2", "write"}, } e.AddPolicies(rules) // First add them removed, _ = e.RemovePolicies(rules) fmt.Printf("Multiple policies removed: %v\n", removed) } ``` -------------------------------- ### Adding Policies with AddPolicy and AddPolicies Source: https://context7.com/apache/casbin/llms.txt Dynamically add authorization rules using AddPolicy for a single rule or AddPolicies for multiple rules. Returns true if added, false if the rule already exists. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Check initial access - should be denied allowed, _ := e.Enforce("charlie", "data3", "read") fmt.Printf("Before AddPolicy - charlie can read data3: %v\n", allowed) // false // Add a new policy rule added, err := e.AddPolicy("charlie", "data3", "read") if err != nil { fmt.Printf("Error adding policy: %v\n", err) return } fmt.Printf("Policy added: %v\n", added) // true // Now check access - should be allowed allowed, _ = e.Enforce("charlie", "data3", "read") fmt.Printf("After AddPolicy - charlie can read data3: %v\n", allowed) // true // Try adding duplicate - should return false added, _ = e.AddPolicy("charlie", "data3", "read") fmt.Printf("Duplicate policy added: %v\n", added) // false // Add multiple policies at once rules := [][]string{ {"david", "data4", "read"}, {"david", "data4", "write"}, } added, _ = e.AddPolicies(rules) fmt.Printf("Multiple policies added: %v\n", added) // true } ``` -------------------------------- ### Basic Enforcement Check with Enforce Source: https://context7.com/apache/casbin/llms.txt The Enforce method checks if a subject has permission to perform an action on an object based on loaded policies. Ensure the model and policy files are correctly configured. ```go package main import ( "fmt" "log" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Basic enforcement check // Policy file contains: p, alice, data1, read // p, bob, data2, write sub := "alice" // the user that wants to access a resource obj := "data1" // the resource that is going to be accessed act := "read" // the operation that the user performs on the resource allowed, err := e.Enforce(sub, obj, act) if err != nil { log.Fatalf("Error during enforcement: %v", err) } if allowed { fmt.Printf("%s is allowed to %s %s\n", sub, act, obj) // Output: alice is allowed to read data1 } else { fmt.Printf("%s is denied to %s %s\n", sub, act, obj) } // Check bob's access - should be denied for read allowed, _ = e.Enforce("bob", "data1", "read") fmt.Printf("bob can read data1: %v\n", allowed) // Output: false // Check bob's write access to data2 - should be allowed allowed, _ = e.Enforce("bob", "data2", "write") fmt.Printf("bob can write data2: %v\n", allowed) // Output: true } ``` -------------------------------- ### Thread-Safe Enforcement with SyncedEnforcer Source: https://context7.com/apache/casbin/llms.txt Use SyncedEnforcer for concurrent environments requiring thread-safe access and automatic policy reloading. ```go package main import ( "fmt" "sync" "time" "github.com/casbin/casbin/v3" ) func main() { // Create a synchronized enforcer for concurrent access e, err := casbin.NewSyncedEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") if err != nil { fmt.Printf("Error: %v\n", err) return } // Start automatic policy reload every 30 seconds e.StartAutoLoadPolicy(30 * time.Second) // Safe for concurrent use var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(id int) { defer wg.Done() allowed, _ := e.Enforce("alice", "data1", "read") fmt.Printf("Goroutine %d: alice can read data1: %v\n", id, allowed) }(i) } wg.Wait() // Check if auto-loading is running fmt.Printf("Auto-loading running: %v\n", e.IsAutoLoadingRunning()) // Stop automatic policy reload e.StopAutoLoadPolicy() fmt.Printf("Auto-loading stopped: %v\n", !e.IsAutoLoadingRunning()) } ``` -------------------------------- ### Define Access Control Models Source: https://context7.com/apache/casbin/llms.txt Common PERM model configurations for ACL, RBAC, and RBAC with domains. ```ini # Basic ACL Model (examples/basic_model.conf) [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 ``` ```ini # RBAC Model (examples/rbac_model.conf) [request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act ``` ```ini # RBAC with Domains/Tenants (examples/rbac_with_domains_model.conf) [request_definition] r = sub, dom, obj, act [policy_definition] p = sub, dom, obj, act [role_definition] g = _, _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act ``` -------------------------------- ### Manage RBAC Roles in Go Source: https://context7.com/apache/casbin/llms.txt Covers assigning, querying, and removing roles for users within an RBAC-enabled Casbin model. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") // Add a role for a user added, err := e.AddRoleForUser("bob", "data2_admin") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Role added: %v\n", added) // true // Now bob has data2_admin role and can access data2 allowed, _ := e.Enforce("bob", "data2", "read") fmt.Printf("bob can read data2: %v\n", allowed) // true // Get all roles for a user roles, _ := e.GetRolesForUser("alice") fmt.Printf("Alice's roles: %v\n", roles) // [data2_admin] // Get all users who have a specific role users, _ := e.GetUsersForRole("data2_admin") fmt.Printf("Users with data2_admin role: %v\n", users) // [alice bob] // Check if a user has a specific role hasRole, _ := e.HasRoleForUser("alice", "data2_admin") fmt.Printf("Alice has data2_admin role: %v\n", hasRole) // true // Delete a role from a user deleted, _ := e.DeleteRoleForUser("bob", "data2_admin") fmt.Printf("Role deleted: %v\n", deleted) // true // Verify bob no longer has access allowed, _ = e.Enforce("bob", "data2", "read") fmt.Printf("After role removal - bob can read data2: %v\n", allowed) // false } ``` -------------------------------- ### Batch Enforcement with BatchEnforce Source: https://context7.com/apache/casbin/llms.txt Use BatchEnforce to process multiple authorization requests simultaneously for improved efficiency. Ensure the requests are formatted as a slice of slices of interfaces. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Define multiple requests to check at once requests := [][]interface{}{ {"alice", "data1", "read"}, // allowed {"alice", "data1", "write"}, // denied {"bob", "data2", "write"}, // allowed {"bob", "data1", "read"}, // denied } results, err := e.BatchEnforce(requests) if err != nil { fmt.Printf("Batch enforcement error: %v\n", err) return } for i, result := range results { req := requests[i] fmt.Printf("Request %v: %v\n", req, result) } // Output: // Request [alice data1 read]: true // Request [alice data1 write]: false // Request [bob data2 write]: true // Request [bob data1 read]: false } ``` -------------------------------- ### Define Policy Rules in CSV Source: https://context7.com/apache/casbin/llms.txt Format for defining policy rules, role assignments, and domain-based permissions in CSV files. ```csv # Basic policy format # p = policy rules, g = grouping/role rules # Policy rules: p, subject, object, action p, alice, data1, read p, bob, data2, write p, data2_admin, data2, read p, data2_admin, data2, write # Role assignment: g, user, role g, alice, data2_admin # With domains: g, user, role, domain g, alice, admin, domain1 g, bob, user, domain2 # Policy with domains: p, subject, domain, object, action p, admin, domain1, data1, read p, admin, domain1, data1, write ``` -------------------------------- ### Custom Matcher with EnforceWithMatcher Source: https://context7.com/apache/casbin/llms.txt Employ EnforceWithMatcher to apply a dynamic matching expression, overriding the model's default matcher. This is useful for conditional authorization logic. ```go package main import ( "fmt" "github.com/casbin/casbin/v3" ) func main() { e, _ := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") // Use a custom matcher that ignores the action // This checks if the subject and object match, regardless of action customMatcher := "r.sub == p.sub && r.obj == p.obj" // alice has "read" permission on data1, but we're checking "write" // With custom matcher that ignores action, this should be allowed allowed, err := e.EnforceWithMatcher(customMatcher, "alice", "data1", "write") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Custom matcher result: %v\n", allowed) // Output: true // Normal enforcement would deny this normalAllowed, _ := e.Enforce("alice", "data1", "write") fmt.Printf("Normal enforcement result: %v\n", normalAllowed) // Output: false } ``` -------------------------------- ### Cached Enforcement with CachedEnforcer Source: https://context7.com/apache/casbin/llms.txt Use CachedEnforcer to improve performance by caching repeated enforcement decisions. ```go package main import ( "fmt" "time" "github.com/casbin/casbin/v3" ) func main() { // Create a cached enforcer e, err := casbin.NewCachedEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") if err != nil { fmt.Printf("Error: %v\n", err) return } // Set cache expiration time e.SetExpireTime(time.Hour) // First call - not cached start := time.Now() allowed, _ := e.Enforce("alice", "data1", "read") fmt.Printf("First call (not cached): %v, time: %v\n", allowed, time.Since(start)) // Second call - cached result returned start = time.Now() allowed, _ = e.Enforce("alice", "data1", "read") fmt.Printf("Second call (cached): %v, time: %v\n", allowed, time.Since(start)) // Disable caching temporarily e.EnableCache(false) allowed, _ = e.Enforce("alice", "data1", "read") fmt.Printf("Cache disabled: %v\n", allowed) // Re-enable caching e.EnableCache(true) // Invalidate all cached decisions err = e.InvalidateCache() if err != nil { fmt.Printf("Error invalidating cache: %v\n", err) } fmt.Println("Cache invalidated") } ``` -------------------------------- ### ACL Model Configuration Source: https://github.com/apache/casbin/blob/master/README.md This INI configuration defines the basic Access Control List (ACL) model for Casbin, specifying the request, policy, and effect definitions, along with the matching logic. ```ini # Request definition [request_definition] r = sub, obj, act # Policy definition [policy_definition] p = sub, obj, act # Policy effect [policy_effect] e = some(where (p.eft == allow)) # Matchers [matchers] m = r.sub == p.sub && r.obj == p.obj && r.act == p.act ``` -------------------------------- ### Custom Matcher with EnforceWithMatcher Source: https://context7.com/apache/casbin/llms.txt The `EnforceWithMatcher` method allows using a custom matcher expression instead of the one defined in the model. This enables dynamic authorization logic without changing the model configuration. ```APIDOC ## EnforceWithMatcher ### Description Allows using a custom matcher expression instead of the one defined in the model, enabling dynamic authorization logic. ### Method `EnforceWithMatcher` ### Parameters #### Path Parameters - **matcher** (string) - Required - The custom matcher expression. - **sub** (string) - Required - The subject of the request. - **obj** (string) - Required - The object of the request. - **act** (string) - Required - The action of the request. ### Request Example ```json { "matcher": "r.sub == p.sub && r.obj == p.obj", "sub": "alice", "obj": "data1", "act": "write" } ``` ### Response #### Success Response (200) - **allowed** (bool) - True if the request is allowed according to the custom matcher, false otherwise. - **err** (error) - An error object if any occurred during enforcement. #### Response Example ```json { "allowed": true, "err": null } ``` ``` -------------------------------- ### Adding Policies with AddPolicy Source: https://context7.com/apache/casbin/llms.txt The `AddPolicy` method adds an authorization rule to the current policy at runtime. It returns false if the rule already exists and true if the rule was successfully added. `AddPolicies` adds multiple rules at once. ```APIDOC ## AddPolicy / AddPolicies ### Description Adds an authorization rule to the current policy at runtime. `AddPolicies` adds multiple rules at once. ### Method `AddPolicy`, `AddPolicies` ### Parameters #### AddPolicy - **sec** (string) - Required - The section of the policy (e.g., "p"). - **ptype** (string) - Required - The type of the policy rule (e.g., "policy"). - **rule** ([]string) - Required - A slice of strings representing the policy rule (e.g., subject, object, action). #### AddPolicies - **sec** (string) - Required - The section of the policy (e.g., "p"). - **ptype** (string) - Required - The type of the policy rule (e.g., "policy"). - **rules** ([][]string) - Required - A slice of policy rules to add. ### Request Example (AddPolicy) ```json { "sec": "p", "ptype": "policy", "rule": ["charlie", "data3", "read"] } ``` ### Request Example (AddPolicies) ```json { "sec": "p", "ptype": "policy", "rules": [ ["david", "data4", "read"], ["david", "data4", "write"] ] } ``` ### Response #### Success Response (200) - **added** (bool) - True if the rule(s) were successfully added, false if they already existed. - **err** (error) - An error object if any occurred during policy addition. #### Response Example ```json { "added": true, "err": null } ``` ``` -------------------------------- ### Perform Access Control Check Source: https://github.com/apache/casbin/blob/master/README.md Enforce access control policies before a resource is accessed. This snippet checks if a user ('alice') is permitted to perform an action ('read') on a resource ('data1'). ```go sub := "alice" // the user that wants to access a resource. obj := "data1" // the resource that is going to be accessed. act := "read" // the operation that the user performs on the resource. if res, _ := e.Enforce(sub, obj, act); res { // permit alice to read data1 } else { // deny the request, show an error } ``` -------------------------------- ### Batch Enforcement with BatchEnforce Source: https://context7.com/apache/casbin/llms.txt The `BatchEnforce` method processes multiple authorization requests at once, returning a slice of boolean results. This is more efficient than calling `Enforce` multiple times when checking many requests. ```APIDOC ## BatchEnforce ### Description Processes multiple authorization requests at once, returning a slice of boolean results. ### Method `BatchEnforce` ### Parameters #### Request Body - **requests** ([][]interface{}) - Required - A slice of authorization requests, where each request is a slice of strings representing subject, object, and action. ### Request Example ```json { "requests": [ ["alice", "data1", "read"], ["alice", "data1", "write"], ["bob", "data2", "write"], ["bob", "data1", "read"] ] } ``` ### Response #### Success Response (200) - **results** ([]bool) - A slice of boolean values, where each value corresponds to the result of an authorization request in the input slice. - **err** (error) - An error object if any occurred during batch enforcement. #### Response Example ```json { "results": [true, false, true, false], "err": null } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.