gofiber / fiber

⚡️ Express inspired web framework written in Go
https://gofiber.io
MIT License
33.82k stars 1.67k forks source link

How to use Middleware handler #2967

Closed vibhuh closed 6 months ago

vibhuh commented 6 months ago

Question Description

Middleware in the handler is not working as expected.

Code Snippet (optional)

package main

import (
    "crypto/sha256"
    "crypto/subtle"
    "fmt"

    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/fiber/v3/middleware/keyauth"
)

var (
    apiKey = "correct horse battery staple"
)

func validateAPIKey(c fiber.Ctx, key string) (bool, error) {
    hashedAPIKey := sha256.Sum256([]byte(apiKey))
    hashedKey := sha256.Sum256([]byte(key))

    if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 {
        fmt.Println("checkpoint: 14-April-2024: _____________--_______-______-    validateAPIKey   -______--_________--")
        return true, nil
    }
    fmt.Println("checkpoint: 14-April-2024: _____________--_______-______-    validateAPIKey false  -______--_________--")
    return false, keyauth.ErrMissingOrMalformedAPIKey
}

func AuthMiddleWare() fiber.Handler {
    fmt.Println("checkpoint: 14-April-2024: _____________--_______-______-    AuthMiddleWare   -______--_________--")
    return keyauth.New(keyauth.Config{
        //Next:      authFilter,
        KeyLookup: "cookie:access_token",
        Validator: validateAPIKey,
    })
}

func Profile(ctx fiber.Ctx) error {
    return ctx.Status(fiber.StatusOK).JSON(SuccessResponseStringData("User info"))
}

func SuccessResponseStringData(message string) *fiber.Map {
    return &fiber.Map{
        "status":  "success",
        "error":   false,
        "message": message,
    }
}

func main() {
    app := fiber.New()

    app.Get("/", func(c fiber.Ctx) error {
        return c.SendString("Welcome")
    })
    app.Get("/authenticated", AuthMiddleWare(), Profile)

    app.Listen(":3000")
}

Checklist:

welcome[bot] commented 6 months ago

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

gaby commented 6 months ago

@vibhuh This is a bug in the documentation,

// v2
func (app *App) Get(path string, handlers ...Handler) Router

// v3
func (app *App) Get(path string, handler Handler, middleware ...Handler) Router

Try changing this line: -> app.Get("/authenticated", AuthMiddleWare(), Profile) To this line: -> app.Get("/authenticated", Profile, AuthMiddleWare)

gaby commented 6 months ago

@vibhuh Does that solve your issue?