-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.go
116 lines (93 loc) · 2.4 KB
/
document.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
package document
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"io"
"github.com/oklog/ulid/v2"
)
// Document is a document that can be stored in a database.
type Document struct {
ID ulid.ULID `json:"_id"`
Collection string `json:"collection"`
Data map[string]interface{} `json:"data"`
}
// SetID sets the ID of the document. Should only be used for testing.
func (d *Document) SetID(id string) *Document {
d.ID = ulid.MustParse(id)
return d
}
// SetCollection sets the collection of the document.
func (d *Document) SetCollection(name string) *Document {
d.Collection = name
return d
}
// SetData sets the fields of the document.
func (d *Document) SetData(data map[string]interface{}) *Document {
if data == nil {
data = make(map[string]interface{})
}
d.Data = data
return d
}
// ToStorage returns the document as a byte slice that can be stored in a database,
// if an encryption key is provided, the document will be encrypted.
func (d *Document) ToStorage(encryptionKey []byte) ([]byte, error) {
b, err := json.Marshal(&d)
if err != nil {
return nil, err
}
if len(encryptionKey) > 0 {
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, b, nil), nil
}
return b, nil
}
// FromStorage returns a document from a byte slice that was stored in a database,
// if an encryption key is provided, the document will be decrypted.
func FromStorage(b []byte, encryptionKey []byte) (*Document, error) {
if len(encryptionKey) > 0 {
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(b) < nonceSize {
return nil, err
}
nonce, ciphertext := b[:nonceSize], b[nonceSize:]
b, err = gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
}
d := &Document{}
if err := json.Unmarshal(b, d); err != nil {
return nil, err
}
return d, nil
}
// New returns a new document.
func New() *Document {
return &Document{
ID: ulid.Make(),
Collection: "",
Data: make(map[string]interface{}),
}
}