1package auth
 2
 3import (
 4	"crypto/sha256"
 5	"fmt"
 6
 7	"github.com/MichaelMure/git-bug/entity"
 8)
 9
10const (
11	keyringKeyTokenValue = "value"
12)
13
14var _ Credential = &Token{}
15
16// Token holds an API access token data
17type Token struct {
18	*credentialBase
19	Value string
20}
21
22// NewToken instantiate a new token
23func NewToken(target, value string) *Token {
24	return &Token{
25		credentialBase: newCredentialBase(target),
26		Value:          value,
27	}
28}
29
30func NewTokenFromConfig(conf map[string]string) (*Token, error) {
31	base, err := newCredentialBaseFromData(conf)
32	if err != nil {
33		return nil, err
34	}
35
36	return &Token{
37		credentialBase: base,
38		Value:          conf[keyringKeyTokenValue],
39	}, nil
40}
41
42func (t *Token) ID() entity.Id {
43	h := sha256.New()
44	_, _ = h.Write(t.salt)
45	_, _ = h.Write([]byte(t.target))
46	_, _ = h.Write([]byte(t.Value))
47	return entity.Id(fmt.Sprintf("%x", h.Sum(nil)))
48}
49
50func (t *Token) Kind() CredentialKind {
51	return KindToken
52}
53
54// Validate ensure token important fields are valid
55func (t *Token) Validate() error {
56	err := t.credentialBase.validate()
57	if err != nil {
58		return err
59	}
60	if t.Value == "" {
61		return fmt.Errorf("missing value")
62	}
63	return nil
64}
65
66func (t *Token) toConfig() map[string]string {
67	return map[string]string{
68		keyringKeyTokenValue: t.Value,
69	}
70}