From 0357839d3fe7abf84ad91ab964dca7d73113488b Mon Sep 17 00:00:00 2001 From: cp-20 Date: Fri, 20 Dec 2024 10:46:12 +0900 Subject: [PATCH] =?UTF-8?q?getAuthorizedUser=20=E3=81=AE=E3=83=AA=E3=83=95?= =?UTF-8?q?=E3=82=A1=E3=82=AF=E3=82=BF=E3=83=AA=E3=83=B3=E3=82=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router/comments.go | 5 ++++- router/common.go | 5 +++++ router/items.go | 9 ++++++--- router/middleware.go | 8 ++++++-- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/router/comments.go b/router/comments.go index 20165d1..79fba6b 100644 --- a/router/comments.go +++ b/router/comments.go @@ -25,7 +25,10 @@ func PostComment(c echo.Context) error { return invalidRequest(c, err) } - me := getAuthorizedUser(c) + me, err := getAuthorizedUser(c) + if err != nil { + return unauthorizedRequest(c, err) + } var body PostCommentBody if err := c.Bind(&body); err != nil { diff --git a/router/common.go b/router/common.go index af73ac1..dcc8918 100644 --- a/router/common.go +++ b/router/common.go @@ -6,6 +6,11 @@ import ( "github.com/labstack/echo/v4" ) +func unauthorizedRequest(c echo.Context, err error) error { + c.Logger().Infof("unauthorized request on %s: %w", c.Path(), err.Error()) + return c.String(http.StatusUnauthorized, "認証に失敗しました") +} + func invalidRequest(c echo.Context, err error) error { c.Logger().Infof("invalid request on %s: %w", c.Path(), err.Error()) return c.String(http.StatusBadRequest, "リクエストデータの処理に失敗しました") diff --git a/router/items.go b/router/items.go index f91a179..85dc850 100644 --- a/router/items.go +++ b/router/items.go @@ -58,10 +58,13 @@ func parseGetItemsParams(c echo.Context) (model.GetItemsBody, error) { // PostItems POST /items func PostItems(c echo.Context) error { - me := getAuthorizedUser(c) - items := []model.RequestPostItemsBody{} - err := c.Bind(&items) + me, err := getAuthorizedUser(c) if err != nil { + return unauthorizedRequest(c, err) + } + + items := []model.RequestPostItemsBody{} + if err := c.Bind(&items); err != nil { return invalidRequest(c, err) } diff --git a/router/middleware.go b/router/middleware.go index a6bf2ea..f0c8545 100644 --- a/router/middleware.go +++ b/router/middleware.go @@ -41,6 +41,10 @@ func CreateUserProvider(debugUserName string) *UserProvider { }} } -func getAuthorizedUser(c echo.Context) string { - return c.Get(userProviderKey).(string) +func getAuthorizedUser(c echo.Context) (string, error) { + user, ok := c.Get(userProviderKey).(string) + if !ok { + return "", errors.New("認証に失敗しました") + } + return user, nil }