-
Notifications
You must be signed in to change notification settings - Fork 3
/
token.go
64 lines (50 loc) · 1.42 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
package token
import (
"context"
"github.com/alexfalkowski/go-service/crypto/argon2"
"github.com/alexfalkowski/go-service/os"
)
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(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
}