Go Fiber Middleware cannot find route if I chack if user is superuser

99 Views Asked by At

First I'm checking if user is loggedin using the AuthMiddleware which is also called from the first if block. Later, I'm trying to allow all the users from middleware that has superuser permission as follows.

func HasPermissionMiddleware(expectedPermissions ...string) fiber.Handler {
    return func(c *fiber.Ctx) error {
        if authError := AuthMiddleware()(c); authError != nil {
            return authError
        }

        user := c.Locals("user").(models.Users)
        if !user.HasChangedInitPassword {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Please change the initial password first"})
        }
        if !user.IsSuperuser {
            return c.Next()
        }
        if !HasPermissions(expectedPermissions, user.Permissions) {
            joined := strings.Join(expectedPermissions, ", ")
            log.Printf("Requires %s access", joined)
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Insufficiant permission access"})
        }
        return c.Next()
    }
}

and use it as with my routes as

func UserManagementRoutes(app *fiber.App) {
    router := app.Group("api/users")

    router.Get("/", middlewares.AuthMiddleware(), controllers.GetUsersListHandler)
    ...
    router.Get("/permissions/:id", middlewares.HasPermissionMiddleware("permissions_view"), controllers.AllPermissionOfUserHandler)
    ...
}

When I hit the details api postman throws the follwoing error:

Cannot GET /api/users/1

But If I remove if user.IsSuperuser{} block from middleware it do response successfully. It seems like, if i return something from inside that block it throws the error.

0

There are 0 best solutions below