Compare commits

...

6 Commits

Author SHA1 Message Date
9df4b173fb remove println 2025-03-26 09:43:01 +00:00
c736b95c50 remove println 2025-03-26 09:42:44 +00:00
06a7296285 update my tickets table creation 2025-03-26 09:42:02 +00:00
8dc4f61089 new helper for adding tickets 2025-03-26 09:41:39 +00:00
eae4561e1f new ticket functions 2025-03-26 09:41:22 +00:00
41ce9a3dd0 Move around endpoints. 2025-03-26 09:41:01 +00:00
6 changed files with 141 additions and 42 deletions

View File

@@ -2,63 +2,145 @@ package handlers
import ( import (
"database/sql" "database/sql"
"fmt"
"html/template" "html/template"
"io"
"log" "log"
"net/http" "net/http"
"os"
"strconv"
"synlotto-website/helpers" "synlotto-website/helpers"
"synlotto-website/models" "synlotto-website/models"
"synlotto-website/storage" "time"
"github.com/gorilla/csrf" "github.com/gorilla/csrf"
) )
func NewTicket(db *sql.DB) http.HandlerFunc { func AddTicket(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
log.Println("➡️ New ticket form opened") rows, err := db.Query(`
SELECT DISTINCT draw_date
FROM results_thunderball
ORDER BY draw_date DESC
`)
if err != nil {
log.Println("❌ Failed to load draw dates:", err)
http.Error(w, "Unable to load draw dates", http.StatusInternalServerError)
return
}
defer rows.Close()
tmpl := template.Must(template.ParseFiles( var drawDates []string
for rows.Next() {
var date string
if err := rows.Scan(&date); err == nil {
drawDates = append(drawDates, date)
}
}
context := helpers.TemplateContext(w, r)
context["csrfField"] = csrf.TemplateField(r)
context["DrawDates"] = drawDates
tmpl := template.Must(template.New("").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html", "templates/layout.html",
"templates/new_ticket.html", "templates/account/tickets/add_ticket.html",
)) ))
err := tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{ err = tmpl.ExecuteTemplate(w, "layout", context)
"csrfField": csrf.TemplateField(r),
"Page": "new_ticket",
"Data": nil,
})
if err != nil { if err != nil {
log.Println("❌ Template error:", err) log.Println("❌ Template render error:", err)
http.Error(w, "Error rendering form", http.StatusInternalServerError) http.Error(w, "Error rendering form", http.StatusInternalServerError)
} }
} })
} }
func SubmitTicket(db *sql.DB) http.HandlerFunc { func SubmitTicket(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if _, ok := helpers.GetCurrentUserID(r); !ok { err := r.ParseMultipartForm(10 << 20)
if err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
userID, ok := helpers.GetCurrentUserID(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther) http.Redirect(w, r, "/login", http.StatusSeeOther)
return return
} }
ticket := models.MyTicket{
GameType: r.FormValue("game_type"), game := r.FormValue("game_type")
DrawDate: r.FormValue("draw_date"), drawDate := r.FormValue("draw_date")
Ball1: helpers.Atoi(r.FormValue("ball1")), purchaseMethod := r.FormValue("purchase_method")
Ball2: helpers.Atoi(r.FormValue("ball2")), purchaseDate := r.FormValue("purchase_date")
Ball3: helpers.Atoi(r.FormValue("ball3")), purchaseTime := r.FormValue("purchase_time")
Ball4: helpers.Atoi(r.FormValue("ball4")),
Ball5: helpers.Atoi(r.FormValue("ball5")), if purchaseTime != "" {
Bonus1: helpers.Nullable(helpers.Atoi(r.FormValue("bonus1"))), purchaseDate += "T" + purchaseTime
Bonus2: helpers.Nullable(helpers.Atoi(r.FormValue("bonus2"))),
} }
if err := storage.InsertTicket(db, ticket); err != nil { imagePath := ""
log.Println("❌ Failed to insert ticket:", err) file, handler, err := r.FormFile("ticket_image")
http.Error(w, "Error storing ticket", http.StatusInternalServerError) if err == nil && handler != nil {
return defer file.Close()
filename := fmt.Sprintf("uploads/ticket_%d_%s", time.Now().UnixNano(), handler.Filename)
out, err := os.Create(filename)
if err == nil {
defer out.Close()
io.Copy(out, file)
imagePath = filename
}
} }
http.Redirect(w, r, "/", http.StatusSeeOther) ballCount := 6
} bonusCount := 2
balls := make([][]int, ballCount)
bonuses := make([][]int, bonusCount)
for i := 1; i <= ballCount; i++ {
balls[i-1] = helpers.ParseIntSlice(r.Form["ball"+strconv.Itoa(i)])
}
for i := 1; i <= bonusCount; i++ {
bonuses[i-1] = helpers.ParseIntSlice(r.Form["bonus"+strconv.Itoa(i)])
}
lineCount := len(balls[0])
for i := 0; i < lineCount; i++ {
var b [6]int
var bo [2]int
for j := 0; j < ballCount; j++ {
if j < len(balls) && i < len(balls[j]) {
b[j] = balls[j][i]
}
}
for j := 0; j < bonusCount; j++ {
if j < len(bonuses) && i < len(bonuses[j]) {
bo[j] = bonuses[j][i]
}
}
_, err := db.Exec(`
INSERT INTO my_tickets (
user_id, game_type, draw_date,
ball1, ball2, ball3, ball4, ball5, ball6,
bonus1, bonus2,
purchase_method, purchase_date, image_path
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
userID, game, drawDate,
b[0], b[1], b[2], b[3], b[4], b[5],
bo[0], bo[1],
purchaseMethod, purchaseDate, imagePath,
)
if err != nil {
log.Println("❌ Insert failed:", err)
}
}
http.Redirect(w, r, "/tickets", http.StatusSeeOther)
})
} }
func ListTickets(db *sql.DB) http.HandlerFunc { func ListTickets(db *sql.DB) http.HandlerFunc {

14
helpers/parse.go Normal file
View File

@@ -0,0 +1,14 @@
package helpers
import "strconv"
func ParseIntSlice(input []string) []int {
var out []int
for _, s := range input {
n, err := strconv.Atoi(s)
if err == nil {
out = append(out, n)
}
}
return out
}

View File

@@ -2,7 +2,6 @@ package helpers
import ( import (
"html/template" "html/template"
"log"
"net/http" "net/http"
"synlotto-website/models" "synlotto-website/models"
) )
@@ -48,8 +47,6 @@ func TemplateContext(w http.ResponseWriter, r *http.Request) map[string]interfac
currentUser = nil currentUser = nil
} }
log.Printf("🧪 TemplateContext user: %#v", currentUser)
return map[string]interface{}{ return map[string]interface{}{
"Flash": flash, "Flash": flash,
"User": currentUser, "User": currentUser,

10
main.go
View File

@@ -27,17 +27,15 @@ func main() {
mux.HandleFunc("/", handlers.Home(db)) mux.HandleFunc("/", handlers.Home(db))
mux.HandleFunc("/new", handlers.NewDraw) // ToDo: needs to be wrapped in admin auth mux.HandleFunc("/new", handlers.NewDraw) // ToDo: needs to be wrapped in admin auth
mux.HandleFunc("/submit", handlers.Submit) mux.HandleFunc("/submit", handlers.Submit)
//mux.HandleFunc("/tickets", middleware.Auth(true)(handlers.ListTickets(db)))
//mux.HandleFunc("/submit-ticket", helpers.AuthMiddleware(handlers.SubmitTicket(db)))
mux.HandleFunc("/login", middleware.Auth(false)(handlers.Login))
mux.HandleFunc("/logout", handlers.Logout)
mux.HandleFunc("/signup", middleware.Auth(false)(handlers.Signup))
// Result pages // Result pages
mux.HandleFunc("/results/thunderball", handlers.ResultsThunderball(db)) mux.HandleFunc("/results/thunderball", handlers.ResultsThunderball(db))
// Account Pages // Account Pages
mux.HandleFunc("account/ticket/add_ticket", middleware.Auth(true)(handlers.NewTicket(db))) mux.HandleFunc("/login", middleware.Auth(false)(handlers.Login))
mux.HandleFunc("/logout", handlers.Logout)
mux.HandleFunc("/signup", middleware.Auth(false)(handlers.Signup))
mux.HandleFunc("/account/tickets/add_ticket", middleware.Auth(true)(handlers.AddTicket(db)))
log.Println("🌐 Running on http://localhost:8080") log.Println("🌐 Running on http://localhost:8080")
http.ListenAndServe(":8080", helpers.RateLimit(csrfMiddleware(mux))) http.ListenAndServe(":8080", helpers.RateLimit(csrfMiddleware(mux)))

View File

@@ -20,6 +20,7 @@ func SetDB(database *sql.DB) {
func CreateUser(username, passwordHash string) error { func CreateUser(username, passwordHash string) error {
_, err := db.Exec("INSERT INTO users (username, password_hash) VALUES (?, ?)", username, passwordHash) _, err := db.Exec("INSERT INTO users (username, password_hash) VALUES (?, ?)", username, passwordHash)
return err return err
} }
@@ -34,6 +35,7 @@ func GetUserByUsername(username string) *User {
} }
return nil return nil
} }
return &user return &user
} }
@@ -48,7 +50,7 @@ func GetUserByID(id int) *User {
} }
return nil return nil
} }
log.Printf("📦 Looking up user ID %d", id)
return &user return &user
} }
@@ -62,7 +64,9 @@ func LogLoginAttempt(username string, success bool) {
func boolToInt(b bool) int { func boolToInt(b bool) int {
if b { if b {
return 1 return 1
} }
return 0 return 0
} }

View File

@@ -34,6 +34,7 @@ func InitDB(filepath string) *sql.DB {
createMyTicketsTable := ` createMyTicketsTable := `
CREATE TABLE IF NOT EXISTS my_tickets ( CREATE TABLE IF NOT EXISTS my_tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
userId INTEGER NOT NULL,
game_type TEXT NOT NULL, game_type TEXT NOT NULL,
draw_date TEXT NOT NULL, draw_date TEXT NOT NULL,
ball1 INTEGER, ball1 INTEGER,
@@ -44,7 +45,10 @@ func InitDB(filepath string) *sql.DB {
bonus1 INTEGER, bonus1 INTEGER,
bonus2 INTEGER, bonus2 INTEGER,
duplicate BOOLEAN DEFAULT 0, duplicate BOOLEAN DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP purchased_date TEXT,
purchased_location TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (userId) REFERENCES users(id)
);` );`
if _, err := db.Exec(createMyTicketsTable); err != nil { if _, err := db.Exec(createMyTicketsTable); err != nil {