summaryrefslogtreecommitdiff
path: root/csrf.go
blob: 45398252e00bf9ad24092766f0362117b0b3f3a9 (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
package main

import (
	"html/template"
	"net/http"

	"github.com/gorilla/csrf"
	"github.com/gorilla/securecookie"
)

func csrfHandler(next http.Handler) http.Handler {
	return csrf.Protect(
		securecookie.GenerateRandomKey(32),
		csrf.SameSite(csrf.SameSiteStrictMode),
		csrf.FieldName("csrf.csrffield"), // should match the structure in `Csrf`
	)(next)
}

// Csrf handles the CSRF data for a form.
// Include it verbatim and then use `{{.CsrfField}}` in templates.
type Csrf struct {
	CsrfField template.HTML `form:"-" schema:"-"`
}

func (c *Csrf) SetCsrfField(r *http.Request) {
	c.CsrfField = csrf.TemplateField(r)
}

type WithCsrf interface {
	SetCsrfField(r *http.Request)
}