expand on admin functionality, hardening still needs to be implemented.

This commit is contained in:
2025-03-31 10:52:12 +01:00
parent b466c351da
commit c3a7480c65
15 changed files with 447 additions and 13 deletions

View File

@@ -0,0 +1,68 @@
package handlers
import (
"database/sql"
"html/template"
"log"
"net/http"
helpers "synlotto-website/helpers"
"synlotto-website/models"
)
func AdminDashboardHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
// userID, ok := helpers.GetCurrentUserID(r)
// if !ok {
// http.Redirect(w, r, "/login", http.StatusSeeOther)
// return
// }
// TODO: check is_admin from users table here
context := helpers.TemplateContext(w, r)
// Total ticket stats
var total, winners int
var prizeSum float64
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,
"TotalWinners": winners,
"TotalPrizeAmount": prizeSum,
}
// Match run log
rows, err := db.Query(`
SELECT run_at, triggered_by, tickets_matched, winners_found, COALESCE(notes, '')
FROM log_ticket_matching
ORDER BY run_at DESC LIMIT 10
`)
if err != nil {
log.Println("⚠️ Failed to load logs:", err)
}
defer rows.Close()
var logs []models.MatchLog
for rows.Next() {
var logEntry models.MatchLog
err := rows.Scan(&logEntry.RunAt, &logEntry.TriggeredBy, &logEntry.TicketsMatched, &logEntry.WinnersFound, &logEntry.Notes)
if err != nil {
log.Println("⚠️ Failed to scan log row:", err)
continue
}
logs = append(logs, logEntry)
}
context["MatchLogs"] = logs
tmpl := template.Must(template.New("").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/admin/dashboard.html",
))
err = tmpl.ExecuteTemplate(w, "layout", context)
if err != nil {
http.Error(w, "Failed to render dashboard", http.StatusInternalServerError)
}
})
}

72
handlers/admin/draws.go Normal file
View File

@@ -0,0 +1,72 @@
package handlers
import (
"database/sql"
"html/template"
"net/http"
helpers "synlotto-website/helpers"
)
func NewDrawHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
context := helpers.TemplateContext(w, r)
if r.Method == http.MethodPost {
game := r.FormValue("game_type")
date := r.FormValue("draw_date")
machine := r.FormValue("machine")
ballset := r.FormValue("ball_set")
_, err := db.Exec(`INSERT INTO results_thunderball (game_type, draw_date, machine, ball_set) VALUES (?, ?, ?, ?)`,
game, date, machine, ballset)
if err != nil {
http.Error(w, "Failed to add draw", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/admin/dashboard", http.StatusSeeOther)
return
}
tmpl := template.Must(template.New("new_draw").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/admin/draws/new_draw.html",
))
tmpl.ExecuteTemplate(w, "layout", context)
})
}
func ModifyDrawHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
id := r.FormValue("id")
_, err := db.Exec(`UPDATE results_thunderball SET game_type=?, draw_date=?, ball_set=?, machine=? WHERE id=?`,
r.FormValue("game_type"), r.FormValue("draw_date"), r.FormValue("ball_set"), r.FormValue("machine"), id)
if err != nil {
http.Error(w, "Update failed", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/admin/dashboard", http.StatusSeeOther)
return
}
// For GET: load draw by ID (pseudo-code)
// id := r.URL.Query().Get("id")
// query DB, pass into context.Draw
})
}
func DeleteDrawHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
id := r.FormValue("id")
_, err := db.Exec(`DELETE FROM results_thunderball WHERE id = ?`, id)
if err != nil {
http.Error(w, "Delete failed", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/admin/dashboard", http.StatusSeeOther)
return
}
})
}

70
handlers/admin/prizes.go Normal file
View File

@@ -0,0 +1,70 @@
package handlers
import (
"database/sql"
"fmt"
"html/template"
"net/http"
"strconv"
"synlotto-website/helpers"
)
func AddPrizesHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
tmpl := template.Must(template.New("").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/admin/draws/prizes/add_prizes.html",
))
tmpl.ExecuteTemplate(w, "layout", helpers.TemplateContext(w, r))
return
}
drawDate := r.FormValue("draw_date")
values := make([]interface{}, 0)
for i := 1; i <= 9; i++ {
val, _ := strconv.Atoi(r.FormValue(fmt.Sprintf("prize%d_per_winner", i)))
values = append(values, val)
}
stmt := `INSERT INTO prizes_thunderball (
draw_date, prize1_per_winner, prize2_per_winner, prize3_per_winner,
prize4_per_winner, prize5_per_winner, prize6_per_winner,
prize7_per_winner, prize8_per_winner, prize9_per_winner
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
_, err := db.Exec(stmt, append([]interface{}{drawDate}, values...)...)
if err != nil {
http.Error(w, "Insert failed: "+err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/admin/draws", http.StatusSeeOther)
})
}
func ModifyPrizesHandler(db *sql.DB) http.HandlerFunc {
return helpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
tmpl := template.Must(template.New("").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/admin/draws/prizes/modify_prizes.html",
))
tmpl.ExecuteTemplate(w, "layout", helpers.TemplateContext(w, r))
return
}
drawDate := r.FormValue("draw_date")
for i := 1; i <= 9; i++ {
key := fmt.Sprintf("prize%d_per_winner", i)
val, _ := strconv.Atoi(r.FormValue(key))
_, err := db.Exec("UPDATE prizes_thunderball SET "+key+" = ? WHERE draw_date = ?", val, drawDate)
if err != nil {
http.Error(w, "Update failed: "+err.Error(), http.StatusInternalServerError)
return
}
}
http.Redirect(w, r, "/admin/draws", http.StatusSeeOther)
})
}