-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_key_security_handler.go
66 lines (52 loc) · 1.36 KB
/
static_key_security_handler.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
package auth
import (
"context"
"errors"
"github.com/awlsring/texit/pkg/gen/texit"
)
var (
ErrInvalidKey = errors.New("invalid key")
)
type StaticKeySecurityHandlerOption func(*StaticKeySecurityHandler)
type StaticKeySecurityHandler struct {
keys []string
noAuthOperations []string
}
func WithNoAuthOperations(operations []string) StaticKeySecurityHandlerOption {
return func(h *StaticKeySecurityHandler) {
h.noAuthOperations = operations
}
}
func NewSecurityHandler(keys []string, opts ...StaticKeySecurityHandlerOption) texit.SecurityHandler {
sec := &StaticKeySecurityHandler{
keys: keys,
}
for _, opt := range opts {
opt(sec)
}
return sec
}
func stringInList(s string, list []string) bool {
for _, item := range list {
if s == item {
return true
}
}
return false
}
func (h *StaticKeySecurityHandler) isNoAuthOperation(operationName string) bool {
return stringInList(operationName, h.noAuthOperations)
}
func (h *StaticKeySecurityHandler) isValidKey(key string) bool {
return stringInList(key, h.keys)
}
func (h *StaticKeySecurityHandler) HandleSmithyAPIHttpApiKeyAuth(ctx context.Context, operationName string, t texit.SmithyAPIHttpApiKeyAuth) (context.Context, error) {
key := t.GetAPIKey()
if h.isNoAuthOperation(operationName) {
return ctx, nil
}
if h.isValidKey(key) {
return ctx, nil
}
return ctx, ErrInvalidKey
}