fix loading ofr login form and redirects.

This commit is contained in:
2025-04-23 10:06:55 +01:00
parent 2ce810a4dd
commit e938828a8c
7 changed files with 83 additions and 69 deletions

View File

@@ -1,6 +1,7 @@
package handlers package handlers
import ( import (
"database/sql"
"log" "log"
"net/http" "net/http"
"time" "time"
@@ -8,28 +9,30 @@ import (
httpHelpers "synlotto-website/helpers/http" httpHelpers "synlotto-website/helpers/http"
securityHelpers "synlotto-website/helpers/security" securityHelpers "synlotto-website/helpers/security"
templateHelpers "synlotto-website/helpers/template" templateHelpers "synlotto-website/helpers/template"
"synlotto-website/logging"
"synlotto-website/models" "synlotto-website/models"
"synlotto-website/storage" "synlotto-website/storage"
"github.com/gorilla/csrf" "github.com/gorilla/csrf"
) )
func Login(w http.ResponseWriter, r *http.Request) { func Login(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
session, _ := httpHelpers.GetSession(w, r) session, _ := httpHelpers.GetSession(w, r)
if _, ok := session.Values["user_id"].(int); ok { if _, ok := session.Values["user_id"].(int); ok {
http.Redirect(w, r, "/", http.StatusSeeOther) http.Redirect(w, r, "/", http.StatusSeeOther)
return return
} }
tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html")
tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html")
context := templateHelpers.TemplateContext(w, r, models.TemplateData{}) context := templateHelpers.TemplateContext(w, r, models.TemplateData{})
context["csrfField"] = csrf.TemplateField(r) context["csrfField"] = csrf.TemplateField(r)
err := tmpl.ExecuteTemplate(w, "layout", context) if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
if err != nil { logging.Info("❌ Template render error:", err)
log.Println("❌ Template render error:", err) http.Error(w, "Error rendering login page", http.StatusInternalServerError)
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
} }
return return
} }
@@ -37,47 +40,59 @@ func Login(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username") username := r.FormValue("username")
password := r.FormValue("password") password := r.FormValue("password")
user := models.GetUserByUsername(username) logging.Info("🔐 Login attempt - Username: %s, Password: %s", username, password)
if user == nil || !securityHelpers.CheckPasswordHash(user.PasswordHash, password) {
http.Error(w, "Invalid credentials", http.StatusUnauthorized) 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
} }
session, _ := httpHelpers.GetSession(w, r) if !securityHelpers.CheckPasswordHash(user.PasswordHash, password) {
logging.Info("❌ Password mismatch for user: %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 has did it")
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return
}
logging.Info("✅ Login successful for user: %s", username)
storage.LogLoginAttempt(r, username, true)
session, _ := httpHelpers.GetSession(w, r)
for k := range session.Values { for k := range session.Values {
delete(session.Values, k) delete(session.Values, k)
} }
session.Values["user_id"] = user.Id session.Values["user_id"] = user.Id
session.Values["last_activity"] = time.Now() session.Values["last_activity"] = time.Now().UTC()
remember := r.FormValue("remember") == "on" if r.FormValue("remember") == "on" {
if remember {
session.Options.MaxAge = 60 * 60 * 24 * 30 session.Options.MaxAge = 60 * 60 * 24 * 30
} else { } else {
session.Options.MaxAge = 0 session.Options.MaxAge = 0
} }
err := session.Save(r, w) if err := session.Save(r, w); err != nil {
if err != nil { logging.Info("❌ Failed to save session: %v", err)
log.Println("❌ Failed to save session:", err)
} else { } else {
log.Printf("✅ Login saved: user_id=%d, maxAge=%d", user.Id, session.Options.MaxAge) logging.Info("✅ Session saved for user: %s", username)
for _, c := range r.Cookies() {
log.Printf("🍪 Cookie after login: %s = %s", c.Name, c.Value)
} }
}
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)
http.Redirect(w, r, "/", http.StatusSeeOther) http.Redirect(w, r, "/", http.StatusSeeOther)
} }
}
func Logout(w http.ResponseWriter, r *http.Request) { func Logout(w http.ResponseWriter, r *http.Request) {
session, _ := httpHelpers.GetSession(w, r) session, _ := httpHelpers.GetSession(w, r)
@@ -91,10 +106,9 @@ func Logout(w http.ResponseWriter, r *http.Request) {
err := session.Save(r, w) err := session.Save(r, w)
if err != nil { if err != nil {
log.Println("❌ Logout session save failed:", err) logging.Error("❌ Logout session save failed:", err)
} }
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
http.Redirect(w, r, "/login", http.StatusSeeOther)
} }
func Signup(w http.ResponseWriter, r *http.Request) { func Signup(w http.ResponseWriter, r *http.Request) {
@@ -122,5 +136,5 @@ func Signup(w http.ResponseWriter, r *http.Request) {
return return
} }
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
} }

View File

@@ -15,7 +15,7 @@ func AdminDashboardHandler(db *sql.DB) http.HandlerFunc {
return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) { return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
// userID, ok := securityHelpers.GetCurrentUserID(r) // userID, ok := securityHelpers.GetCurrentUserID(r)
// if !ok { // if !ok {
// http.Redirect(w, r, "/login", http.StatusSeeOther) // http.Redirect(w, r, "/account/login", http.StatusSeeOther)
// return // return
// } // }

View File

@@ -67,7 +67,7 @@ func AddTicket(db *sql.DB) http.HandlerFunc {
userID, ok := securityHelpers.GetCurrentUserID(r) userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok { if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return return
} }
@@ -190,7 +190,7 @@ func SubmitTicket(db *sql.DB) http.HandlerFunc {
userID, ok := securityHelpers.GetCurrentUserID(r) userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok { if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return return
} }
@@ -272,7 +272,7 @@ func GetMyTickets(db *sql.DB) http.HandlerFunc {
return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) { return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
userID, ok := securityHelpers.GetCurrentUserID(r) userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok { if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return return
} }

View File

@@ -17,7 +17,7 @@ func Auth(required bool) func(http.HandlerFunc) http.HandlerFunc {
_, ok := session.Values["user_id"].(int) _, ok := session.Values["user_id"].(int)
if required && !ok { if required && !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return return
} }
@@ -31,7 +31,7 @@ func Auth(required bool) func(http.HandlerFunc) http.HandlerFunc {
newSession.Values["flash"] = "Your session has timed out." newSession.Values["flash"] = "Your session has timed out."
newSession.Save(r, w) newSession.Save(r, w)
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/account/login", http.StatusSeeOther)
return return
} }

View File

@@ -4,7 +4,7 @@ import (
"database/sql" "database/sql"
"net/http" "net/http"
account "synlotto-website/handlers/account" accountHandlers "synlotto-website/handlers/account"
lotteryDrawHandlers "synlotto-website/handlers/lottery/tickets" lotteryDrawHandlers "synlotto-website/handlers/lottery/tickets"
"synlotto-website/handlers" "synlotto-website/handlers"
@@ -12,9 +12,9 @@ import (
) )
func SetupAccountRoutes(mux *http.ServeMux, db *sql.DB) { func SetupAccountRoutes(mux *http.ServeMux, db *sql.DB) {
mux.HandleFunc("/login", middleware.Protected(account.Login)) mux.HandleFunc("/account/login", accountHandlers.Login(db))
mux.HandleFunc("/logout", account.Logout) mux.HandleFunc("/account/logout", middleware.Protected(accountHandlers.Logout))
mux.HandleFunc("/signup", middleware.Protected(account.Signup)) mux.HandleFunc("/account/signup", accountHandlers.Signup)
mux.HandleFunc("/account/tickets/add_ticket", lotteryDrawHandlers.AddTicket(db)) mux.HandleFunc("/account/tickets/add_ticket", lotteryDrawHandlers.AddTicket(db))
mux.HandleFunc("/account/tickets/my_tickets", lotteryDrawHandlers.GetMyTickets(db)) mux.HandleFunc("/account/tickets/my_tickets", lotteryDrawHandlers.GetMyTickets(db))
mux.HandleFunc("/account/messages", middleware.Protected(handlers.MessagesInboxHandler(db))) mux.HandleFunc("/account/messages", middleware.Protected(handlers.MessagesInboxHandler(db)))

View File

@@ -1,6 +1,6 @@
{{ define "content" }} {{ define "content" }}
<h2>Login</h2> <h2>Login</h2>
<form method="POST" action="/login" class="form"> <form method="POST" action="/account/login" class="form">
{{ .CSRFField }} {{ .CSRFField }}
<div class="mb-3"> <div class="mb-3">

View File

@@ -1,6 +1,6 @@
{{ define "content" }} {{ define "content" }}
<h2>Sign Up</h2> <h2>Sign Up</h2>
<form method="POST" action="/signup"> <form method="POST" action="/account/signup">
{{ .csrfField }} {{ .csrfField }}
<label>Username: <input type="text" name="username" required></label><br> <label>Username: <input type="text" name="username" required></label><br>
<label>Password: <input type="password" name="password" required></label><br> <label>Password: <input type="password" name="password" required></label><br>