diff --git a/src/handlers/get.go b/src/handlers/get.go index b672a08..88174ca 100644 --- a/src/handlers/get.go +++ b/src/handlers/get.go @@ -2,7 +2,6 @@ package handlers import ( "github.com/gofiber/fiber/v2" - log "github.com/sirupsen/logrus" ) // Hello handler @@ -12,6 +11,18 @@ func (h Handlers) Hello(c *fiber.Ctx) error { // AccountGet handler func (h Handlers) AccountGet(c *fiber.Ctx) error { - log.WithFields(log.Fields{"accountID": c.Params("accountID")}).Debug("GETing account") - return c.SendString("Account ffs") + accountID := c.Params("accountID") + // logContext := log.WithFields(log.Fields{"accountID": accountID}) + + authErr := h.RequireAdminRoleOrAccountID(c, accountID) + if authErr != nil { + return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}}) + } + + account, accountErr := h.Db.AccountGet(accountID, "") + if accountErr != nil { + return c.Status(500).JSON([]ResJSONError{{Error: accountErr.Error()}}) + } + + return c.JSON(account) } diff --git a/src/handlers/helpers.go b/src/handlers/helpers.go index 7dc5d98..bf8ba72 100644 --- a/src/handlers/helpers.go +++ b/src/handlers/helpers.go @@ -113,3 +113,37 @@ func (h Handlers) RequireAdminRole(c *fiber.Ctx) error { return errors.New("No \"admin\" role found on account") } + +// RequireAdminRoleOrAccountID returns nil if no error is found +func (h Handlers) RequireAdminRoleOrAccountID(c *fiber.Ctx, accountID string) error { + headers := h.parseHeaders(c) + + if headers["Authorization"] == "" { + return errors.New("Authorization header is missing") + } + + claims, claimsErr := h.parseJWT(headers["Authorization"]) + if claimsErr != nil { + return claimsErr + } + + if claims.AccountID == accountID { + return nil + } + + if claims.AccountFields == nil { + return errors.New("AccountID does not match and account have no fields at all") + } + + if claims.AccountFields["role"] == nil { + return errors.New("AccountID does not match and account have no field named \"role\"") + } + + for _, role := range claims.AccountFields["role"] { + if role == "admin" { + return nil + } + } + + return errors.New("AccountID does not match and no \"admin\" role found on account") +}