Massive refactor!
This commit is contained in:
51
helpers/http/session.go
Normal file
51
helpers/http/session.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
session "synlotto-website/handlers/session"
|
||||
|
||||
"synlotto-website/constants"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
|
||||
return session.GetSession(w, r)
|
||||
}
|
||||
|
||||
func IsSessionExpired(session *sessions.Session) bool {
|
||||
last, ok := session.Values["last_activity"].(time.Time)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return time.Since(last) > constants.SessionDuration
|
||||
}
|
||||
|
||||
func UpdateSessionActivity(session *sessions.Session, r *http.Request, w http.ResponseWriter) {
|
||||
session.Values["last_activity"] = time.Now().UTC()
|
||||
session.Save(r, w)
|
||||
}
|
||||
|
||||
func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := GetSession(w, r)
|
||||
|
||||
if IsSessionExpired(session) {
|
||||
session.Options.MaxAge = -1
|
||||
session.Save(r, w)
|
||||
|
||||
newSession, _ := GetSession(w, r)
|
||||
newSession.Values["flash"] = "Your session has timed out."
|
||||
newSession.Save(r, w)
|
||||
|
||||
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
UpdateSessionActivity(session, r, w)
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user