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

13
helpers/auth.go Normal file
View File

@@ -0,0 +1,13 @@
package helpers
import "golang.org/x/crypto/bcrypt"
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
func CheckPasswordHash(hash, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

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
}