skeleton/internal/web/handlers.go

56 lines
1.3 KiB
Go
Raw Normal View History

2019-05-14 14:11:03 +02:00
package web
import (
"net/http"
"bitmask.me/skeleton/internal/app"
2019-12-14 07:28:33 +01:00
scs "github.com/alexedwards/scs/v2"
2019-08-22 00:48:27 +02:00
"github.com/gorilla/csrf"
2019-05-14 14:11:03 +02:00
)
2019-08-22 00:49:23 +02:00
type Config struct {
CSRFSecret string `env:"CSRF_TOKEN"`
}
2019-05-14 14:11:03 +02:00
type Handlers struct {
*app.App
session *scs.Session
2019-08-22 00:49:23 +02:00
Config *Config
2019-05-14 14:11:03 +02:00
}
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
}
2019-08-22 00:48:27 +02:00
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 {
2019-08-22 00:49:23 +02:00
if h.Config.CSRFSecret == "" {
// TODO FIXME: generate random
h.Config.CSRFSecret = "12345678901234567890123456789012"
}
2019-08-22 00:48:27 +02:00
return csrf.Protect(
2019-08-22 00:49:23 +02:00
[]byte(h.Config.CSRFSecret),
2019-08-22 00:48:27 +02:00
csrf.FieldName("authenticity_token"),
csrf.Secure(h.session.Cookie.Secure),
)
}
2019-05-14 14:11:03 +02:00
func (h *Handlers) LandingPageHandler(w http.ResponseWriter, r *http.Request) {
h.Templates().Get("landing.tmpl").Execute(w, nil)
}