Skip to content

Commit

Permalink
getAuthorizedUser のリファクタリング
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-20 committed Dec 20, 2024
1 parent db22735 commit 0357839
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 6 deletions.
5 changes: 4 additions & 1 deletion router/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions router/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, "リクエストデータの処理に失敗しました")
Expand Down
9 changes: 6 additions & 3 deletions router/items.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
8 changes: 6 additions & 2 deletions router/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 0357839

Please sign in to comment.