From e938828a8c2abf95c434a8bc2caf7180b4d71aba Mon Sep 17 00:00:00 2001 From: H3ALY Date: Wed, 23 Apr 2025 10:06:55 +0100 Subject: [PATCH] fix loading ofr login form and redirects. --- handlers/account/authentication.go | 128 ++++++++++++--------- handlers/admin/dashboard.go | 2 +- handlers/lottery/tickets/ticket_handler.go | 6 +- middleware/auth.go | 4 +- routes/accountroutes.go | 8 +- templates/account/login.html | 2 +- templates/account/signup.html | 2 +- 7 files changed, 83 insertions(+), 69 deletions(-) diff --git a/handlers/account/authentication.go b/handlers/account/authentication.go index da209c8..8751322 100644 --- a/handlers/account/authentication.go +++ b/handlers/account/authentication.go @@ -1,6 +1,7 @@ package handlers import ( + "database/sql" "log" "net/http" "time" @@ -8,75 +9,89 @@ import ( httpHelpers "synlotto-website/helpers/http" securityHelpers "synlotto-website/helpers/security" templateHelpers "synlotto-website/helpers/template" + + "synlotto-website/logging" "synlotto-website/models" "synlotto-website/storage" "github.com/gorilla/csrf" ) -func Login(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodGet { - session, _ := httpHelpers.GetSession(w, r) - if _, ok := session.Values["user_id"].(int); ok { - http.Redirect(w, r, "/", http.StatusSeeOther) +func Login(db *sql.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + session, _ := httpHelpers.GetSession(w, r) + if _, ok := session.Values["user_id"].(int); ok { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + + tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html") + context := templateHelpers.TemplateContext(w, r, models.TemplateData{}) + context["csrfField"] = csrf.TemplateField(r) + + if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil { + logging.Info("❌ Template render error:", err) + http.Error(w, "Error rendering login page", http.StatusInternalServerError) + } return } - tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html") - context := templateHelpers.TemplateContext(w, r, models.TemplateData{}) - context["csrfField"] = csrf.TemplateField(r) + username := r.FormValue("username") + password := r.FormValue("password") - err := tmpl.ExecuteTemplate(w, "layout", context) - if err != nil { - log.Println("❌ Template render error:", err) - http.Error(w, "Error rendering login page", http.StatusInternalServerError) // Take hte flash message from licnse server this just does a black page also should be using db ahain see licvense server + logging.Info("🔐 Login attempt - Username: %s, Password: %s", username, password) + + user := storage.GetUserByUsername(db, username) + if user == nil { + logging.Info("❌ User not found: %s", username) + storage.LogLoginAttempt(r, username, false) + + session, _ := httpHelpers.GetSession(w, r) + session.Values["flash"] = "Invalid username or password." + session.Save(r, w) + log.Printf("login did it") + http.Redirect(w, r, "/account/login", http.StatusSeeOther) + return } - return - } - username := r.FormValue("username") - password := r.FormValue("password") + if !securityHelpers.CheckPasswordHash(user.PasswordHash, password) { + logging.Info("❌ Password mismatch for user: %s", username) + storage.LogLoginAttempt(r, username, false) - user := models.GetUserByUsername(username) - if user == nil || !securityHelpers.CheckPasswordHash(user.PasswordHash, password) { - http.Error(w, "Invalid credentials", http.StatusUnauthorized) - return - } - - session, _ := httpHelpers.GetSession(w, r) - - for k := range session.Values { - delete(session.Values, k) - } - - session.Values["user_id"] = user.Id - session.Values["last_activity"] = time.Now() - - remember := r.FormValue("remember") == "on" - if remember { - session.Options.MaxAge = 60 * 60 * 24 * 30 - } else { - session.Options.MaxAge = 0 - } - - err := session.Save(r, w) - if err != nil { - log.Println("❌ Failed to save session:", err) - } else { - log.Printf("✅ Login saved: user_id=%d, maxAge=%d", user.Id, session.Options.MaxAge) - for _, c := range r.Cookies() { - log.Printf("🍪 Cookie after login: %s = %s", c.Name, c.Value) + session, _ := httpHelpers.GetSession(w, r) + session.Values["flash"] = "Invalid username or password." + session.Save(r, w) + log.Printf("login has did it") + http.Redirect(w, r, "/account/login", http.StatusSeeOther) + return } - } - if user == nil || !securityHelpers.CheckPasswordHash(user.PasswordHash, password) { - storage.LogLoginAttempt(r, username, false) - http.Error(w, "Invalid credentials", http.StatusUnauthorized) - return - } - storage.LogLoginAttempt(r, username, true) + logging.Info("✅ Login successful for user: %s", username) + storage.LogLoginAttempt(r, username, true) - http.Redirect(w, r, "/", http.StatusSeeOther) + session, _ := httpHelpers.GetSession(w, r) + for k := range session.Values { + delete(session.Values, k) + } + + session.Values["user_id"] = user.Id + session.Values["last_activity"] = time.Now().UTC() + + if r.FormValue("remember") == "on" { + session.Options.MaxAge = 60 * 60 * 24 * 30 + } else { + session.Options.MaxAge = 0 + } + + if err := session.Save(r, w); err != nil { + logging.Info("❌ Failed to save session: %v", err) + } else { + logging.Info("✅ Session saved for user: %s", username) + } + + http.Redirect(w, r, "/", http.StatusSeeOther) + } } func Logout(w http.ResponseWriter, r *http.Request) { @@ -91,10 +106,9 @@ func Logout(w http.ResponseWriter, r *http.Request) { err := session.Save(r, w) if err != nil { - log.Println("❌ Logout session save failed:", err) + logging.Error("❌ Logout session save failed:", err) } - - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) } func Signup(w http.ResponseWriter, r *http.Request) { @@ -122,5 +136,5 @@ func Signup(w http.ResponseWriter, r *http.Request) { return } - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) } diff --git a/handlers/admin/dashboard.go b/handlers/admin/dashboard.go index d001289..4ae170b 100644 --- a/handlers/admin/dashboard.go +++ b/handlers/admin/dashboard.go @@ -15,7 +15,7 @@ func AdminDashboardHandler(db *sql.DB) http.HandlerFunc { return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) { // userID, ok := securityHelpers.GetCurrentUserID(r) // if !ok { - // http.Redirect(w, r, "/login", http.StatusSeeOther) + // http.Redirect(w, r, "/account/login", http.StatusSeeOther) // return // } diff --git a/handlers/lottery/tickets/ticket_handler.go b/handlers/lottery/tickets/ticket_handler.go index 8d8869d..cbaeeec 100644 --- a/handlers/lottery/tickets/ticket_handler.go +++ b/handlers/lottery/tickets/ticket_handler.go @@ -67,7 +67,7 @@ func AddTicket(db *sql.DB) http.HandlerFunc { userID, ok := securityHelpers.GetCurrentUserID(r) if !ok { - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } @@ -190,7 +190,7 @@ func SubmitTicket(db *sql.DB) http.HandlerFunc { userID, ok := securityHelpers.GetCurrentUserID(r) if !ok { - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } @@ -272,7 +272,7 @@ func GetMyTickets(db *sql.DB) http.HandlerFunc { return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) { userID, ok := securityHelpers.GetCurrentUserID(r) if !ok { - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } diff --git a/middleware/auth.go b/middleware/auth.go index 11d210a..dad3314 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -17,7 +17,7 @@ func Auth(required bool) func(http.HandlerFunc) http.HandlerFunc { _, ok := session.Values["user_id"].(int) if required && !ok { - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } @@ -31,7 +31,7 @@ func Auth(required bool) func(http.HandlerFunc) http.HandlerFunc { newSession.Values["flash"] = "Your session has timed out." newSession.Save(r, w) - http.Redirect(w, r, "/login", http.StatusSeeOther) + http.Redirect(w, r, "/account/login", http.StatusSeeOther) return } diff --git a/routes/accountroutes.go b/routes/accountroutes.go index 5ca96e2..e302615 100644 --- a/routes/accountroutes.go +++ b/routes/accountroutes.go @@ -4,7 +4,7 @@ import ( "database/sql" "net/http" - account "synlotto-website/handlers/account" + accountHandlers "synlotto-website/handlers/account" lotteryDrawHandlers "synlotto-website/handlers/lottery/tickets" "synlotto-website/handlers" @@ -12,9 +12,9 @@ import ( ) func SetupAccountRoutes(mux *http.ServeMux, db *sql.DB) { - mux.HandleFunc("/login", middleware.Protected(account.Login)) - mux.HandleFunc("/logout", account.Logout) - mux.HandleFunc("/signup", middleware.Protected(account.Signup)) + mux.HandleFunc("/account/login", accountHandlers.Login(db)) + mux.HandleFunc("/account/logout", middleware.Protected(accountHandlers.Logout)) + mux.HandleFunc("/account/signup", accountHandlers.Signup) mux.HandleFunc("/account/tickets/add_ticket", lotteryDrawHandlers.AddTicket(db)) mux.HandleFunc("/account/tickets/my_tickets", lotteryDrawHandlers.GetMyTickets(db)) mux.HandleFunc("/account/messages", middleware.Protected(handlers.MessagesInboxHandler(db))) diff --git a/templates/account/login.html b/templates/account/login.html index ff8e6be..3b4c83e 100644 --- a/templates/account/login.html +++ b/templates/account/login.html @@ -1,6 +1,6 @@ {{ define "content" }}

Login

-
+ {{ .CSRFField }}
diff --git a/templates/account/signup.html b/templates/account/signup.html index 9085bf8..53b779b 100644 --- a/templates/account/signup.html +++ b/templates/account/signup.html @@ -1,6 +1,6 @@ {{ define "content" }}

Sign Up

- + {{ .csrfField }}