|
|
|
@ -2,23 +2,38 @@ package http |
|
|
|
|
|
|
|
|
|
import ( |
|
|
|
|
"errors" |
|
|
|
|
"net" |
|
|
|
|
"net/http" |
|
|
|
|
"net/url" |
|
|
|
|
|
|
|
|
|
"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil" |
|
|
|
|
) |
|
|
|
|
|
|
|
|
|
func (a *api) checkCSRFMiddleware(h http.Handler) http.Handler { |
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
|
|
|
|
func checkCSRF(r *http.Request, publicURL *url.URL) error { |
|
|
|
|
|
|
|
|
|
if ipStr, _, err := net.SplitHostPort(r.Host); err == nil { |
|
|
|
|
if ip := net.ParseIP(ipStr); ip != nil && ip.IsLoopback() { |
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
refererURL, err := url.Parse(r.Referer()) |
|
|
|
|
if err != nil { |
|
|
|
|
apiutil.BadRequest(rw, r, errors.New("invalid Referer")) |
|
|
|
|
return |
|
|
|
|
return errors.New("invalid Referer") |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
if refererURL.Scheme != a.params.PublicURL.Scheme || |
|
|
|
|
refererURL.Host != a.params.PublicURL.Host { |
|
|
|
|
if refererURL.Scheme != publicURL.Scheme || |
|
|
|
|
refererURL.Host != publicURL.Host { |
|
|
|
|
return errors.New("invalid Referer") |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
func (a *api) checkCSRFMiddleware(h http.Handler) http.Handler { |
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
|
|
|
|
|
|
|
|
|
if err := checkCSRF(r, a.params.PublicURL); err != nil { |
|
|
|
|
apiutil.BadRequest(rw, r, errors.New("invalid Referer")) |
|
|
|
|
return |
|
|
|
|
} |
|
|
|
|