forked from garetht/amanar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keychain_utils.go
72 lines (56 loc) · 1.84 KB
/
keychain_utils.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
// +build darwin cgo
package amanar
import (
"errors"
"fmt"
"github.com/keybase/go-keychain"
)
// Deletion poses problems because there does not seem to be a
// way to make deletion prompt for access, which means it will fail.
// trustedApplications is only set when creating a new keychain entry.
// Q: what happens when updating?
func CreateOrUpdateKeychainEntriesForService(service, account, password string, trustedApplications []string) error {
item := keychain.NewItem()
item.SetSecClass(keychain.SecClassGenericPassword)
item.SetService(service)
item.SetMatchLimit(keychain.MatchLimitAll)
item.SetReturnAttributes(true)
results, err := keychain.QueryItem(item)
if err != nil {
return err
}
if len(results) == 0 {
return CreateKeychainEntryForService(service, account, password, trustedApplications)
}
if len(results) > 1 {
return errors.New(fmt.Sprintf("[KEYCHAIN] Found more than one entry for the service %s. Please delete duplicates and try again.", service))
}
for _, result := range results {
originalItem := keychain.NewItem()
originalItem.SetSecClass(keychain.SecClassGenericPassword)
originalItem.SetService(result.Service)
originalItem.SetAccount(result.Account)
updateItem := keychain.NewItem()
if account != "" {
updateItem.SetAccount(account)
}
updateItem.SetData([]byte(password))
// There should only ever be one result
err = keychain.UpdateItem(originalItem, updateItem)
}
return err
}
// Creates a new keychain entry and
func CreateKeychainEntryForService(service, account, password string, trustedApplications []string) error {
item := keychain.NewItem()
item.SetSecClass(keychain.SecClassGenericPassword)
item.SetService(service)
item.SetAccount(account)
item.SetLabel(service)
item.SetData([]byte(password))
err := keychain.AddItem(item)
if err != nil {
return err
}
return nil
}