-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroles.go
More file actions
66 lines (52 loc) · 1.56 KB
/
Copy pathroles.go
File metadata and controls
66 lines (52 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package hyperacc
import (
"fmt"
"slices"
"github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
)
// RoleRule checks for a specific role
type RoleRule struct {
role string
}
// RequireRole creates a rule to check for a specific role
func RequireRole(role string) *RoleRule {
return &RoleRule{role: role}
}
// Check checks if the caller has the role
func (r *RoleRule) Check(ctx contractapi.TransactionContextInterface) error {
identity := ctx.GetClientIdentity()
role, found, err := identity.GetAttributeValue("role")
if err != nil {
return fmt.Errorf("failed to get role attribute: %w", err)
}
if !found {
return fmt.Errorf("role attribute not found in identity")
}
if role != r.role {
return NewAccessError(fmt.Sprintf("required role '%s', got '%s'", r.role, role))
}
return nil
}
// AnyRoleRule checks for one of the specified roles
type AnyRoleRule struct {
roles []string
}
// RequireAnyRole creates a rule to check for one of the roles
func RequireAnyRole(roles ...string) *AnyRoleRule {
return &AnyRoleRule{roles: roles}
}
// Check checks if the caller has one of the roles
func (r *AnyRoleRule) Check(ctx contractapi.TransactionContextInterface) error {
identity := ctx.GetClientIdentity()
role, found, err := identity.GetAttributeValue("role")
if err != nil {
return fmt.Errorf("failed to get role attribute: %w", err)
}
if !found {
return fmt.Errorf("role attribute not found in identity")
}
if slices.Contains(r.roles, role) {
return nil
}
return NewAccessError(fmt.Sprintf("required one of roles %v, got '%s'", r.roles, role))
}