aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/core/auth/token.go
blob: 84d6ac13e804188e3c0b3513e649c60b41bc0c68 (plain) (blame)
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
package auth

import (
	"crypto/sha256"
	"fmt"

	"github.com/MichaelMure/git-bug/entity"
)

const (
	keyringKeyTokenValue = "value"
)

var _ Credential = &Token{}

// Token holds an API access token data
type Token struct {
	*credentialBase
	Value string
}

// NewToken instantiate a new token
func NewToken(target, value string) *Token {
	return &Token{
		credentialBase: newCredentialBase(target),
		Value:          value,
	}
}

func NewTokenFromConfig(conf map[string]string) (*Token, error) {
	base, err := newCredentialBaseFromData(conf)
	if err != nil {
		return nil, err
	}

	return &Token{
		credentialBase: base,
		Value:          conf[keyringKeyTokenValue],
	}, nil
}

func (t *Token) ID() entity.Id {
	h := sha256.New()
	_, _ = h.Write(t.salt)
	_, _ = h.Write([]byte(t.target))
	_, _ = h.Write([]byte(t.Value))
	return entity.Id(fmt.Sprintf("%x", h.Sum(nil)))
}

func (t *Token) Kind() CredentialKind {
	return KindToken
}

// Validate ensure token important fields are valid
func (t *Token) Validate() error {
	err := t.credentialBase.validate()
	if err != nil {
		return err
	}
	if t.Value == "" {
		return fmt.Errorf("missing value")
	}
	return nil
}

func (t *Token) toConfig() map[string]string {
	return map[string]string{
		keyringKeyTokenValue: t.Value,
	}
}