This repository has been archived by the owner on Jul 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
apikey.go
75 lines (66 loc) · 1.73 KB
/
apikey.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
package apikey
import (
"net/http"
"os"
"github.com/gofiber/fiber/v2"
)
const (
// DefaultKeyIdentifier is the default api key identifier
DefaultKeyIdentifier string = "key"
// DefaultHeaderKeyIdentifier is the default api key identifier in request headers
DefaultHeaderKeyIdentifier string = "x-api-key"
)
// Config is the configuration object for this middleware
type Config struct {
// Skip this middleware
Skip func(*fiber.Ctx) bool
// Key is the api key
Key string
// ValidatorFunc is the function to validates the request
ValidatorFunc func(*fiber.Ctx, Config) bool
}
// DefaultValidatorFunc is the default validator function used to validates the request
// This validator try to look for api key in:
// - URL's query params
// - Request headers
// If api key not found in both of those location, return false
func DefaultValidatorFunc(c *fiber.Ctx, cfg Config) bool {
queryKey := c.Query(DefaultKeyIdentifier)
headerKey := c.Get(DefaultHeaderKeyIdentifier)
if queryKey == "" && headerKey == "" {
return false
}
if queryKey != "" && queryKey == cfg.Key {
return true
}
if headerKey != "" && headerKey == cfg.Key {
return true
}
return false
}
var defaultConfig = Config{
Key: os.Getenv("API_KEY"),
ValidatorFunc: DefaultValidatorFunc,
}
// New returns the middleware function
func New(config ...Config) fiber.Handler {
var cfg Config
if len(config) == 0 {
cfg = defaultConfig
} else {
cfg = config[0]
if cfg.ValidatorFunc == nil {
cfg.ValidatorFunc = DefaultValidatorFunc
}
}
return func(c *fiber.Ctx) error {
if cfg.Skip != nil && cfg.Skip(c) {
return c.Next()
}
pass := cfg.ValidatorFunc(c, cfg)
if !pass {
return c.SendStatus(http.StatusUnauthorized)
}
return c.Next()
}
}