-
Notifications
You must be signed in to change notification settings - Fork 0
/
onepassword.go
87 lines (74 loc) · 2.01 KB
/
onepassword.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
package onepassword
import (
"context"
"regexp"
"strings"
"sync"
"github.com/1Password/connect-sdk-go/connect"
"github.com/pkg/errors"
)
var (
onePasswordCache = map[string]map[string]string{}
onePasswordUUID = regexp.MustCompile(`^[a-z0-9]{26}$`)
)
var (
ErrNotFound = errors.New("not found")
ErrNotSignedIn = errors.New("not signed in")
)
var onePasswordGetLock sync.Mutex
var onePasswordGetDocumentLock sync.Mutex
func Secret(ctx context.Context, account, vaultUUID, itemUUID, field string) (string, error) {
cacheKey := strings.Join([]string{account, vaultUUID, itemUUID}, "#")
if _, ok := onePasswordCache[cacheKey]; !ok {
switch {
case IsConnect():
client, err := connect.NewClientFromEnvironment()
if err != nil {
return "", err
}
if res, err := ConnectSecret(client, vaultUUID, itemUUID); err != nil {
return "", err
} else {
onePasswordCache[cacheKey] = res
}
default:
if res, err := CLiSecret(ctx, account, vaultUUID, itemUUID); err != nil {
return "", err
} else {
onePasswordCache[cacheKey] = res
}
}
}
value, ok := onePasswordCache[cacheKey][field]
if !ok {
return "", ErrNotFound
}
return value, nil
}
func Document(ctx context.Context, account, vaultUUID, itemUUID string) (string, error) {
// create cache key
cacheKey := strings.Join([]string{account, vaultUUID, itemUUID}, "#")
if _, ok := onePasswordCache[cacheKey]; !ok {
switch {
case IsConnect():
if client, err := connect.NewClientFromEnvironment(); err != nil {
return "", err
} else if res, err := ConnectDocument(client, vaultUUID, itemUUID); err != nil {
return "", err
} else {
onePasswordCache[cacheKey] = map[string]string{"document": res}
}
default:
if res, err := CLIDocument(ctx, account, vaultUUID, itemUUID); err != nil {
return "", err
} else {
onePasswordCache[cacheKey] = map[string]string{"document": res}
}
}
}
value, ok := onePasswordCache[cacheKey]["document"]
if !ok {
return "", ErrNotFound
}
return value, nil
}