-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
keychain_mac.go
57 lines (48 loc) · 1.38 KB
/
keychain_mac.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
// +build darwin,amd64
package main
import (
"errors"
"log"
"github.com/keybase/go-keychain"
)
var defaultKeychain = func(serviceLabel string) ([]keychain.QueryResult, error) {
query := getKeychain(serviceLabel)
query.SetReturnData(true)
return keychain.QueryItem(query)
}
func getKeychain(serviceLabel string) keychain.Item {
query := keychain.NewItem()
query.SetSecClass(keychain.SecClassGenericPassword)
query.SetService(serviceLabel)
return query
}
func keychainFetcher(serviceLabel string) (string, error) {
results, err := defaultKeychain(serviceLabel)
if err != nil {
return "", errors.New("unable to connect to keychain")
} else if len(results) > 1 {
return "", errors.New("too many matching items")
} else if len(results) != 1 {
return "", errors.New("item doesn't exist")
}
return string(results[0].Data), nil
}
func keychainWriter(serviceLabel string, secret string) error {
query := getKeychain(serviceLabel)
query.SetData([]byte(secret))
err := keychain.AddItem(query)
if err == keychain.ErrorDuplicateItem {
log.Print("Item already exists, deleting it first")
err = keychainDeleter(serviceLabel)
if err != nil {
return err
}
return keychainWriter(serviceLabel, secret)
}
return err
}
func keychainDeleter(serviceLabel string) error {
query := getKeychain(serviceLabel)
query.SetMatchLimit(keychain.MatchLimitOne)
return keychain.DeleteItem(query)
}