Coder Social home page Coder Social logo

Comments (10)

renanbastos93 avatar renanbastos93 commented on July 17, 2024 1

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.

renanbastos93 avatar renanbastos93 commented on July 17, 2024 1

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.

Borzoff avatar Borzoff commented on July 17, 2024 1

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.

renanbastos93 avatar renanbastos93 commented on July 17, 2024 1

@Borzoff no worries, regards.

from fiber.

welcome avatar welcome commented on July 17, 2024

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.

renanbastos93 avatar renanbastos93 commented on July 17, 2024

Which version do you use?

Maybe you method GetAdminStatus always returns true.

from fiber.

Borzoff avatar Borzoff commented on July 17, 2024

Which version do you use?

Maybe you method GetAdminStatus always returns true.

I checked with debug, it returns false. Fiber v2

from fiber.

renanbastos93 avatar renanbastos93 commented on July 17, 2024

Can you share more details about your code?
your platform is? fiber.Group?

from fiber.

Borzoff avatar Borzoff commented on July 17, 2024

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.

Borzoff avatar Borzoff commented on July 17, 2024

of course, i will do some tests.

Okay, thanks for the help!

from fiber.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.