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)
}
}

View File

@@ -2,24 +2,33 @@ package helpers
import (
"html/template"
"log"
"net/http"
"strings"
"time"
helpers "synlotto-website/internal/helpers/http"
httpHelpers "synlotto-website/internal/helpers/http"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/config"
"github.com/gorilla/csrf"
"github.com/justinas/nosurf"
)
func TemplateContext(w http.ResponseWriter, r *http.Request, data models.TemplateData) map[string]interface{} {
cfg := config.Get()
if cfg == nil {
log.Println("⚠️ Config not initialized!")
// ToDo should these structs be here?
type siteMeta struct {
Name string
CopyrightYearStart int
}
var meta siteMeta
func InitSiteMeta(name string, yearStart, yearEnd int) {
meta = siteMeta{
Name: name,
CopyrightYearStart: yearStart,
}
session, _ := helpers.GetSession(w, r)
}
func TemplateContext(w http.ResponseWriter, r *http.Request, data models.TemplateData) map[string]interface{} {
session, _ := httpHelpers.GetSession(w, r)
var flash string
if f, ok := session.Values["flash"].(string); ok {
@@ -29,7 +38,7 @@ func TemplateContext(w http.ResponseWriter, r *http.Request, data models.Templat
}
return map[string]interface{}{
"CSRFField": csrf.TemplateField(r),
"CSRFToken": nosurf.Token(r),
"Flash": flash,
"User": data.User,
"IsAdmin": data.IsAdmin,
@@ -37,8 +46,8 @@ func TemplateContext(w http.ResponseWriter, r *http.Request, data models.Templat
"Notifications": data.Notifications,
"MessageCount": data.MessageCount,
"Messages": data.Messages,
"SiteName": cfg.Site.SiteName,
"CopyrightYearStart": cfg.Site.CopyrightYearStart,
"SiteName": meta.Name,
"CopyrightYearStart": meta.CopyrightYearStart,
}
}
@@ -57,9 +66,8 @@ func TemplateFuncs() template.FuncMap {
"min": func(a, b int) int {
if a < b {
return a
} else {
return b
}
return b
},
"intVal": func(p *int) int {
if p == nil {
@@ -102,12 +110,11 @@ func LoadTemplateFiles(name string, files ...string) *template.Template {
"templates/main/footer.html",
}
all := append(shared, files...)
return template.Must(template.New(name).Funcs(TemplateFuncs()).ParseFiles(all...))
}
func SetFlash(w http.ResponseWriter, r *http.Request, message string) {
session, _ := helpers.GetSession(w, r)
session, _ := httpHelpers.GetSession(w, r)
session.Values["flash"] = message
session.Save(r, w)
}

View File

@@ -1,39 +0,0 @@
package helpers
import (
"fmt"
"log"
"net/http"
"os"
"synlotto-website/internal/models"
)
func RenderError(w http.ResponseWriter, r *http.Request, statusCode int) {
log.Printf("⚙️ RenderError called with status: %d", statusCode)
context := TemplateContext(w, r, models.TemplateData{})
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 := LoadTemplateFiles(fmt.Sprintf("%d.html", statusCode), pagePath)
w.WriteHeader(statusCode)
err := tmpl.ExecuteTemplate(w, "layout", context)
if 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 database
}

View File

@@ -4,6 +4,7 @@ import (
"database/sql"
)
// ToDo: Sql shouldnt be here.
func GetTotalPages(db *sql.DB, tableName, whereClause string, args []interface{}, pageSize int) (totalPages, totalCount int) {
query := "SELECT COUNT(*) FROM " + tableName + " " + whereClause
row := db.QueryRow(query, args...)

View File

@@ -1,5 +1,6 @@
package middleware
// ToDo: will no doubt need to fix as now using new session not the olf gorilla one
import (
"net/http"
"time"

View File

@@ -1,5 +1,6 @@
package middleware
// ToDo: make sure im using with gin
import "net/http"
func EnforceHTTPS(next http.Handler, enabled bool) http.Handler {

View File

@@ -1,5 +1,6 @@
package middleware
// ToDo: make sure im using with gin
import (
"net"
"net/http"

View File

@@ -1,5 +1,6 @@
package middleware
// ToDo: make sure im using with gin not to be confused with gins recovery but may do the same?
import (
"log"
"net/http"

View File

@@ -0,0 +1,18 @@
package middleware
import (
"net/http"
"github.com/alexedwards/scs/v2"
"github.com/gin-gonic/gin"
)
func Session(sm *scs.SessionManager) gin.HandlerFunc {
return func(c *gin.Context) {
handler := sm.LoadAndSave(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c.Request = r
c.Next()
}))
handler.ServeHTTP(c.Writer, c.Request)
}
}

View File

@@ -1,5 +1,6 @@
package middleware
// ToDo: This is more than likele now redunant with the session change
import (
"log"
"net/http"

View File

@@ -4,14 +4,11 @@ import (
"encoding/json"
"log"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/config"
)
func LogConfig(config *models.Config) {
func LogConfig(config *config.Config) {
safeConfig := *config
safeConfig.CSRF.CSRFKey = "[REDACTED]"
safeConfig.Session.AuthKeyPath = "[REDACTED]"
safeConfig.Session.EncryptionKeyPath = "[REDACTED]"
cfg, err := json.MarshalIndent(safeConfig, "", " ")
if err != nil {

View File

@@ -1,26 +0,0 @@
package bootstrap
import (
"fmt"
"net/http"
"github.com/gorilla/csrf"
)
var CSRFMiddleware func(http.Handler) http.Handler
func InitCSRFProtection(csrfKey []byte, isProduction bool) error {
if len(csrfKey) != 32 {
return fmt.Errorf("csrf key must be 32 bytes, got %d", len(csrfKey))
}
CSRFMiddleware = csrf.Protect(
csrfKey,
csrf.Secure(isProduction),
csrf.SameSite(csrf.SameSiteStrictMode),
csrf.Path("/"),
csrf.HttpOnly(true),
)
return nil
}

View File

@@ -5,12 +5,12 @@ import (
"time"
internal "synlotto-website/internal/licensecheck"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/config"
)
var globalChecker *internal.LicenseChecker
func InitLicenseChecker(config *models.Config) error {
func InitLicenseChecker(config *config.Config) error {
checker := &internal.LicenseChecker{
LicenseAPIURL: config.License.APIURL,
APIKey: config.License.APIKey,

View File

@@ -5,11 +5,11 @@ import (
"fmt"
"os"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/config"
)
type AppState struct {
Config *models.Config
Config *config.Config
}
func LoadAppState(configPath string) (*AppState, error) {
@@ -19,7 +19,7 @@ func LoadAppState(configPath string) (*AppState, error) {
}
defer file.Close()
var config models.Config
var config config.Config
if err := json.NewDecoder(file).Decode(&config); err != nil {
return nil, fmt.Errorf("decode config: %w", err)
}

View File

@@ -1,115 +0,0 @@
package bootstrap
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"fmt"
"net/http"
"os"
"time"
sessionHandlers "synlotto-website/internal/handlers/session"
sessionHelpers "synlotto-website/internal/helpers/session"
"synlotto-website/internal/logging"
"synlotto-website/internal/models"
"github.com/gorilla/sessions"
)
var (
sessionStore *sessions.CookieStore
Name string
authKey []byte
encryptKey []byte
)
func InitSession(cfg *models.Config) error {
gob.Register(time.Time{})
authPath := cfg.Session.AuthKeyPath
encPath := cfg.Session.EncryptionKeyPath
if _, err := os.Stat(authPath); os.IsNotExist(err) {
logging.Info("⚠️ Auth key not found, creating: %s", authPath)
key, err := generateRandomBytes(32)
if err != nil {
return err
}
encoded := sessionHelpers.EncodeKey(key)
err = os.WriteFile(authPath, []byte(encoded), 0600)
if err != nil {
return err
}
}
if _, err := os.Stat(encPath); os.IsNotExist(err) {
logging.Info("⚠️ Encryption key not found, creating: %s", encPath)
key, err := generateRandomBytes(32)
if err != nil {
return err
}
encoded := sessionHelpers.EncodeKey(key)
err = os.WriteFile(encPath, []byte(encoded), 0600)
if err != nil {
return err
}
}
return loadSessionKeys(
authPath,
encPath,
cfg.Session.Name,
cfg.HttpServer.ProductionMode,
)
}
func generateRandomBytes(length int) ([]byte, error) {
b := make([]byte, length)
_, err := rand.Read(b)
if err != nil {
logging.Error("failed to generate random bytes: %w", err)
return nil, err
}
return b, nil
}
func loadSessionKeys(authPath, encryptionPath, name string, isProduction bool) error {
var err error
rawAuth, err := os.ReadFile(authPath)
if err != nil {
return fmt.Errorf("error reading auth key: %w", err)
}
authKey, err = base64.StdEncoding.DecodeString(string(bytes.TrimSpace(rawAuth)))
if err != nil {
return fmt.Errorf("error decoding auth key: %w", err)
}
rawEnc, err := os.ReadFile(encryptionPath)
if err != nil {
return fmt.Errorf("error reading encryption key: %w", err)
}
encryptKey, err = base64.StdEncoding.DecodeString(string(bytes.TrimSpace(rawEnc)))
if err != nil {
return fmt.Errorf("error decoding encryption key: %w", err)
}
if len(authKey) != 32 || len(encryptKey) != 32 {
return fmt.Errorf("auth and encryption keys must be 32 bytes each (got auth=%d, enc=%d)", len(authKey), len(encryptKey))
}
sessionHandlers.SessionStore = sessions.NewCookieStore(authKey, encryptKey)
sessionHandlers.SessionStore.Options = &sessions.Options{
Path: "/",
MaxAge: 86400,
HttpOnly: true,
Secure: isProduction,
SameSite: http.SameSiteLaxMode,
}
sessionHandlers.Name = name
return nil
}

View File

@@ -3,20 +3,20 @@ package config
import (
"sync"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/config"
)
var (
appConfig *models.Config
appConfig *config.Config
once sync.Once
)
func Init(config *models.Config) {
func Init(config *config.Config) {
once.Do(func() {
appConfig = config
})
}
func Get() *models.Config {
func Get() *config.Config {
return appConfig
}

View File

@@ -0,0 +1,21 @@
package config
import (
"encoding/json"
"os"
)
func Load(path string) (Config, error) {
var cfg Config
data, err := os.ReadFile(path)
if err != nil {
return cfg, err
}
if err := json.Unmarshal(data, &cfg); err != nil {
return cfg, err
}
return cfg, nil
}

View File

@@ -2,7 +2,7 @@ package config
type Config struct {
CSRF struct {
CSRFKey string `json:"csrfKey"`
CookieName string `json:"cookieName"`
} `json:"csrf"`
Database struct {
@@ -28,9 +28,8 @@ type Config struct {
} `json:"license"`
Session struct {
AuthKeyPath string `json:"authKeyPath"`
EncryptionKeyPath string `json:"encryptionKeyPath"`
Name string `json:"name"`
Name string `json:"name"`
Lifetime string `json:"lifetime"`
} `json:"session"`
Site struct {

View File

@@ -0,0 +1,21 @@
package csrf
import (
"net/http"
"synlotto-website/internal/platform/config"
"github.com/justinas/nosurf"
)
func Wrap(h http.Handler, cfg config.Config) http.Handler {
cs := nosurf.New(h)
cs.SetBaseCookie(http.Cookie{
Name: cfg.CSRF.CookieName,
Path: "/",
HttpOnly: true,
Secure: cfg.HttpServer.ProductionMode,
SameSite: http.SameSiteLaxMode,
})
return cs
}

View File

@@ -0,0 +1,25 @@
package session
import (
"net/http"
"time"
"synlotto-website/internal/platform/config"
"github.com/alexedwards/scs/v2"
)
func New(cfg config.Config) *scs.SessionManager {
lifetime := 12 * time.Hour
if d, err := time.ParseDuration(cfg.Session.Lifetime); err == nil && d > 0 {
lifetime = d
}
s := scs.New()
s.Lifetime = lifetime
s.Cookie.Name = cfg.Session.Name
s.Cookie.HttpOnly = true
s.Cookie.SameSite = http.SameSiteLaxMode
s.Cookie.Secure = cfg.HttpServer.ProductionMode
return s
}

View File

@@ -8,11 +8,13 @@ import (
lotteryTicketHandlers "synlotto-website/internal/handlers/lottery/tickets"
thunderballrules "synlotto-website/internal/rules/thunderball"
services "synlotto-website/internal/services/draws"
lotteryTicketService "synlotto-website/internal/services/tickets"
"synlotto-website/internal/helpers"
"synlotto-website/internal/models"
)
// ToDo: SQL in here needs to me moved out the handler!
func RunTicketMatching(db *sql.DB, triggeredBy string) (models.MatchRunStats, error) {
stats := models.MatchRunStats{}
@@ -212,7 +214,8 @@ func RefreshTicketPrizes(db *sql.DB) error {
mainMatches := helpers.CountMatches(matchTicket.Balls, draw.Balls)
bonusMatches := helpers.CountMatches(matchTicket.BonusBalls, draw.BonusBalls)
prizeTier := matcher.GetPrizeTier(row.GameType, mainMatches, bonusMatches, thunderballrules.ThunderballPrizeRules)
// ToDo: this isn't a lottery ticket service really its a draw one
prizeTier := lotteryTicketService.GetPrizeTier(row.GameType, mainMatches, bonusMatches, thunderballrules.ThunderballPrizeRules)
isWinner := prizeTier != ""
var label string

View File

@@ -41,7 +41,8 @@ func AdminOnly(db *sql.DB, next http.HandlerFunc) http.HandlerFunc {
})
}
func LogLoginAttempt(r *http.Request, username string, success bool) {
// Todo has to add in - db *sql.DB to make this work should this not be an import as all functions use it, more importantly no functions in storage just sql?
func LogLoginAttempt(db *sql.DB, r *http.Request, username string, success bool) {
ip := r.RemoteAddr
userAgent := r.UserAgent()

View File

@@ -0,0 +1,3 @@
// Currently no delete functions, only archiving to remove from user
// view but they can pull them back. Consider a soft delete which hides them from being unarchived for 5 years? then systematically delete after 5 years? or delete sooner but retain backup
package storage

View File

@@ -1,3 +0,0 @@
// Currently no delete functions, only archiving to remove from user
// view but they can pull them back. Consider a soft delete which hides them from being unarchived for 5 years?
// Then systematically delete after 5 years? or delete sooner but retain backup

View File

@@ -1,54 +0,0 @@
package storage
import (
"database/sql"
"log"
"synlotto-website/internal/logging"
"synlotto-website/internal/platform/config"
// ToDo: remove sqlite
_ "modernc.org/sqlite"
)
var db *sql.DB
func InitDB(filepath string) *sql.DB {
var err error
cfg := config.Get()
db, err = sql.Open("sqlite", filepath)
if err != nil {
log.Fatal("❌ Failed to open DB:", err)
}
schemas := []string{
SchemaUsers,
SchemaThunderballResults,
SchemaThunderballPrizes,
SchemaLottoResults,
SchemaMyTickets,
SchemaUsersMessages,
SchemaUsersNotifications,
SchemaAuditLog,
SchemaAuditLogin,
SchemaLogTicketMatching,
SchemaAdminAccessLog,
SchemaNewAuditLog,
SchemaSyndicates,
SchemaSyndicateMembers,
SchemaSyndicateInvites,
SchemaSyndicateInviteTokens,
}
if cfg == nil {
logging.Error("❌ config is nil — did config.Init() run before InitDB?")
panic("config not ready")
}
for _, stmt := range schemas {
if _, err := db.Exec(stmt); err != nil {
log.Fatalf("❌ Failed to apply schema: %v", err)
}
}
return db
}

View File

@@ -4,19 +4,19 @@ package storage
import (
"context"
"database/sql"
"errors"
"synlotto-website/internal/models"
)
type UsersRepo struct{ db *sql.DB}
type UsersRepo struct{ db *sql.DB }
func NewUsersRepo(db *.sql.DB) *UsersRepo { return &UsersRepo{db: db} }
func NewUsersRepo(db *sql.DB) *UsersRepo {
return &UsersRepo{db: db}
}
// ToDo: should the function be in sql?
func (r *UsersRepo) Create(ctx context.Context, username, passwordHash string, isAdmin bool) error {
_, err := r.db.ExecContext(ctx,
`INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)`,
username, passwordHash, isAdmin,
)
return err
}
}