Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-db/go/json.go
2500 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package db
6
7
import (
8
"encoding/json"
9
"fmt"
10
"gorm.io/datatypes"
11
)
12
13
type EncryptedJSON[T any] datatypes.JSON
14
15
func (j *EncryptedJSON[T]) EncryptedData() (EncryptedData, error) {
16
var data EncryptedData
17
err := json.Unmarshal(*j, &data)
18
if err != nil {
19
return EncryptedData{}, fmt.Errorf("failed to unmarshal encrypted json: %w", err)
20
}
21
22
return data, nil
23
}
24
25
func (j *EncryptedJSON[T]) Decrypt(decryptor Decryptor) (T, error) {
26
var out T
27
data, err := j.EncryptedData()
28
if err != nil {
29
return out, fmt.Errorf("failed to obtain encrypted data: %w", err)
30
}
31
32
b, err := decryptor.Decrypt(data)
33
if err != nil {
34
return out, fmt.Errorf("failed to decrypt encrypted json: %w", err)
35
}
36
37
err = json.Unmarshal(b, &out)
38
if err != nil {
39
return out, fmt.Errorf("failed to unmarshal encrypted json: %w", err)
40
}
41
42
return out, nil
43
}
44
45
func EncryptJSON[T any](encryptor Encryptor, data T) (EncryptedJSON[T], error) {
46
b, err := json.Marshal(data)
47
if err != nil {
48
return nil, fmt.Errorf("failed to marshal data into json: %w", err)
49
}
50
51
encrypted, err := encryptor.Encrypt(b)
52
if err != nil {
53
return nil, fmt.Errorf("failed to encrypt json: %w", err)
54
}
55
56
return NewEncryptedJSON[T](encrypted)
57
}
58
59
func NewEncryptedJSON[T any](data EncryptedData) (EncryptedJSON[T], error) {
60
b, err := json.Marshal(data)
61
if err != nil {
62
return nil, fmt.Errorf("failed to serialize encrypted data into json: %w", err)
63
}
64
65
return b, nil
66
}
67
68