package handlers import ( "context" "database/sql" "html/template" "net/http" "github.com/gorilla/sessions" ) type PageData struct { Title string Navbar string LoggedIn bool ShowCookieBanner bool BasePath string StaticPath string CurrentURL string } type Config struct { DomainName string `json:"domain_name"` ThreadrDir string `json:"threadr_dir"` DBUsername string `json:"db_username"` DBPassword string `json:"db_password"` DBDatabase string `json:"db_database"` DBServerHost string `json:"db_svr_host"` } type App struct { DB *sql.DB Store *sessions.CookieStore Config *Config Tmpl *template.Template } func (app *App) SessionMW(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { session, err := app.Store.Get(r, "session-name") if err != nil { session = sessions.NewSession(app.Store, "session-name") } if _, ok := session.Values["user_id"].(int); ok { if session.Values["user_ip"] != r.RemoteAddr || session.Values["user_agent"] != r.UserAgent() { session.Values = make(map[interface{}]interface{}) session.Options.MaxAge = -1 session.Save(r, w) http.Redirect(w, r, app.Config.ThreadrDir+"/login/?error=session", http.StatusFound) return } ctx := context.WithValue(r.Context(), "session", session) r = r.WithContext(ctx) } else { ctx := context.WithValue(r.Context(), "session", session) r = r.WithContext(ctx) } next(w, r) } } func (app *App) RequireLoginMW(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { session := r.Context().Value("session").(*sessions.Session) if _, ok := session.Values["user_id"].(int); !ok { http.Redirect(w, r, app.Config.ThreadrDir+"/login/?error=session", http.StatusFound) return } next(w, r) } }