added authentication among other things. considered working at this point.

This commit is contained in:
2025-03-25 11:27:21 +00:00
parent cf8b0041b2
commit f1ad9757ba
19 changed files with 310 additions and 58 deletions

44
handlers/session.go Normal file
View File

@@ -0,0 +1,44 @@
package handlers
import (
"net/http"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("super-secret-key")) // ToDo: Make global
func init() {
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 1,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
}
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
return store.Get(r, "session-name")
}
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
}
func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, ok := GetCurrentUserID(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
next(w, r)
}
}