package middleware // ToDo: will no doubt need to fix as now using new session not the olf gorilla one import ( "net/http" "time" httpHelpers "synlotto-website/internal/helpers/http" "synlotto-website/internal/platform/constants" ) func Auth(required bool) func(http.HandlerFunc) http.HandlerFunc { return func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { session, _ := httpHelpers.GetSession(w, r) _, ok := session.Values["user_id"].(int) if required && !ok { http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } if ok { last, hasLast := session.Values["last_activity"].(time.Time) if hasLast && time.Since(last) > constants.SessionDuration { session.Options.MaxAge = -1 session.Save(r, w) newSession, _ := httpHelpers.GetSession(w, r) newSession.Values["flash"] = "Your session has timed out." newSession.Save(r, w) http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } session.Values["last_activity"] = time.Now() session.Save(r, w) } next(w, r) } } } func Protected(h http.HandlerFunc) http.HandlerFunc { return Auth(true)(SessionTimeout(h)) }