aboutsummaryrefslogtreecommitdiff
path: root/account.go
blob: e0d24b05ca2d7ef5a460a0f4cb91243d27c2a13e (plain)
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
package acme

import (
	"crypto/rsa"
	"io"
	"net/mail"
	"strings"

	"github.com/square/go-jose"
)

// KeySize is a default RSA key size
const KeySize = 2048

// Account ...
type Account struct {
	Contact Contacts        `json:"contact"`
	PrivKey *rsa.PrivateKey `json:"key"`
	signer  jose.Signer
	nonce   chan string
}

func newMail(email string) (Mail, error) {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return "", err
	}
	mm := Mail(m.Address)
	return mm, nil
}

func newPhone(phone string) (Phone, error) {
	p := strings.TrimSpace(phone)
	return Phone(p), nil
}

// NewAccount ...
func NewAccount(key *rsa.PrivateKey) (*Account, error) {
	return &Account{PrivKey: key}, nil
}

func (a *Account) AddMail(mail string) error {
	if m, _ := newMail(mail); m != "" {
		a.Contact = append(a.Contact, m)
	}
	return nil
}

func (a *Account) AddPhone(phone string) error {
	if ph, _ := newPhone(phone); ph != "" {
		a.Contact = append(a.Contact, ph)
	}
	return nil
}

// Signer describes a signing interface
type Signer interface {
	Sign([]byte, jose.NonceSource) (io.Reader, error)
}

func (a *Account) Sign(msg []byte, n jose.NonceSource) (io.Reader, error) {
	if a.signer == nil {
		var err error
		a.signer, err = jose.NewSigner(jose.RS256, a.PrivKey)
		if err != nil {
			return nil, err
		}
		a.signer.SetNonceSource(n)
	}
	obj, err := a.signer.Sign(msg)
	if err != nil {
		return nil, err
	}
	return strings.NewReader(obj.FullSerialize()), nil
}