2019-12-08 23:15:06 +03:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/MichaelMure/git-bug/entity"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-07-28 13:56:46 +03:00
|
|
|
keyringKeyTokenValue = "value"
|
2019-12-08 23:15:06 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ Credential = &Token{}
|
|
|
|
|
|
|
|
// Token holds an API access token data
|
|
|
|
type Token struct {
|
2020-02-12 20:32:01 +03:00
|
|
|
*credentialBase
|
|
|
|
Value string
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewToken instantiate a new token
|
2020-02-12 20:32:01 +03:00
|
|
|
func NewToken(target, value string) *Token {
|
2019-12-08 23:15:06 +03:00
|
|
|
return &Token{
|
2020-02-12 20:32:01 +03:00
|
|
|
credentialBase: newCredentialBase(target),
|
|
|
|
Value: value,
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-12 20:32:01 +03:00
|
|
|
func NewTokenFromConfig(conf map[string]string) (*Token, error) {
|
2020-07-28 13:56:46 +03:00
|
|
|
base, err := newCredentialBaseFromData(conf)
|
2020-02-12 20:32:01 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
|
2020-02-12 20:32:01 +03:00
|
|
|
return &Token{
|
|
|
|
credentialBase: base,
|
2020-07-28 13:56:46 +03:00
|
|
|
Value: conf[keyringKeyTokenValue],
|
2020-02-12 20:32:01 +03:00
|
|
|
}, nil
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Token) ID() entity.Id {
|
2020-02-12 20:32:01 +03:00
|
|
|
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)))
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Token) Kind() CredentialKind {
|
|
|
|
return KindToken
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate ensure token important fields are valid
|
|
|
|
func (t *Token) Validate() error {
|
2020-02-12 20:32:01 +03:00
|
|
|
err := t.credentialBase.validate()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-12-08 23:15:06 +03:00
|
|
|
if t.Value == "" {
|
|
|
|
return fmt.Errorf("missing value")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-12-26 00:55:53 +03:00
|
|
|
func (t *Token) toConfig() map[string]string {
|
2019-12-08 23:15:06 +03:00
|
|
|
return map[string]string{
|
2020-07-28 13:56:46 +03:00
|
|
|
keyringKeyTokenValue: t.Value,
|
2019-12-08 23:15:06 +03:00
|
|
|
}
|
|
|
|
}
|