-
Notifications
You must be signed in to change notification settings - Fork 0
/
checks.go
103 lines (82 loc) · 2.51 KB
/
checks.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package fgax
import (
"context"
ofgaclient "github.com/openfga/go-sdk/client"
)
// AccessCheck is a struct to hold the information needed to check access
type AccessCheck struct {
// ObjectType is the type of object being checked
ObjectType Kind
// ObjectID is the ID of the object being checked
ObjectID string
// Relation is the relationship being checked (e.g. "view", "edit", "delete")
Relation string
// UserID is the ID of the user making the request
UserID string
}
// CheckTuple checks the openFGA store for provided relationship tuple
func (c *Client) CheckTuple(ctx context.Context, check ofgaclient.ClientCheckRequest) (bool, error) {
data, err := c.Ofga.Check(ctx).Body(check).Execute()
if err != nil {
c.Logger.Errorw("error checking tuple", "tuple", check, "error", err.Error())
return false, err
}
return *data.Allowed, nil
}
// CheckAccess checks if the user has access to the object type with the given relation
func (c *Client) CheckAccess(ctx context.Context, ac AccessCheck) (bool, error) {
if err := validateAccessCheck(ac); err != nil {
return false, err
}
sub := Entity{
Kind: "user",
Identifier: ac.UserID,
}
obj := Entity{
Kind: ac.ObjectType,
Identifier: ac.ObjectID,
}
c.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object", obj.String())
checkReq := ofgaclient.ClientCheckRequest{
User: sub.String(),
Relation: ac.Relation,
Object: obj.String(),
}
return c.CheckTuple(ctx, checkReq)
}
// CheckOrgAccess checks if the user has access to the organization with the given relation
func (c *Client) CheckOrgAccess(ctx context.Context, userID, orgID, relation string) (bool, error) {
ac := AccessCheck{
ObjectType: "organization",
ObjectID: orgID,
Relation: relation,
UserID: userID,
}
return c.CheckAccess(ctx, ac)
}
// CheckGroupAccess checks if the user has access to the group with the given relation
func (c *Client) CheckGroupAccess(ctx context.Context, userID, groupID, relation string) (bool, error) {
ac := AccessCheck{
ObjectType: "group",
ObjectID: groupID,
Relation: relation,
UserID: userID,
}
return c.CheckAccess(ctx, ac)
}
// validateAccessCheck checks if the AccessCheck struct is valid
func validateAccessCheck(ac AccessCheck) error {
if ac.UserID == "" {
return ErrInvalidAccessCheck
}
if ac.ObjectType == "" {
return ErrInvalidAccessCheck
}
if ac.ObjectID == "" {
return ErrInvalidAccessCheck
}
if ac.Relation == "" {
return ErrInvalidAccessCheck
}
return nil
}