-
Notifications
You must be signed in to change notification settings - Fork 3
/
token.go
82 lines (64 loc) · 1.75 KB
/
token.go
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
package token
import (
"context"
"github.com/alexfalkowski/go-service/crypto/argon2"
"github.com/alexfalkowski/go-service/crypto/rand"
"github.com/alexfalkowski/go-service/os"
)
// Generate key and hash for token.
func Generate() (Key, Hash, error) {
k, err := rand.GenerateString(32)
if err != nil {
return "", "", err
}
algo := argon2.NewAlgo()
h, err := algo.Generate(k)
if err != nil {
return "", "", err
}
return Key(k), Hash(h), nil
}
type (
// Generator allows the implementation of different types generators.
Generator interface {
// Generate a new token or error.
Generate(ctx context.Context) (context.Context, []byte, error)
}
// Verifier allows the implementation of different types of verifiers.
Verifier interface {
// Verify a token or error.
Verify(ctx context.Context, token []byte) (context.Context, error)
}
// Tokenizer will generate and verify.
Tokenizer interface {
Generator
Verifier
}
token struct {
cfg *Config
algo argon2.Algo
}
none struct{}
)
// NewTokenizer for token.
func NewTokenizer(cfg *Config, algo argon2.Algo) Tokenizer {
if !IsEnabled(cfg) {
return &none{}
}
return &token{cfg: cfg, algo: algo}
}
// Generate token from secret file.
func (t *token) Generate(ctx context.Context) (context.Context, []byte, error) {
d, err := os.ReadBase64File(string(t.cfg.Key))
return ctx, []byte(d), err
}
// Verify the token with the stored hash.
func (t *token) Verify(ctx context.Context, token []byte) (context.Context, error) {
return ctx, t.algo.Compare(string(t.cfg.Hash), string(token))
}
func (*none) Generate(ctx context.Context) (context.Context, []byte, error) {
return ctx, nil, nil
}
func (*none) Verify(ctx context.Context, _ []byte) (context.Context, error) {
return ctx, nil
}