forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_struct.go
118 lines (96 loc) · 2.54 KB
/
path_struct.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package framework
import (
"encoding/json"
"fmt"
"github.com/hashicorp/vault/logical"
)
// PathStruct can be used to generate a path that stores a struct
// in the storage. This structure is a map[string]interface{} but the
// types are set according to the schema in this structure.
type PathStruct struct {
Name string
Path string
Schema map[string]*FieldSchema
HelpSynopsis string
HelpDescription string
Read bool
}
// Get reads the structure.
func (p *PathStruct) Get(s logical.Storage) (map[string]interface{}, error) {
entry, err := s.Get(fmt.Sprintf("struct/%s", p.Name))
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result map[string]interface{}
if err := json.Unmarshal(entry.Value, &result); err != nil {
return nil, err
}
return result, nil
}
// Put writes the structure.
func (p *PathStruct) Put(s logical.Storage, v map[string]interface{}) error {
bytes, err := json.Marshal(v)
if err != nil {
return err
}
return s.Put(&logical.StorageEntry{
Key: fmt.Sprintf("struct/%s", p.Name),
Value: bytes,
})
}
// Delete removes the structure.
func (p *PathStruct) Delete(s logical.Storage) error {
return s.Delete(fmt.Sprintf("struct/%s", p.Name))
}
// Paths are the paths to append to the Backend paths.
func (p *PathStruct) Paths() []*Path {
// The single path we support to read/write this config
path := &Path{
Pattern: p.Path,
Fields: p.Schema,
Callbacks: map[logical.Operation]OperationFunc{
logical.CreateOperation: p.pathWrite,
logical.UpdateOperation: p.pathWrite,
logical.DeleteOperation: p.pathDelete,
},
ExistenceCheck: p.pathExistenceCheck,
HelpSynopsis: p.HelpSynopsis,
HelpDescription: p.HelpDescription,
}
// If we support reads, add that
if p.Read {
path.Callbacks[logical.ReadOperation] = p.pathRead
}
return []*Path{path}
}
func (p *PathStruct) pathRead(
req *logical.Request, d *FieldData) (*logical.Response, error) {
v, err := p.Get(req.Storage)
if err != nil {
return nil, err
}
return &logical.Response{
Data: v,
}, nil
}
func (p *PathStruct) pathWrite(
req *logical.Request, d *FieldData) (*logical.Response, error) {
err := p.Put(req.Storage, d.Raw)
return nil, err
}
func (p *PathStruct) pathDelete(
req *logical.Request, d *FieldData) (*logical.Response, error) {
err := p.Delete(req.Storage)
return nil, err
}
func (p *PathStruct) pathExistenceCheck(
req *logical.Request, d *FieldData) (bool, error) {
v, err := p.Get(req.Storage)
if err != nil {
return false, err
}
return v != nil, nil
}