mediocre-blog/srv/src/http/csrf.go

60 lines
1.2 KiB
Go
Raw Normal View History

2022-05-20 17:17:31 +00:00
package http
2021-08-30 04:15:58 +00:00
import (
"errors"
"net/http"
2022-05-20 17:17:31 +00:00
"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil"
2021-08-30 04:15:58 +00:00
)
const (
csrfTokenCookieName = "csrf_token"
csrfTokenHeaderName = "X-CSRF-Token"
csrfTokenFormName = "csrfToken"
2021-08-30 04:15:58 +00:00
)
func setCSRFMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "")
2021-08-30 04:15:58 +00:00
if err != nil {
apiutil.InternalServerError(rw, r, err)
2021-08-30 04:15:58 +00:00
return
} else if csrfTok == "" {
http.SetCookie(rw, &http.Cookie{
Name: csrfTokenCookieName,
Value: apiutil.RandStr(32),
2021-08-30 04:15:58 +00:00
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, "")
2021-08-30 04:15:58 +00:00
if err != nil {
apiutil.InternalServerError(rw, r, err)
2021-08-30 04:15:58 +00:00
return
}
givenCSRFTok := r.Header.Get(csrfTokenHeaderName)
if givenCSRFTok == "" {
givenCSRFTok = r.FormValue(csrfTokenFormName)
}
2021-08-30 04:15:58 +00:00
if csrfTok == "" || givenCSRFTok != csrfTok {
apiutil.BadRequest(rw, r, errors.New("invalid CSRF token"))
2021-08-30 04:15:58 +00:00
return
}
h.ServeHTTP(rw, r)
})
}