summaryrefslogtreecommitdiff
path: root/srv/api/csrf.go
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2021-08-29 22:15:58 -0600
committerBrian Picciano <mediocregopher@gmail.com>2021-08-29 22:15:58 -0600
commit15ae483fadbd136acefcd602b2f2ac5a83165c73 (patch)
tree0f25ed1dd81e4fffeed6055dd02da48a567c8fb2 /srv/api/csrf.go
parent5746a510fc569fd464e46b646d4979a976ad769b (diff)
add CSRF checking
Diffstat (limited to 'srv/api/csrf.go')
-rw-r--r--srv/api/csrf.go50
1 files changed, 50 insertions, 0 deletions
diff --git a/srv/api/csrf.go b/srv/api/csrf.go
new file mode 100644
index 0000000..d705adb
--- /dev/null
+++ b/srv/api/csrf.go
@@ -0,0 +1,50 @@
+package api
+
+import (
+ "errors"
+ "net/http"
+)
+
+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 := getCookie(r, csrfTokenCookieName, "")
+
+ if err != nil {
+ internalServerError(rw, r, err)
+ return
+
+ } else if csrfTok == "" {
+ http.SetCookie(rw, &http.Cookie{
+ Name: csrfTokenCookieName,
+ Value: 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 := getCookie(r, csrfTokenCookieName, "")
+
+ if err != nil {
+ internalServerError(rw, r, err)
+ return
+
+ } else if csrfTok == "" || r.Header.Get(csrfTokenHeaderName) != csrfTok {
+ badRequest(rw, r, errors.New("invalid CSRF token"))
+ return
+ }
+
+ h.ServeHTTP(rw, r)
+ })
+}