-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcondition_equal.go
82 lines (66 loc) · 2.39 KB
/
condition_equal.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
package restrict
import (
"fmt"
"reflect"
)
const (
// EqualConditionType - EqualCondition's type identifier.
EqualConditionType = "EQUAL"
//NotEqualConditionType - NotEqualCondition's type identifier.
NotEqualConditionType = "NOT_EQUAL"
)
// baseEqualCondition - describes fields needed by Equal/NotEqual Conditions.
type baseEqualCondition struct {
// ID - Condition's id, useful when there is a need to identify failing Condition.
ID string `json:"name,omitempty" yaml:"name,omitempty"`
// Left - ValueDescriptor for left operand of equality check.
Left *ValueDescriptor `json:"left" yaml:"left"`
// Right - ValueDescriptor for right operand of equality check.
Right *ValueDescriptor `json:"right" yaml:"right"`
}
// EqualCondition - checks whether given value (Left) is equal to some other value (Right).
type EqualCondition baseEqualCondition
// Type - returns Condition's type.
func (c *EqualCondition) Type() string {
return EqualConditionType
}
// Check - returns true if values are equal, false otherwise.
func (c *EqualCondition) Check(request *AccessRequest) error {
left, right, err := unpackEqualDescriptors(c.Left, c.Right, request)
if err != nil {
return err
}
if !reflect.DeepEqual(left, right) {
return NewConditionNotSatisfiedError(c, request, fmt.Errorf("values \"%v\" and \"%v\" are not equal", left, right))
}
return nil
}
// NotEqualCondition - checks whether given value (Left) is not equal to some other value (Right).
type NotEqualCondition baseEqualCondition
// Type - returns Condition's type.
func (c *NotEqualCondition) Type() string {
return NotEqualConditionType
}
// Check - returns true if values are not equal, false otherwise.
func (c *NotEqualCondition) Check(request *AccessRequest) error {
left, right, err := unpackEqualDescriptors(c.Left, c.Right, request)
if err != nil {
return err
}
if reflect.DeepEqual(left, right) {
return NewConditionNotSatisfiedError(c, request, fmt.Errorf("values \"%v\" and \"%v\" are equal", left, right))
}
return nil
}
// unpackDescriptors - helper function for unpacking ValueDescriptors' values.
func unpackEqualDescriptors(left, right *ValueDescriptor, request *AccessRequest) (interface{}, interface{}, error) {
leftValue, err := left.GetValue(request)
if err != nil {
return nil, nil, err
}
rightValue, err := right.GetValue(request)
if err != nil {
return nil, nil, err
}
return leftValue, rightValue, nil
}