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
+9 -4
View File
@@ -1,16 +1,21 @@
package utils
import (
"context"
"errors"
"io/ioutil"
"io"
"net/http"
"time"
)
func GetJSON(url string) ([]byte, error) {
client := &http.Client{Timeout: 10 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.Get(url)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
@@ -20,7 +25,7 @@ func GetJSON(url string) ([]byte, error) {
return nil, errors.New("received non-200 response: " + resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
+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
},
})
}
+23
View File
@@ -0,0 +1,23 @@
package security
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
)
// GenerateRawKey returns a 32byte cryptographicallyrandom string
func GenerateRawKey() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// HashKey returns the SHA256 hash suitable for storage.
func HashKey(raw string) []byte {
h := sha256.Sum256([]byte(raw))
return h[:]
}