AuThEnTiCaTiOn and clean up....

This commit is contained in:
2025-03-25 21:39:48 +00:00
parent b58a8bdb82
commit 11f031ff54
8 changed files with 127 additions and 56 deletions

View File

@@ -2,11 +2,13 @@ package helpers
import (
"net/http"
"time"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("super-secret-key")) // move this here
var store = sessions.NewCookieStore([]byte("super-secret-key")) // //ToDo make key global
const SessionTimeout = 30 * time.Minute
func init() {
store.Options = &sessions.Options{
@@ -21,3 +23,48 @@ func init() {
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
return store.Get(r, "session-name")
}
func IsSessionExpired(session *sessions.Session) bool {
last, ok := session.Values["last_activity"].(time.Time)
if !ok {
return false
}
return time.Since(last) > SessionTimeout
}
func UpdateSessionActivity(session *sessions.Session, r *http.Request, w http.ResponseWriter) {
session.Values["last_activity"] = time.Now()
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, "/login", http.StatusSeeOther)
return
}
UpdateSessionActivity(session, r, w)
next(w, r)
}
}
func GetCurrentUserID(r *http.Request) (int, bool) {
session, err := GetSession(nil, r)
if err != nil {
return 0, false
}
id, ok := session.Values["user_id"].(int)
return id, ok
}