diff --git a/api/api.go b/api/api.go index 5b32555..f74d34c 100644 --- a/api/api.go +++ b/api/api.go @@ -1,6 +1,7 @@ package api import ( + "github.com/BarTar213/notificator/middleware" "github.com/BarTar213/notificator/models" "log" "net/http" @@ -95,6 +96,8 @@ func NewApi(options ...func(api *Api)) *Api { notifications := a.Router.Group("/notifications") { + notifications.Use(middleware.CheckAccount()) + notifications.GET("/:id", nh.GetNotification) notifications.GET("", nh.ListNotifications) notifications.PATCH("/:id", nh.UpdateNotification) diff --git a/api/utils.go b/api/utils.go index 73f8ae1..03297c2 100644 --- a/api/utils.go +++ b/api/utils.go @@ -54,3 +54,10 @@ func (h *TemplateHandlers) returnTemplate(t *models.Template) { t.Reset() h.templatePool.Put(t) } + +//returns account information for user +//should be only used in handler functions that using middleware CheckAccount function +func GetAccount(c *gin.Context) *models.Account { + account := c.Keys["account"].(models.Account) + return &account +} diff --git a/middleware/account.go b/middleware/account.go new file mode 100644 index 0000000..51137b1 --- /dev/null +++ b/middleware/account.go @@ -0,0 +1,20 @@ +package middleware + +import ( + "github.com/BarTar213/notificator/models" + "github.com/gin-gonic/gin" + "net/http" +) + +func CheckAccount() gin.HandlerFunc { + return func(c *gin.Context) { + account := models.Account{} + err := c.ShouldBindHeader(&account) + if err != nil { + c.AbortWithStatusJSON(http.StatusForbidden, models.Response{Error: "invalid account headers"}) + return + } + c.Set("account", account) + c.Next() + } +} diff --git a/utils/utils.go b/utils/utils.go index 1b86381..65ba0be 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -3,4 +3,3 @@ package utils const ( EmptyStr = "" ) -