api key auth added

This commit is contained in:
Ravi Prasad
2025-05-08 00:32:49 -05:00
parent 09d81c251a
commit 8c577b441c
17 changed files with 345 additions and 61 deletions
+35
View File
@@ -0,0 +1,35 @@
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
},
})
}