mw-csrf: github.com/gobuffalo/mw-csrf Index | Files

package csrf

import "github.com/gobuffalo/mw-csrf"

Index

Package Files

csrf.go

Variables

var (
    // ErrNoReferer is returned when a HTTPS request provides an empty Referer
    // header.
    ErrNoReferer = errors.New("referer not supplied")
    // ErrBadReferer is returned when the scheme & host in the URL do not match
    // the supplied Referer header.
    ErrBadReferer = errors.New("referer invalid")
    // ErrNoToken is returned if no CSRF token is supplied in the request.
    ErrNoToken = errors.New("CSRF token not found in request")
    // ErrBadToken is returned if the CSRF token in the request does not match
    // the token in the session, or is otherwise malformed.
    ErrBadToken = errors.New("CSRF token invalid")
)
var New = func(next buffalo.Handler) buffalo.Handler {
    return func(c buffalo.Context) error {

        if envy.Get("GO_ENV", "development") == "test" {
            c.Set(tokenKey, "test")
            return next(c)
        }

        req := c.Request()

        ct := req.Header.Get("Content-Type")
        if len(ct) == 0 {
            ct = req.Header.Get("Accept")
        }

        if ct != "" && !contains(htmlTypes, ct) {
            return next(c)
        }

        var realToken []byte
        var err error
        rawRealToken := c.Session().Get(tokenKey)

        if rawRealToken == nil || len(rawRealToken.([]byte)) != tokenLength {

            realToken, err = generateRandomBytes(tokenLength)
            if err != nil {
                return err
            }

            c.Session().Set(tokenKey, realToken)
        } else {
            realToken = rawRealToken.([]byte)
        }

        c.Set(fieldName, mask(realToken, req))

        if !contains(safeMethods, req.Method) {

            if req.URL.Scheme == "https" {

                referer, err := url.Parse(req.Referer())
                if err != nil || referer.String() == "" {
                    return ErrNoReferer
                }

                if !sameOrigin(req.URL, referer) {
                    return ErrBadReferer
                }
            }

            requestToken := unmask(requestCSRFToken(req))

            if requestToken == nil {
                return ErrNoToken
            }

            if !compareTokens(requestToken, realToken) {
                return ErrBadToken
            }
        }

        return next(c)
    }
}

New enable CSRF protection on routes using this middleware. This middleware is adapted from gorilla/csrf

Package csrf imports 9 packages (graph) and is imported by 7 packages. Updated 2019-03-06. Refresh now. Tools for package owners.