-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyring.go
81 lines (69 loc) · 1.75 KB
/
keyring.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
package jt
import (
"errors"
"fmt"
"os"
"github.com/99designs/keyring"
"golang.org/x/term"
)
const (
// tokenKey is the key used to store the token in the keyring.
tokenKey = "jira-pat"
)
func defaultKeyringConfig() keyring.Config {
return keyring.Config{
ServiceName: "jt",
LibSecretCollectionName: "jt",
KWalletAppID: "jt",
KWalletFolder: "jt",
WinCredPrefix: "jt",
FilePasswordFunc: passphrasePrompt,
KeychainTrustApplication: true,
KeychainSynchronizable: false,
KeychainAccessibleWhenUnlocked: true,
}
}
func GetToken() (string, error) {
c := defaultKeyringConfig()
kr, err := keyring.Open(c)
if err != nil {
return "", fmt.Errorf("failed to open keyring: %w", err)
}
item, err := kr.Get(tokenKey)
if err != nil {
if errors.Is(err, keyring.ErrKeyNotFound) {
return SetToken(tokenKey)
}
return "", fmt.Errorf("failed to get token from keyring: %w", err)
}
return string(item.Data), nil
}
func SetToken(key string) (string, error) {
c := defaultKeyringConfig()
kr, err := keyring.Open(c)
if err != nil {
return "", fmt.Errorf("failed to open keyring: %w", err)
}
token, err := passphrasePrompt("Please enter your Jira personal access token")
if err != nil {
return "", fmt.Errorf("failed to read token: %w", err)
}
err = kr.Set(keyring.Item{
Key: key,
Label: "Jira Personal Access Token",
Data: []byte(token),
})
if err != nil {
return "", fmt.Errorf("failed to save token to keyring: %w", err)
}
return token, nil
}
func passphrasePrompt(prompt string) (string, error) {
fmt.Fprintf(os.Stderr, "%s: ", prompt)
b, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
fmt.Println()
return string(b), nil
}