summaryrefslogtreecommitdiff
path: root/srv/src/api/csrf.go
blob: 9717030ff00009d601e0e7494ce80dbfa2535e2f (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package api

import (
	"errors"
	"net/http"

	"github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutil"
)

const (
	csrfTokenCookieName = "csrf_token"
	csrfTokenHeaderName = "X-CSRF-Token"
)

func setCSRFMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "")

		if err != nil {
			apiutil.InternalServerError(rw, r, err)
			return

		} else if csrfTok == "" {
			http.SetCookie(rw, &http.Cookie{
				Name:   csrfTokenCookieName,
				Value:  apiutil.RandStr(32),
				Secure: true,
			})
		}

		h.ServeHTTP(rw, r)
	})
}

func checkCSRFMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "")

		if err != nil {
			apiutil.InternalServerError(rw, r, err)
			return
		}

		givenCSRFTok := r.Header.Get(csrfTokenHeaderName)
		if givenCSRFTok == "" {
			givenCSRFTok = r.FormValue("csrfToken")
		}

		if csrfTok == "" || givenCSRFTok != csrfTok {
			apiutil.BadRequest(rw, r, errors.New("invalid CSRF token"))
			return
		}

		h.ServeHTTP(rw, r)
	})
}