Files
NBA_Go/utils/middleware/api_key_middleware.go
T
2025-05-08 00:32:49 -05:00

35 lines
954 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"crypto/subtle"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/keyauth"
"github.com/nprasad2077/NBA_Go/models"
"github.com/nprasad2077/NBA_Go/utils/security"
"gorm.io/gorm"
)
// APIKeyAuth returns a Fiber Handler that validates XAPIKey
func APIKeyAuth(db *gorm.DB) fiber.Handler {
return keyauth.New(keyauth.Config{
KeyLookup: "header:X-API-Key",
Validator: func(c *fiber.Ctx, rawKey string) (bool, error) {
var rec models.APIKey
hash := security.HashKey(rawKey)
err := db.
Where("hash = ? AND revoked = FALSE", hash).
First(&rec).Error
if err != nil {
return false, keyauth.ErrMissingOrMalformedAPIKey
}
if subtle.ConstantTimeCompare(rec.Hash, hash) != 1 {
return false, keyauth.ErrMissingOrMalformedAPIKey
}
// put the key ID on the context for ratelimiting or logging later
c.Locals("apiKeyID", rec.ID)
return true, nil
},
})
}