Comments (10)
Can you share more details about your code? your platform is? fiber.Group?
platform is Group.
Routes:
api := app.Group("/api", logger.New()) api.Get("/", handler.HelloHandler) // user routes userRepo := repository.NewUserRepository(database) userService := service.NewUserService(userRepo) userHandler := handler.NewUserHandler(userService) user := api.Group("/user") user.Post("/", userHandler.CreateUserHandler) user.Get("/secret_key", middleware.Protected(), userHandler.UpdateUserSecretKey) user.Get("/:id", userHandler.GetUserHandler) // platform routes platformRepo := repository.NewPlatformRepository(database) platformService := service.NewPlatformService(platformRepo) platformHandler := handler.NewPlatformHandler(platformService) platform := api.Group("/platform") platform.Post("/", middleware.AdminMiddleware, platformHandler.AddPlatform)
This Handler is launched on post request:
func (h *PlatformHandler) AddPlatform(c *fiber.Ctx) error { platform := new(model.Platform) if err := c.BodyParser(platform); err != nil { return &fiber.Error{ Code: fiber.ErrBadRequest.Code, Message: βInvalid request, } } return h.PlatformService.AddPlatform(platform) }
I'm enabling Middleware so that there is an admin check. The admin check works, but the Handler still runs as if it is running in parallel.
of course, i will do some tests.
from fiber.
I have tested it now see code block at below.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
/**
* GetAdminStatus - Returns whether the given user ID is an admin or not.
*
* @param {string} userId - The user ID to check.
* @return {bool} - true if the user ID is an admin, false otherwise.
*/
func GetAdminStatus(userId string) bool {
/**
* The user ID is an admin if it is equal to the string "admin".
* This is a simple, naive check and should not be used in a production
* environment without being securely validated.
*/
return userId == "admin"
}
/**
* AdminMiddleware - A middleware that checks if the user is an admin.
*
* @param {fiber.Ctx} c - The context of the request.
* @return {error} - A fiber error.
*/
func AdminMiddleware(c *fiber.Ctx) error {
/**
* Get the authorization header from the request.
*/
authorization := c.Get("Authorization", "no-admin")
/**
* Check if the user is an admin.
*/
isAdmin := GetAdminStatus(authorization)
if !isAdmin {
/**
* If the user is not an admin, return a forbidden error.
*/
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": "Forbidden: Admins only",
})
} else {
/**
* If the user is an admin, continue to the next handler.
*/
return c.Next()
}
}
/**
* AddPlatform - Handles the POST request to the /platform endpoint.
*
* @param {fiber.Ctx} c - The context of the request.
* @return {error} - A fiber error.
*/
func AddPlatform(c *fiber.Ctx) error {
/**
* The /platform endpoint responds to POST requests with a 201 status code.
*/
return c.SendStatus(201)
}
/**
* main - The entry point of the application.
*
* @return {error} - A fiber error.
*/
func main() {
/**
* Create a new instance of the fiber router.
*/
app := fiber.New()
/**
* Create a group for the /api endpoint and add a middleware to log
* requests and responses.
*/
api := app.Group("/api", logger.New())
/**
* Create a group for the /platform endpoint.
*/
platform := api.Group("/platform")
/**
* Add a POST handler to the /platform endpoint that checks if the user
* is an admin and then responds with a 201 status code.
*/
platform.Post("/", AdminMiddleware, AddPlatform)
/**
* Start the server listening on port 3030.
*/
err := app.Listen(":3030")
if err != nil {
panic(err)
}
}
// curl -X POST "http://127.0.0.1:3030/api/platform" -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -H "Authorization: no-admin"
// {"error":"Forbidden: Admins only"}%
// curl -X POST "http://127.0.0.1:3030/api/platform" -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -H "Authorization: admin"
// Created%
As we can see here, I simulated based on your code above. Here I haven't found some error. Maybe you have a little bug in your project.
I tested using Go version: 1.22.3
Fiber V2 version: v2.52.4
from fiber.
I have tested it now see code block at below.
package main import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" ) /** * GetAdminStatus - Returns whether the given user ID is an admin or not. * * @param {string} userId - The user ID to check. * @return {bool} - true if the user ID is an admin, false otherwise. */ func GetAdminStatus(userId string) bool { /** * The user ID is an admin if it is equal to the string "admin". * This is a simple, naive check and should not be used in a production * environment without being securely validated. */ return userId == "admin" } /** * AdminMiddleware - A middleware that checks if the user is an admin. * * @param {fiber.Ctx} c - The context of the request. * @return {error} - A fiber error. */ func AdminMiddleware(c *fiber.Ctx) error { /** * Get the authorization header from the request. */ authorization := c.Get("Authorization", "no-admin") /** * Check if the user is an admin. */ isAdmin := GetAdminStatus(authorization) if !isAdmin { /** * If the user is not an admin, return a forbidden error. */ return c.Status(fiber.StatusForbidden).JSON(fiber.Map{ "error": "Forbidden: Admins only", }) } else { /** * If the user is an admin, continue to the next handler. */ return c.Next() } } /** * AddPlatform - Handles the POST request to the /platform endpoint. * * @param {fiber.Ctx} c - The context of the request. * @return {error} - A fiber error. */ func AddPlatform(c *fiber.Ctx) error { /** * The /platform endpoint responds to POST requests with a 201 status code. */ return c.SendStatus(201) } /** * main - The entry point of the application. * * @return {error} - A fiber error. */ func main() { /** * Create a new instance of the fiber router. */ app := fiber.New() /** * Create a group for the /api endpoint and add a middleware to log * requests and responses. */ api := app.Group("/api", logger.New()) /** * Create a group for the /platform endpoint. */ platform := api.Group("/platform") /** * Add a POST handler to the /platform endpoint that checks if the user * is an admin and then responds with a 201 status code. */ platform.Post("/", AdminMiddleware, AddPlatform) /** * Start the server listening on port 3030. */ err := app.Listen(":3030") if err != nil { panic(err) } } // curl -X POST "http://127.0.0.1:3030/api/platform" -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -H "Authorization: no-admin" // {"error":"Forbidden: Admins only"}% // curl -X POST "http://127.0.0.1:3030/api/platform" -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -H "Authorization: admin" // Created%As we can see here, I simulated based on your code above. Here I haven't found some error. Maybe you have a little bug in your project.
I tested using Go version:
1.22.3
Fiber V2 version:v2.52.4
Indeed, the problems were with me, and specifically with the database. I apologize for your time. Thank you!
from fiber.
@Borzoff no worries, regards.
from fiber.
Thanks for opening your first issue here! π Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord
from fiber.
Which version do you use?
Maybe you method GetAdminStatus
always returns true.
from fiber.
Which version do you use?
Maybe you method
GetAdminStatus
always returns true.
I checked with debug, it returns false. Fiber v2
from fiber.
Can you share more details about your code?
your platform is? fiber.Group?
from fiber.
Can you share more details about your code? your platform is? fiber.Group?
platform is Group.
Routes:
api := app.Group("/api", logger.New())
api.Get("/", handler.HelloHandler)
// user routes
userRepo := repository.NewUserRepository(database)
userService := service.NewUserService(userRepo)
userHandler := handler.NewUserHandler(userService)
user := api.Group("/user")
user.Post("/", userHandler.CreateUserHandler)
user.Get("/secret_key", middleware.Protected(), userHandler.UpdateUserSecretKey)
user.Get("/:id", userHandler.GetUserHandler)
// platform routes
platformRepo := repository.NewPlatformRepository(database)
platformService := service.NewPlatformService(platformRepo)
platformHandler := handler.NewPlatformHandler(platformService)
platform := api.Group("/platform")
platform.Post("/", middleware.AdminMiddleware, platformHandler.AddPlatform)
This Handler is launched on post request:
func (h *PlatformHandler) AddPlatform(c *fiber.Ctx) error {
platform := new(model.Platform)
if err := c.BodyParser(platform); err != nil {
return &fiber.Error{
Code: fiber.ErrBadRequest.Code,
Message: βInvalid request,
}
}
return h.PlatformService.AddPlatform(platform)
}
I'm enabling Middleware so that there is an admin check. The admin check works, but the Handler still runs as if it is running in parallel.
from fiber.
of course, i will do some tests.
Okay, thanks for the help!
from fiber.
Related Issues (20)
- π [Bug]: incorrect selection of the error handler if one of the sub apps is mounted on "/" HOT 2
- π€ [Question]: gofiber v3 rc release date? HOT 2
- π [Proposal]: v3 auto binding HOT 2
- π€ [Question]: Does fiber v3's Request not have the function of adding files to FormData? HOT 3
- π€ [Question]: Is `fiber.Ctx` thread safe? If not, is that documented? HOT 8
- π€ [Question]: A new Redis key is created every time the url is accessed. Is this normal? HOT 5
- [question]: Why do long requests block each other? HOT 15
- π [Bug]: Limiter middleware with pebble storage does not deduct remaining limit
- π [Proposal]: Improving route matching and url parsing performance with Ada Url HOT 7
- Improve Error Handling in CSRF Middleware Storage
- π€ [Question]: v3 when ready for production HOT 1
- π [Bug]: Unclear "json: invalid use of ,string struct tag, trying to unmarshal unquoted value into uint64" HOT 9
- π€ [Question]: Cache Next is not called when KeyGenerator is Defined HOT 6
- π [Bug]: v3 Flash Message with redirect is not working HOT 3
- π [Proposal]: Upgrade fiber.NewError() for error handle HOT 4
- π [Proposal]: Reduce memory usage for "prefork" mode of the master process HOT 2
- π§Ή [Maintenance]: Add Parallel Benchmarks
- π€ [Question]: zero allocation - why is this any different from how Chi or others behave? Can you document an example of what you mean? HOT 8
- π€ [Question]: FX with Fiber graceful shutdown Failed to stop cleanly: context deadline exceeded HOT 15
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fiber.