Refactoring for Gin, NoSurf and SCS continues.

This commit is contained in:
2025-10-24 13:08:53 +01:00
parent 7276903733
commit fb07c4a5eb
61 changed files with 546 additions and 524 deletions

View File

@@ -9,12 +9,13 @@ import (
httpHelpers "synlotto-website/internal/helpers/http"
securityHelpers "synlotto-website/internal/helpers/security"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/logging"
"synlotto-website/internal/models"
"synlotto-website/internal/storage"
auditlogStorage "synlotto-website/internal/storage/auditlog"
usersStorage "synlotto-website/internal/storage/users"
"github.com/gorilla/csrf"
"github.com/justinas/nosurf"
)
func Login(db *sql.DB) http.HandlerFunc {
@@ -29,7 +30,7 @@ func Login(db *sql.DB) http.HandlerFunc {
tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html")
data := models.TemplateData{}
context := templateHelpers.TemplateContext(w, r, data)
context["csrfField"] = csrf.TemplateField(r)
context["CSRFToken"] = nosurf.Token(r)
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
logging.Info("❌ Template render error:", err)
@@ -44,10 +45,10 @@ func Login(db *sql.DB) http.HandlerFunc {
// ToDo: this outputs password in clear text remove or obscure!
logging.Info("🔐 Login attempt - Username: %s, Password: %s", username, password)
user := storage.GetUserByUsername(db, username)
user := usersStorage.GetUserByUsername(db, username)
if user == nil {
logging.Info("❌ User not found: %s", username)
storage.LogLoginAttempt(r, username, false)
auditlogStorage.LogLoginAttempt(db, r, username, false)
session, _ := httpHelpers.GetSession(w, r)
session.Values["flash"] = "Invalid username or password."
@@ -58,7 +59,7 @@ func Login(db *sql.DB) http.HandlerFunc {
if !securityHelpers.CheckPasswordHash(user.PasswordHash, password) {
logging.Info("❌ Password mismatch for user: %s", username)
storage.LogLoginAttempt(r, username, false)
auditlogStorage.LogLoginAttempt(db, r, username, false)
session, _ := httpHelpers.GetSession(w, r)
session.Values["flash"] = "Invalid username or password."
@@ -69,7 +70,7 @@ func Login(db *sql.DB) http.HandlerFunc {
}
logging.Info("✅ Login successful for user: %s", username)
storage.LogLoginAttempt(r, username, true)
auditlogStorage.LogLoginAttempt(db, r, username, true)
session, _ := httpHelpers.GetSession(w, r)
for k := range session.Values {
@@ -112,30 +113,39 @@ func Logout(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
}
func Signup(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
tmpl := templateHelpers.LoadTemplateFiles("signup.html", "templates/account/signup.html")
// ToDo: opted to inject the repo which is better for tests/DI rather than taking the *sql.DB
func Signup(usersRepo *usersStorage.UsersRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
tmpl := templateHelpers.LoadTemplateFiles("signup.html", "templates/account/signup.html")
if err := tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
"csrfField": csrf.TemplateField(r), // ToDo: this is the olf Gorilla thing
}); err != nil {
logging.Info("❌ Template render error: %v", err)
http.Error(w, "Error rendering signup page", http.StatusInternalServerError)
}
return
}
tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
"csrfField": csrf.TemplateField(r),
})
return
username := r.FormValue("username")
password := r.FormValue("password")
if username == "" || password == "" {
http.Error(w, "Username and password are required", http.StatusBadRequest)
return
}
hashed, err := securityHelpers.HashPassword(password)
if err != nil {
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
if err := usersRepo.Create(r.Context(), username, hashed, false); err != nil {
http.Error(w, "Could not create user", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
}
username := r.FormValue("username")
password := r.FormValue("password")
hashed, err := securityHelpers.HashPassword(password)
if err != nil {
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
err = models.CreateUser(username, hashed)
if err != nil {
http.Error(w, "Could not create user", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
}

View File

@@ -10,7 +10,7 @@ import (
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/models"
"synlotto-website/internal/storage"
usersStorage "synlotto-website/internal/storage/users"
)
var (
@@ -26,7 +26,7 @@ func AdminDashboardHandler(db *sql.DB) http.HandlerFunc {
return
}
user := storage.GetUserByID(db, userID)
user := usersStorage.GetUserByID(db, userID)
if user == nil {
http.Error(w, "User not found", http.StatusUnauthorized)
return
@@ -36,7 +36,7 @@ func AdminDashboardHandler(db *sql.DB) http.HandlerFunc {
context := templateHelpers.TemplateContext(w, r, data)
context["User"] = user
context["IsAdmin"] = user.IsAdmin
// Missing messages, notifications, potentially syndicate notifictions if that becomes a new top bar icon.
// ToDo: Missing messages, notifications, potentially syndicate notifictions if that becomes a new top bar icon.
db.QueryRow(`SELECT COUNT(*), SUM(CASE WHEN is_winner THEN 1 ELSE 0 END), SUM(prize_amount) FROM my_tickets`).Scan(&total, &winners, &prizeSum)
context["Stats"] = map[string]interface{}{
"TotalTickets": total,

View File

@@ -5,11 +5,10 @@ import (
"log"
"net/http"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/helpers"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/models"
"synlotto-website/internal/storage"
resultsThunderballStorage "synlotto-website/internal/storage/results/thunderball"
)
func NewDraw(db *sql.DB) http.HandlerFunc {
@@ -45,7 +44,7 @@ func Submit(db *sql.DB, w http.ResponseWriter, r *http.Request) {
Thunderball: helpers.Atoi(r.FormValue("thunderball")),
}
err := storage.InsertThunderballResult(db, draw)
err := resultsThunderballStorage.InsertThunderballResult(db, draw)
if err != nil {
log.Println("❌ Failed to insert draw:", err)
http.Error(w, "Failed to save draw", http.StatusInternalServerError)

View File

@@ -9,10 +9,11 @@ import (
templateHandlers "synlotto-website/internal/handlers/template"
securityHelpers "synlotto-website/internal/helpers/security"
templateHelpers "synlotto-website/internal/helpers/template"
syndicateStorage "synlotto-website/internal/storage/syndicate"
ticketStorage "synlotto-website/internal/storage/tickets"
"synlotto-website/internal/helpers"
"synlotto-website/internal/models"
"synlotto-website/internal/storage"
)
func CreateSyndicateHandler(db *sql.DB) http.HandlerFunc {
@@ -35,7 +36,7 @@ func CreateSyndicateHandler(db *sql.DB) http.HandlerFunc {
return
}
_, err := storage.CreateSyndicate(db, userId, name, description)
_, err := syndicateStorage.CreateSyndicate(db, userId, name, description)
if err != nil {
log.Printf("❌ CreateSyndicate failed: %v", err)
templateHelpers.SetFlash(w, r, "Failed to create syndicate")
@@ -58,8 +59,8 @@ func ListSyndicatesHandler(db *sql.DB) http.HandlerFunc {
return
}
managed := storage.GetSyndicatesByOwner(db, userID)
member := storage.GetSyndicatesByMember(db, userID)
managed := syndicateStorage.GetSyndicatesByOwner(db, userID)
member := syndicateStorage.GetSyndicatesByMember(db, userID)
managedMap := make(map[int]bool)
for _, s := range managed {
@@ -92,21 +93,21 @@ func ViewSyndicateHandler(db *sql.DB) http.HandlerFunc {
}
syndicateID := helpers.Atoi(r.URL.Query().Get("id"))
syndicate, err := storage.GetSyndicateByID(db, syndicateID)
syndicate, err := syndicateStorage.GetSyndicateByID(db, syndicateID)
if err != nil || syndicate == nil {
templateHelpers.RenderError(w, r, 404)
return
}
isManager := userID == syndicate.OwnerID
isMember := storage.IsSyndicateMember(db, syndicateID, userID)
isMember := syndicateStorage.IsSyndicateMember(db, syndicateID, userID)
if !isManager && !isMember {
templateHelpers.RenderError(w, r, 403)
return
}
members := storage.GetSyndicateMembers(db, syndicateID)
members := syndicateStorage.GetSyndicateMembers(db, syndicateID)
data := templateHandlers.BuildTemplateData(db, w, r)
context := templateHelpers.TemplateContext(w, r, data)
@@ -128,7 +129,7 @@ func SyndicateLogTicketHandler(db *sql.DB) http.HandlerFunc {
}
syndicateId := helpers.Atoi(r.URL.Query().Get("id"))
syndicate, err := storage.GetSyndicateByID(db, syndicateId)
syndicate, err := syndicateStorage.GetSyndicateByID(db, syndicateId)
if err != nil || syndicate.OwnerID != userID {
templateHelpers.RenderError(w, r, 403)
return
@@ -148,7 +149,7 @@ func SyndicateLogTicketHandler(db *sql.DB) http.HandlerFunc {
drawDate := r.FormValue("draw_date")
method := r.FormValue("purchase_method")
err := storage.InsertTicket(db, models.Ticket{
err := ticketStorage.InsertTicket(db, models.Ticket{
UserId: userID,
GameType: gameType,
DrawDate: drawDate,
@@ -185,12 +186,12 @@ func SyndicateTicketsHandler(db *sql.DB) http.HandlerFunc {
return
}
if !storage.IsSyndicateMember(db, syndicateID, userID) {
if !syndicateStorage.IsSyndicateMember(db, syndicateID, userID) {
templateHelpers.RenderError(w, r, 403)
return
}
tickets := storage.GetSyndicateTickets(db, syndicateID)
tickets := ticketStorage.GetSyndicateTickets(db, syndicateID)
data := templateHandlers.BuildTemplateData(db, w, r)
context := templateHelpers.TemplateContext(w, r, data)

View File

@@ -10,16 +10,17 @@ import (
templateHandlers "synlotto-website/internal/handlers/template"
securityHelpers "synlotto-website/internal/helpers/security"
templateHelpers "synlotto-website/internal/helpers/template"
storage "synlotto-website/internal/storage/syndicate"
syndicateStorage "synlotto-website/internal/storage/syndicate"
"synlotto-website/internal/helpers"
"synlotto-website/internal/storage"
)
func SyndicateInviteHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok {
templateHelpers.RenderError(w, r, http.StatusForbidden)
templateHandlers.RenderError(w, r, http.StatusForbidden)
return
}
@@ -33,13 +34,13 @@ func SyndicateInviteHandler(db *sql.DB) http.HandlerFunc {
tmpl := templateHelpers.LoadTemplateFiles("invite-syndicate.html", "templates/syndicate/invite.html")
err := tmpl.ExecuteTemplate(w, "layout", context)
if err != nil {
templateHelpers.RenderError(w, r, 500)
templateHandlers.RenderError(w, r, 500)
}
case http.MethodPost:
syndicateID := helpers.Atoi(r.FormValue("syndicate_id"))
username := r.FormValue("username")
err := storage.InviteToSyndicate(db, userID, syndicateID, username)
err := syndicateStorage.InviteToSyndicate(db, userID, syndicateID, username)
if err != nil {
templateHelpers.SetFlash(w, r, "Failed to send invite: "+err.Error())
} else {
@@ -48,7 +49,7 @@ func SyndicateInviteHandler(db *sql.DB) http.HandlerFunc {
http.Redirect(w, r, "/syndicate/view?id="+strconv.Itoa(syndicateID), http.StatusSeeOther)
default:
templateHelpers.RenderError(w, r, http.StatusMethodNotAllowed)
templateHandlers.RenderError(w, r, http.StatusMethodNotAllowed)
}
}
}
@@ -57,11 +58,11 @@ func ViewInvitesHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok {
templateHelpers.RenderError(w, r, 403)
templateHandlers.RenderError(w, r, 403)
return
}
invites := storage.GetPendingInvites(db, userID)
invites := syndicateStorage.GetPendingInvites(db, userID)
data := templateHandlers.BuildTemplateData(db, w, r)
context := templateHelpers.TemplateContext(w, r, data)
context["Invites"] = invites
@@ -76,10 +77,10 @@ func AcceptInviteHandler(db *sql.DB) http.HandlerFunc {
inviteID := helpers.Atoi(r.URL.Query().Get("id"))
userID, ok := securityHelpers.GetCurrentUserID(r)
if !ok {
templateHelpers.RenderError(w, r, 403)
templateHandlers.RenderError(w, r, 403)
return
}
err := storage.AcceptInvite(db, inviteID, userID)
err := syndicateStorage.AcceptInvite(db, inviteID, userID)
if err != nil {
templateHelpers.SetFlash(w, r, "Failed to accept invite")
} else {
@@ -92,7 +93,7 @@ func AcceptInviteHandler(db *sql.DB) http.HandlerFunc {
func DeclineInviteHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
inviteID := helpers.Atoi(r.URL.Query().Get("id"))
_ = storage.UpdateInviteStatus(db, inviteID, "declined")
_ = syndicateStorage.UpdateInviteStatus(db, inviteID, "declined")
http.Redirect(w, r, "/syndicate/invites", http.StatusSeeOther)
}
}
@@ -113,6 +114,7 @@ func CreateInviteToken(db *sql.DB, syndicateID, invitedByID int, ttlHours int) (
return token, err
}
// ToDo: Whys is there SQL in here??? Shouldn't be in handlers
func AcceptInviteToken(db *sql.DB, token string, userID int) error {
var syndicateID int
var expiresAt, acceptedAt sql.NullTime

View File

@@ -18,7 +18,7 @@ import (
"synlotto-website/internal/helpers"
"synlotto-website/internal/models"
"github.com/gorilla/csrf"
"github.com/justinas/nosurf"
)
func AddTicket(db *sql.DB) http.HandlerFunc {
@@ -46,7 +46,7 @@ func AddTicket(db *sql.DB) http.HandlerFunc {
data := models.TemplateData{}
context := templateHelpers.TemplateContext(w, r, data)
context["csrfField"] = csrf.TemplateField(r)
context["CSRFToken"] = nosurf.Token(r)
context["DrawDates"] = drawDates
tmpl := templateHelpers.LoadTemplateFiles("add_ticket.html", "templates/account/tickets/add_ticket.html")

View File

@@ -8,10 +8,13 @@ import (
templateHandlers "synlotto-website/internal/handlers/template"
httpHelpers "synlotto-website/internal/helpers/http"
securityHelpers "synlotto-website/internal/helpers/security"
// ToDo multi storage references need handler?
templateHelpers "synlotto-website/internal/helpers/template"
messagesStorage "synlotto-website/internal/storage/messages"
storage "synlotto-website/internal/storage/messages"
"synlotto-website/internal/helpers"
storage "synlotto-website/internal/storage/mysql"
)
func MessagesInboxHandler(db *sql.DB) http.HandlerFunc {
@@ -28,13 +31,13 @@ func MessagesInboxHandler(db *sql.DB) http.HandlerFunc {
}
perPage := 10
totalCount := storage.GetInboxMessageCount(db, userID)
totalCount := messagesStorage.GetInboxMessageCount(db, userID)
totalPages := (totalCount + perPage - 1) / perPage
if totalPages == 0 {
totalPages = 1
}
messages := storage.GetInboxMessages(db, userID, page, perPage)
messages := messagesStorage.GetInboxMessages(db, userID, page, perPage)
data := templateHandlers.BuildTemplateData(db, w, r)
context := templateHelpers.TemplateContext(w, r, data)
@@ -92,7 +95,7 @@ func ArchiveMessageHandler(db *sql.DB) http.HandlerFunc {
return
}
err := storage.ArchiveMessage(db, userID, id)
err := messagesStorage.ArchiveMessage(db, userID, id)
if err != nil {
templateHelpers.SetFlash(w, r, "Failed to archive message.")
} else {
@@ -117,7 +120,7 @@ func ArchivedMessagesHandler(db *sql.DB) http.HandlerFunc {
}
perPage := 10
messages := storage.GetArchivedMessages(db, userID, page, perPage)
messages := messagesStorage.GetArchivedMessages(db, userID, page, perPage)
hasMore := len(messages) == perPage
data := templateHandlers.BuildTemplateData(db, w, r)
@@ -153,7 +156,7 @@ func SendMessageHandler(db *sql.DB) http.HandlerFunc {
subject := r.FormValue("subject")
body := r.FormValue("message")
if err := storage.SendMessage(db, senderID, recipientID, subject, body); err != nil {
if err := messagesStorage.SendMessage(db, senderID, recipientID, subject, body); err != nil {
templateHelpers.SetFlash(w, r, "Failed to send message.")
} else {
templateHelpers.SetFlash(w, r, "Message sent.")

View File

@@ -9,8 +9,7 @@ import (
templateHandlers "synlotto-website/internal/handlers/template"
httpHelpers "synlotto-website/internal/helpers/http"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/storage"
notificationsStorage "synlotto-website/internal/storage/notifications"
)
func NotificationsHandler(db *sql.DB) http.HandlerFunc {
@@ -44,12 +43,12 @@ func MarkNotificationReadHandler(db *sql.DB) http.HandlerFunc {
return
}
notification, err := storage.GetNotificationByID(db, userID, notificationID)
notification, err := notificationsStorage.GetNotificationByID(db, userID, notificationID)
if err != nil {
log.Printf("❌ Notification not found or belongs to another user: %v", err)
notification = nil
} else if !notification.IsRead {
err = storage.MarkNotificationAsRead(db, userID, notificationID)
err = notificationsStorage.MarkNotificationAsRead(db, userID, notificationID)
if err != nil {
log.Printf("⚠️ Failed to mark as read: %v", err)
}

View File

@@ -1,23 +0,0 @@
package handlers
import (
"fmt"
"net/http"
"github.com/gorilla/sessions"
)
var (
SessionStore *sessions.CookieStore
Name string
)
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
if SessionStore == nil {
return nil, fmt.Errorf("session store not initialized")
}
if Name == "" {
return nil, fmt.Errorf("session name not configured")
}
return SessionStore.Get(r, Name)
}

View File

@@ -1,32 +0,0 @@
package handlers
import (
"net/http"
"github.com/gorilla/securecookie"
)
var (
authKey []byte
encryptKey []byte
)
func SecureCookie(w http.ResponseWriter, name, value string, isProduction bool) error {
s := securecookie.New(authKey, encryptKey)
encoded, err := s.Encode(name, value)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: name,
Value: encoded,
Path: "/",
HttpOnly: true,
Secure: isProduction,
SameSite: http.SameSiteStrictMode,
})
return nil
}

View File

@@ -0,0 +1,63 @@
package handlers
// ToDo not nessisarily an issue with this file but ✅ internal/handlers/template/
//→ For anything that handles HTTP rendering (RenderError, RenderPage)
//✅ internal/helpers/template/
//→ For anything that helps render (TemplateContext, pagination, funcs)
// there for bear usages between helpers and handlers
//In clean Go architecture (especially following “Package by responsibility”):
//Type Responsibility Should access
//Helpers / Utilities Pure, stateless logic — e.g. template functions, math, formatters. Shared logic, no config, no HTTP handlers.
//Handlers Own an HTTP concern — e.g. routes, rendering responses, returning templates or JSON. Injected dependencies (cfg, db, etc.). Should use helpers, not vice versa.
import (
"fmt"
"log"
"net/http"
"os"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/models"
)
func RenderError(
w http.ResponseWriter,
r *http.Request,
statusCode int,
siteName string,
copyrightYearStart int,
) {
log.Printf("⚙️ RenderError called with status: %d", statusCode)
context := templateHelpers.TemplateContext(
w, r,
models.TemplateData{},
siteName,
copyrightYearStart,
)
pagePath := fmt.Sprintf("templates/error/%d.html", statusCode)
log.Printf("📄 Checking for template file: %s", pagePath)
if _, err := os.Stat(pagePath); err != nil {
log.Printf("🚫 Template file missing: %s", err)
http.Error(w, http.StatusText(statusCode), statusCode)
return
}
log.Println("✅ Template file found, loading...")
tmpl := templateHelpers.LoadTemplateFiles(fmt.Sprintf("%d.html", statusCode), pagePath)
w.WriteHeader(statusCode)
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
log.Printf("❌ Failed to render error page layout: %v", err)
http.Error(w, http.StatusText(statusCode), statusCode)
return
}
log.Println("✅ Successfully rendered error page") // ToDo: log these to db
}

View File

@@ -0,0 +1,11 @@
package handlers
import "synlotto-website/internal/platform/config"
type Handler struct {
cfg config.Config
}
func New(cfg config.Config) *Handler {
return &Handler{cfg: cfg}
}

View File

@@ -6,9 +6,12 @@ import (
"net/http"
httpHelper "synlotto-website/internal/helpers/http"
// ToDo: again, need to check if i should be using multiple stotage entries like this or if this si even correct would it not be a helper?
messageStorage "synlotto-website/internal/storage/messages"
notificationStorage "synlotto-website/internal/storage/notifications"
usersStorage "synlotto-website/internal/storage/users"
"synlotto-website/internal/models"
"synlotto-website/internal/storage"
)
func BuildTemplateData(db *sql.DB, w http.ResponseWriter, r *http.Request) models.TemplateData {
@@ -25,13 +28,13 @@ func BuildTemplateData(db *sql.DB, w http.ResponseWriter, r *http.Request) model
var messages []models.Message
if userId, ok := session.Values["user_id"].(int); ok {
user = storage.GetUserByID(db, userId)
user = usersStorage.GetUserByID(db, userId)
if user != nil {
isAdmin = user.IsAdmin
notificationCount = storage.GetNotificationCount(db, user.Id)
notifications = storage.GetRecentNotifications(db, user.Id, 15)
messageCount, _ = storage.GetMessageCount(db, user.Id)
messages = storage.GetRecentMessages(db, user.Id, 15)
notificationCount = notificationStorage.GetNotificationCount(db, user.Id)
notifications = notificationStorage.GetRecentNotifications(db, user.Id, 15)
messageCount, _ = messageStorage.GetMessageCount(db, user.Id)
messages = messageStorage.GetRecentMessages(db, user.Id, 15)
}
}