Created
November 13, 2017 16:35
-
-
Save ansrivas/4604d16a6f4d88eee657659d458080bc to your computer and use it in GitHub Desktop.
csrf template validation using pongo2, chi and gorilla/csrf
This file contains hidden or 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 | |
| import ( | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "os" | |
| "os/signal" | |
| "syscall" | |
| "time" | |
| pongo "github.com/flosch/pongo2" | |
| "github.com/go-chi/chi" | |
| "github.com/go-chi/chi/middleware" | |
| "github.com/gorilla/csrf" | |
| ) | |
| var form = ` | |
| <html> | |
| <head> | |
| <title>Sign Up!</title> | |
| </head> | |
| <body> | |
| <form method="POST" action="/" accept-charset="UTF-8"> | |
| <input type="text" name="name"> | |
| <input type="text" name="email"> | |
| <input type="hidden" name="myfield" value={{tokenValue}}> | |
| <input type="submit" value="Sign up!"> | |
| </form> | |
| </body> | |
| </html> | |
| ` | |
| var t = pongo.Must(pongo.FromString(form)) | |
| func main() { | |
| r := chi.NewRouter() | |
| csrfMiddleware := | |
| csrf.Protect([]byte("32-byte-long-auth-key"), | |
| csrf.Secure(false), | |
| csrf.FieldName("myfield")) | |
| r.Use(func(next http.Handler) http.Handler { | |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains") | |
| next.ServeHTTP(w, r) | |
| }) | |
| }, | |
| middleware.Recoverer, | |
| middleware.RequestID, | |
| middleware.RealIP, | |
| middleware.Logger, | |
| middleware.StripSlashes, | |
| csrfMiddleware) | |
| r.Get("/", ShowSignupForm) | |
| r.Post("/", SubmitSignupForm) | |
| // config and init server | |
| addr := "127.0.0.1:8080" | |
| s := &http.Server{ | |
| Addr: addr, | |
| Handler: r, | |
| ReadTimeout: 10 * time.Second, | |
| WriteTimeout: 10 * time.Second, | |
| MaxHeaderBytes: 1 << 20, | |
| } | |
| errc := make(chan error) | |
| go func() { | |
| c := make(chan os.Signal, 2) | |
| signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) | |
| errc <- fmt.Errorf("%s", <-c) | |
| }() | |
| // HTTP transport. | |
| go func() { | |
| fmt.Printf("server listening on http://%s", addr) | |
| errc <- s.ListenAndServe() | |
| }() | |
| // Run! | |
| log.Fatalln("exit", <-errc) | |
| } | |
| func ShowSignupForm(w http.ResponseWriter, r *http.Request) { | |
| err := t.ExecuteWriter(pongo.Context{"tokenValue": csrf.Token(r)}, w) | |
| if err != nil { | |
| http.Error(w, err.Error(), http.StatusInternalServerError) | |
| return | |
| } | |
| } | |
| func SubmitSignupForm(w http.ResponseWriter, r *http.Request) { | |
| fmt.Fprintf(w, "Successful") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment