Refactors api key functionality
- API Key is now read from env file - API routes won't be set up if no API key is given via ENV file
This commit is contained in:
parent
86a7caa98f
commit
08c7c1f9fa
2 changed files with 22 additions and 9 deletions
|
|
@ -1,20 +1,31 @@
|
||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
"github.com/gofiber/fiber/v2/middleware/keyauth"
|
"github.com/gofiber/fiber/v2/middleware/keyauth"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Setup(app *fiber.App) {
|
func Setup(app *fiber.App) error {
|
||||||
|
apiKey := os.Getenv("API_KEY")
|
||||||
|
|
||||||
|
if apiKey == "" {
|
||||||
|
return errors.New("Could not read API_KEY from ENV file.")
|
||||||
|
}
|
||||||
|
|
||||||
api := app.Group("/api", keyauth.New(keyauth.Config{
|
api := app.Group("/api", keyauth.New(keyauth.Config{
|
||||||
SuccessHandler: successHandler,
|
SuccessHandler: successHandler,
|
||||||
ErrorHandler: errHandler,
|
ErrorHandler: errHandler,
|
||||||
KeyLookup: "header:x-api-key",
|
KeyLookup: "header:x-api-key",
|
||||||
ContextKey: "apiKey",
|
ContextKey: "apiKey",
|
||||||
Validator: validateAPIKey,
|
Validator: apiKeyValidator(apiKey),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
v1 := api.Group("/v1")
|
v1 := api.Group("/v1")
|
||||||
|
|
||||||
v1.Get("/users", FetchAllUsersHandler)
|
v1.Get("/users", FetchAllUsersHandler)
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,8 @@ var (
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func validateAPIKey(_ *fiber.Ctx, key string) (bool, error) {
|
func apiKeyValidator(apiKey string) func(*fiber.Ctx, string) (bool, error) {
|
||||||
|
return func(_ *fiber.Ctx, key string) (bool, error) {
|
||||||
hashedAPIKey := sha256.Sum256([]byte(apiKey))
|
hashedAPIKey := sha256.Sum256([]byte(apiKey))
|
||||||
hashedKey := sha256.Sum256([]byte(key))
|
hashedKey := sha256.Sum256([]byte(key))
|
||||||
|
|
||||||
|
|
@ -30,6 +31,7 @@ func validateAPIKey(_ *fiber.Ctx, key string) (bool, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
return false, keyauth.ErrMissingOrMalformedAPIKey
|
return false, keyauth.ErrMissingOrMalformedAPIKey
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func protectedRoutesFilter(ctx *fiber.Ctx) bool {
|
func protectedRoutesFilter(ctx *fiber.Ctx) bool {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue