aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/core/auth/credential_base.go
blob: 488c223cef31976694d8464202c6709a976151c6 (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
package auth

import (
	"fmt"
	"time"

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

type credentialBase struct {
	target     string
	createTime time.Time
	salt       []byte
	meta       map[string]string
}

func newCredentialBase(target string) *credentialBase {
	return &credentialBase{
		target:     target,
		createTime: time.Now(),
		salt:       makeSalt(),
	}
}

func newCredentialBaseFromConfig(conf map[string]string) (*credentialBase, error) {
	base := &credentialBase{
		target: conf[configKeyTarget],
		meta:   metaFromConfig(conf),
	}

	if createTime, ok := conf[configKeyCreateTime]; ok {
		t, err := repository.ParseTimestamp(createTime)
		if err != nil {
			return nil, err
		}
		base.createTime = t
	} else {
		return nil, fmt.Errorf("missing create time")
	}

	salt, err := saltFromConfig(conf)
	if err != nil {
		return nil, err
	}
	base.salt = salt

	return base, nil
}

func (cb *credentialBase) Target() string {
	return cb.target
}

func (cb *credentialBase) CreateTime() time.Time {
	return cb.createTime
}

func (cb *credentialBase) Salt() []byte {
	return cb.salt
}

func (cb *credentialBase) validate() error {
	if cb.target == "" {
		return fmt.Errorf("missing target")
	}
	if cb.createTime.IsZero() || cb.createTime.Equal(time.Time{}) {
		return fmt.Errorf("missing creation time")
	}
	if !core.TargetExist(cb.target) {
		return fmt.Errorf("unknown target")
	}
	return nil
}

func (cb *credentialBase) Metadata() map[string]string {
	return cb.meta
}

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

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