| 84 | } |
| 85 | |
| 86 | func syncRBACRoles(e *CasbinEnforcer, c *Config) error { |
| 87 | // allow to override config during sync |
| 88 | conf := c |
| 89 | if conf == nil { |
| 90 | conf = e.config |
| 91 | } |
| 92 | |
| 93 | // Add all the defined policies if they don't exist |
| 94 | for role, policies := range conf.RolesMap { |
| 95 | for _, p := range policies { |
| 96 | // Add policies one by one to skip existing ones |
| 97 | casbinPolicy := []string{string(role), p.Resource, p.Action} |
| 98 | _, err := e.AddPolicy(casbinPolicy) |
| 99 | if err != nil { |
| 100 | return fmt.Errorf("failed to add policy: %w", err) |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // Delete all the policies that are not in the roles map |
| 106 | // 1 - load the policies from the enforcer |
| 107 | policies, err := e.GetPolicy() |
| 108 | if err != nil { |
| 109 | return fmt.Errorf("failed to get policies: %w", err) |
| 110 | } |
| 111 | |
| 112 | // clone policies, as delete operations in CasBin alters the "policies" slice |
| 113 | clonedPolicies := slices.Clone(policies) |
| 114 | |
| 115 | for _, p := range clonedPolicies { |
| 116 | role := p[0] |
| 117 | resource := p[1] |
| 118 | action := p[2] |
| 119 | |
| 120 | wantPolicies, ok := conf.RolesMap[Role(role)] |
| 121 | // if the role does not exist in the map, we can delete the policy |
| 122 | if !ok { |
| 123 | _, err := e.RemovePolicy(role, resource, action) |
| 124 | if err != nil { |
| 125 | return fmt.Errorf("failed to remove policy: %w", err) |
| 126 | } |
| 127 | continue |
| 128 | } |
| 129 | |
| 130 | // We have the role in the map, so we now compare the policies |
| 131 | found := false |
| 132 | for _, p := range wantPolicies { |
| 133 | if p.Resource == resource && p.Action == action { |
| 134 | found = true |
| 135 | break |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // If the policy is not in the map, we remove it |
| 140 | if !found { |
| 141 | _, err := e.RemovePolicy(p) |
| 142 | if err != nil { |
| 143 | return fmt.Errorf("failed to remove policy: %w", err) |