50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
httpHelpers "synlotto-website/helpers/http"
|
|
|
|
"synlotto-website/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))
|
|
}
|