forgejo-tickets/internal/middleware/csrf.go

31 lines
739 B
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/csrf"
)
func CSRF(secret []byte, secure bool) gin.HandlerFunc {
protect := csrf.Protect(
secret,
csrf.Secure(secure),
csrf.Path("/"),
csrf.SameSite(csrf.SameSiteLaxMode),
)
return func(c *gin.Context) {
// Wrap gin's handler chain as an http.Handler so gorilla/csrf can call it
protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Update gin's request in case csrf middleware modified it (added context values)
c.Request = r
c.Next()
})).ServeHTTP(c.Writer, c.Request)
// If csrf rejected the request, abort gin's chain
if c.Writer.Written() && c.Writer.Status() >= 400 {
c.Abort()
}
}
}