package web import ( "net/http" "bitmask.me/skeleton/internal/app" scs "github.com/alexedwards/scs/v2" "github.com/gorilla/csrf" ) type Config struct { CSRFSecret string `env:"CSRF_TOKEN"` } type Handlers struct { *app.App session *scs.Session Config *Config } func NewHandlers(app *app.App) *Handlers { h := &Handlers{App: app} h.session = scs.NewSession() h.session.Cookie.Persist = false h.session.Cookie.Secure = false return h } func (h *Handlers) Session() *scs.Session { return h.session } func (h *Handlers) commonRenderContext(r *http.Request) map[string]interface{} { return map[string]interface{}{ csrf.TemplateTag: csrf.TemplateField(r), "Username": h.Session().GetString(r.Context(), SessKeyUserName), "UserID": h.Session().GetString(r.Context(), SessKeyUserID), } } func (h *Handlers) CSRF() func(http.Handler) http.Handler { if h.Config.CSRFSecret == "" { // TODO FIXME: generate random h.Config.CSRFSecret = "12345678901234567890123456789012" } return csrf.Protect( []byte(h.Config.CSRFSecret), csrf.FieldName("authenticity_token"), csrf.Secure(h.session.Cookie.Secure), ) } func (h *Handlers) LandingPageHandler(w http.ResponseWriter, r *http.Request) { h.Templates().Get("landing.tmpl").Execute(w, nil) }