aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/core/auth/token.go
blob: 42f960bfc9d72ae979f2ae34e86fbbcd11e1bdb6 (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
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
97
98
99
100
101
102
103
104
105
106
package auth

import (
	"crypto/sha256"
	"fmt"
	"time"

	"github.com/MichaelMure/git-bug/bridge/core"
	"github.com/MichaelMure/git-bug/entity"
	"github.com/MichaelMure/git-bug/repository"
)

const (
	tokenValueKey = "value"
)

var _ Credential = &Token{}

// Token holds an API access token data
type Token struct {
	target     string
	createTime time.Time
	Value      string
	meta       map[string]string
}

// NewToken instantiate a new token
func NewToken(value, target string) *Token {
	return &Token{
		target:     target,
		createTime: time.Now(),
		Value:      value,
	}
}

func NewTokenFromConfig(conf map[string]string) *Token {
	token := &Token{}

	token.target = conf[configKeyTarget]
	if createTime, ok := conf[configKeyCreateTime]; ok {
		if t, err := repository.ParseTimestamp(createTime); err == nil {
			token.createTime = t
		}
	}

	token.Value = conf[tokenValueKey]
	token.meta = metaFromConfig(conf)

	return token
}

func (t *Token) ID() entity.Id {
	sum := sha256.Sum256([]byte(t.target + t.Value))
	return entity.Id(fmt.Sprintf("%x", sum))
}

func (t *Token) Target() string {
	return t.target
}

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

func (t *Token) CreateTime() time.Time {
	return t.createTime
}

// Validate ensure token important fields are valid
func (t *Token) Validate() error {
	if t.Value == "" {
		return fmt.Errorf("missing value")
	}
	if t.target == "" {
		return fmt.Errorf("missing target")
	}
	if t.createTime.IsZero() || t.createTime.Equal(time.Time{}) {
		return fmt.Errorf("missing creation time")
	}
	if !core.TargetExist(t.target) {
		return fmt.Errorf("unknown target")
	}
	return nil
}

func (t *Token) Metadata() map[string]string {
	return t.meta
}

func (t *Token) GetMetadata(key string) (string, bool) {
	val, ok := t.meta[key]
	return val, ok
}

func (t *Token) SetMetadata(key string, value string) {
	if t.meta == nil {
		t.meta = make(map[string]string)
	}
	t.meta[key] = value
}

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