diff --git a/handler/middlewares.go b/handler/middlewares.go index fa4e57e..b0b616c 100644 --- a/handler/middlewares.go +++ b/handler/middlewares.go @@ -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() +} diff --git a/handler/routes.go b/handler/routes.go index 9d46b11..c6aa7fe 100644 --- a/handler/routes.go +++ b/handler/routes.go @@ -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) } diff --git a/internal/repo/prober.go b/internal/repo/prober.go index cc6dc55..f5eae34 100644 --- a/internal/repo/prober.go +++ b/internal/repo/prober.go @@ -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 +}