fiber/middleware/csrf/extractors.go
Gusted 7b7dcf29f7
♻️ Tidy up the codebase (#1613)
* run gofmt

* add t.Helper()

* Simplify assigns

* Simplify make operation

* Remove unused field in struct

* Fix typo

* Run gofumpt ./

* Consistent spacing

* len(...) can never be negative

* Use ReplaceAll

* Simplify operation

* Remove deadcode

* Fix typo

* Tidy up `} else { if ...`

* Fix AssertEqual

* Remove t.Helper() to fix go1.14.15
2021-11-05 08:00:03 +01:00

71 lines
1.9 KiB
Go

package csrf
import (
"errors"
"github.com/gofiber/fiber/v2"
)
var (
errMissingHeader = errors.New("missing csrf token in header")
errMissingQuery = errors.New("missing csrf token in query")
errMissingParam = errors.New("missing csrf token in param")
errMissingForm = errors.New("missing csrf token in form")
errMissingCookie = errors.New("missing csrf token in cookie")
)
// csrfFromParam returns a function that extracts token from the url param string.
func csrfFromParam(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Params(param)
if token == "" {
return "", errMissingParam
}
return token, nil
}
}
// csrfFromForm returns a function that extracts a token from a multipart-form.
func csrfFromForm(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.FormValue(param)
if token == "" {
return "", errMissingForm
}
return token, nil
}
}
// csrfFromCookie returns a function that extracts token from the cookie header.
func csrfFromCookie(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Cookies(param)
if token == "" {
return "", errMissingCookie
}
return token, nil
}
}
// csrfFromHeader returns a function that extracts token from the request header.
func csrfFromHeader(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Get(param)
if token == "" {
return "", errMissingHeader
}
return token, nil
}
}
// csrfFromQuery returns a function that extracts token from the query string.
func csrfFromQuery(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Query(param)
if token == "" {
return "", errMissingQuery
}
return token, nil
}
}