Skip to content

Commit

Permalink
feat: move middleware get user to routes
Browse files Browse the repository at this point in the history
  • Loading branch information
JingYiJun committed Nov 10, 2023
1 parent a2c3e8c commit 0c2bda5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
19 changes: 19 additions & 0 deletions apis/routes.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package apis

import (
"github.com/opentreehole/go-common"

"treehole_next/apis/division"
"treehole_next/apis/favourite"
"treehole_next/apis/floor"
Expand All @@ -11,7 +13,9 @@ import (
"treehole_next/apis/subscription"
"treehole_next/apis/tag"
"treehole_next/apis/user"
"treehole_next/config"
_ "treehole_next/docs"
"treehole_next/models"

"github.com/gofiber/fiber/v2"
fiberSwagger "github.com/swaggo/fiber-swagger"
Expand All @@ -32,6 +36,7 @@ func RegisterRoutes(app *fiber.App) {

group := app.Group("/api")
group.Get("/", Index)
group.Use(MiddlewareGetUser)
division.RegisterRoutes(group)
tag.RegisterRoutes(group)
hole.RegisterRoutes(group)
Expand All @@ -43,3 +48,17 @@ func RegisterRoutes(app *fiber.App) {
user.RegisterRoutes(group)
message.RegisterRoutes(group)
}

func MiddlewareGetUser(c *fiber.Ctx) error {
userObject, err := models.GetUser(c)
if err != nil {
return err
}
c.Locals("user", userObject)
if config.Config.AdminOnly {
if !userObject.IsAdmin {
return common.Forbidden()
}
}
return c.Next()
}
16 changes: 0 additions & 16 deletions bootstrap/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,7 @@ func registerMiddlewares(app *fiber.App) {
if config.Config.Mode != "bench" {
app.Use(common.MiddlewareCustomLogger)
}
app.Use(MiddlewareGetUser)
app.Use(pprof.New())

}

func MiddlewareGetUser(c *fiber.Ctx) error {
user, err := models.GetUser(c)
if err != nil {
return err
}
c.Locals("user", user)
if config.Config.AdminOnly {
if !user.IsAdmin {
return common.Forbidden()
}
}
return c.Next()
}

func startTasks() context.CancelFunc {
Expand Down

0 comments on commit 0c2bda5

Please sign in to comment.