Add prober API key check middleware

This commit is contained in:
ditatompel 2024-05-04 19:52:22 +07:00
parent 6430e37548
commit cee2b4341b
No known key found for this signature in database
GPG key ID: 31D3D06D77950979
3 changed files with 37 additions and 1 deletions

View file

@ -1,6 +1,9 @@
package handler
import (
"github.com/ditatompel/xmr-nodes/internal/database"
"github.com/ditatompel/xmr-nodes/internal/repo"
"github.com/gofiber/fiber/v2"
)
@ -16,3 +19,28 @@ func CookieProtected(c *fiber.Ctx) error {
return c.Next()
}
func CheckProber(c *fiber.Ctx) error {
key := c.Get("X-Prober-Api-Key")
if key == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"status": "error",
"message": "Unauthorized",
"data": nil,
})
}
proberRepo := repo.NewProberRepo(database.GetDB())
prober, err := proberRepo.CheckApi(key)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"status": "error",
"message": "No API key match",
"data": nil,
})
}
c.Locals("prober", prober)
return c.Next()
}

View file

@ -16,6 +16,6 @@ func V1Api(app *fiber.App) {
v1.Post("/prober", Prober)
v1.Get("/nodes", MoneroNodes)
v1.Post("/nodes", AddNode)
v1.Get("/job", GiveJob)
v1.Get("/job", CheckProber, GiveJob)
v1.Get("/crons", Crons)
}

View file

@ -13,6 +13,7 @@ import (
type ProberRepository interface {
AddProber(name string) error
Probers(q ProbersQueryParams) (Probers, error)
CheckApi(key string) (Prober, error)
}
type ProberRepo struct {
@ -116,3 +117,10 @@ func (repo *ProberRepo) Probers(q ProbersQueryParams) (Probers, error) {
}
return probers, nil
}
func (repo *ProberRepo) CheckApi(key string) (Prober, error) {
prober := Prober{}
query := `SELECT id, name, api_key, last_submit_ts FROM tbl_prober WHERE api_key = ? LIMIT 1`
err := repo.db.QueryRow(query, key).Scan(&prober.Id, &prober.Name, &prober.ApiKey, &prober.LastSubmitTs)
return prober, err
}