/
config_key.go
111 lines (87 loc) · 2.47 KB
/
config_key.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package auth
import (
"fmt"
"net/http"
"golang.org/x/exp/slices"
"github.com/gin-gonic/gin"
"github.com/justtrackio/gosoline/pkg/cfg"
"github.com/justtrackio/gosoline/pkg/funk"
"github.com/justtrackio/gosoline/pkg/log"
)
const (
ByApiKey = "apiKey"
HeaderApiKey = "X-API-KEY"
configApiKeys = "api_auth_keys"
AttributeApiKey = "apiKey"
)
type configKeyAuthenticator struct {
logger log.Logger
keys []string
provider ApiKeyProvider
}
type ApiKeyProvider func(ginCtx *gin.Context) string
func NewConfigKeyHandler(config cfg.Config, logger log.Logger, provider ApiKeyProvider) gin.HandlerFunc {
auth := NewConfigKeyAuthenticator(config, logger, provider)
return func(ginCtx *gin.Context) {
valid, err := auth.IsValid(ginCtx)
if valid {
return
}
if err == nil {
err = fmt.Errorf("the api key wasn't valid nor was there an error")
}
ginCtx.JSON(http.StatusUnauthorized, gin.H{"err": err.Error()})
ginCtx.Abort()
}
}
func NewConfigKeyAuthenticator(config cfg.Config, logger log.Logger, provider ApiKeyProvider) Authenticator {
keys := config.GetStringSlice(configApiKeys)
keys = funk.Filter(keys, func(key string) bool {
return key != ""
})
return NewConfigKeyAuthenticatorWithInterfaces(logger, keys, provider)
}
func NewConfigKeyAuthenticatorWithInterfaces(logger log.Logger, keys []string, provider ApiKeyProvider) Authenticator {
return &configKeyAuthenticator{
logger: logger,
keys: keys,
provider: provider,
}
}
func (a *configKeyAuthenticator) IsValid(ginCtx *gin.Context) (bool, error) {
apiKey := a.provider(ginCtx)
if apiKey == "" {
return false, fmt.Errorf("no api key provided")
}
if len(a.keys) == 0 {
return false, fmt.Errorf("there are no api keys configured")
}
if !slices.Contains(a.keys, apiKey) {
return false, fmt.Errorf("api key does not match")
}
user := &Subject{
Name: Anonymous,
Anonymous: true,
AuthenticatedBy: ByApiKey,
Attributes: map[string]interface{}{
AttributeApiKey: apiKey,
},
}
RequestWithSubject(ginCtx, user)
return true, nil
}
func ProvideValueFromQueryParam(queryParam string) ApiKeyProvider {
return func(ginCtx *gin.Context) string {
return ginCtx.Query(queryParam)
}
}
func ProvideValueFromHeader(header string) ApiKeyProvider {
return func(ginCtx *gin.Context) string {
return ginCtx.GetHeader(header)
}
}
func ProvideValueFromUriPath(param string) ApiKeyProvider {
return func(ginCtx *gin.Context) string {
return ginCtx.Param(param)
}
}