summaryrefslogtreecommitdiff
path: root/src/http/csrf.go
blob: 707aac41759b5ce69e6dad36b95523594f2ba748 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package http

import (
	"errors"
	"net"
	"net/http"
	"net/url"

	"dev.mediocregopher.com/mediocre-blog.git/src/http/apiutil"
)

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 {
		return errors.New("invalid Referer")
	}

	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
		}

		h.ServeHTTP(rw, r)
	})
}