forked from 14850842/rancher-letsencrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
96 lines (80 loc) · 2.45 KB
/
account.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
88
89
90
91
92
93
94
95
96
package letsencrypt
import (
"crypto"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/Sirupsen/logrus"
lego "github.com/xenolf/lego/acme"
)
type Account struct {
Email string `json:"email"`
Registration *lego.RegistrationResource `json:"registrations"`
key crypto.PrivateKey
path string
}
// NewAccount creates a new or gets a stored LE account for the given email
func NewAccount(email string, apiVer ApiVersion, keyType lego.KeyType) (*Account, error) {
accPath := accountPath(email, apiVer)
keyFile := path.Join(accPath, "account.key")
accountFile := path.Join(accPath, "account.json")
var privKey crypto.PrivateKey
if _, err := os.Stat(keyFile); os.IsNotExist(err) {
logrus.Infof("Generating private key (%s) for %s.", keyType, email)
privKey, err = generatePrivateKey(keyType, keyFile)
if err != nil {
return nil, fmt.Errorf("Error generating private key: %v", err)
}
logrus.Debugf("Saved account key to %s", keyFile)
} else {
privKey, err = loadPrivateKey(keyFile)
if err != nil {
return nil, fmt.Errorf("Error loading private key from %s: %v", keyFile, err)
}
}
if _, err := os.Stat(accountFile); os.IsNotExist(err) {
return &Account{Email: email, key: privKey, path: accPath}, nil
}
fileBytes, err := ioutil.ReadFile(accountFile)
if err != nil {
return nil, fmt.Errorf("Could not load account config file: %v", err)
}
var acc Account
err = json.Unmarshal(fileBytes, &acc)
if err != nil {
return nil, fmt.Errorf("Could not parse account config file: %v", err)
}
acc.key = privKey
acc.path = accPath
return &acc, nil
}
// Save the account to disk
func (a *Account) Save() error {
jsonBytes, err := json.MarshalIndent(a, "", "\t")
if err != nil {
return err
}
accountFile := path.Join(a.path, "account.json")
return ioutil.WriteFile(accountFile, jsonBytes, 0700)
}
/* Methods implementing the lego.User interface*/
// GetEmail returns the email address for the account
func (a *Account) GetEmail() string {
return a.Email
}
// GetPrivateKey returns the private RSA account key.
func (a *Account) GetPrivateKey() crypto.PrivateKey {
return a.key
}
// GetRegistration returns the server registration
func (a *Account) GetRegistration() *lego.RegistrationResource {
return a.Registration
}
func accountPath(email string, apiVer ApiVersion) string {
path := path.Join(StorageDir, strings.ToLower(string(apiVer)), "accounts", email)
maybeCreatePath(path)
return path
}