Created
June 6, 2024 03:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "/", | |
})) | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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