Skip to content

Instantly share code, notes, and snippets.

@saada
Created June 6, 2024 03:26
Show Gist options
  • Save saada/bb018cf242b1cf60611f1d62f53f3c83 to your computer and use it in GitHub Desktop.
Save saada/bb018cf242b1cf60611f1d62f53f3c83 to your computer and use it in GitHub Desktop.
Go echo and templ context passing middleware for csrf borrowed from https://jeffcaldwell.is/blog/using-echo-context-with-templ-components
package custommiddleware
import (
"context"
"github.com/labstack/echo/v4"
)
// extend echo.Context
type contextValue struct {
echo.Context
}
func (c contextValue) Get(key string) interface{} {
// grab value from echo.Context
val := c.Context.Get(key)
// if it's not nil, return it
if val != nil {
return val
}
// otherwise, return Request.Context
return c.Request().Context().Value(key)
}
func (c contextValue) Set(key string, val interface{}) {
// we're replacing the whole Request in echo.Context
// with a copied request that has the updated context value
c.SetRequest(
c.Request().WithContext(
context.WithValue(c.Request().Context(), key, val),
),
)
}
func ContextValueMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// this is just an echo.HandlerFunc
return func(c echo.Context) error {
// instead of passing next(c) as you usually would,
// you return it with the extended version
return next(contextValue{c})
}
}
package main
func main() {
e := echo.New()
// before any other middleware
e.Use(custommiddleware.ContextValueMiddleware)
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
Skipper: middleware.DefaultSkipper,
TokenLength: 32,
ContextKey: "csrf",
CookieName: "_csrf",
CookieMaxAge: 86400,
CookieSameSite: http.SameSiteNoneMode,
CookieHTTPOnly: true,
CookieSecure: PROD,
TokenLookup: "form:csrf",
CookiePath: "/",
}))
// ...
}
func getCSRF(c context.Context) string {
csrfToken := c.Value("csrf")
if csrfToken != nil {
return csrfToken.(string)
}
return ""
}
templ CSRF() {
<input type="hidden" name="csrf" value={ getCSRF(ctx) }/>
}
// use by doing @CSRF() in any view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment