Feature: Add account-protected route to mark notifications as read

- Created /account/notifications/read endpoint secured by session middleware
- Ensured users can only mark their own notifications as read
- Updated dropdown links to point to /account/notifications/read?id={id}
- Improved notification security by matching user_id in DB update
- Added redirect flow to full notifications page after marking read
- Logged DB errors to assist debugging
This commit is contained in:
2025-04-01 22:12:41 +01:00
parent 1e372da57d
commit 06e647d00f
5 changed files with 74 additions and 8 deletions

View File

@@ -3,9 +3,11 @@ package handlers
import (
"database/sql"
"net/http"
"strconv"
"text/template"
"synlotto-website/helpers"
"synlotto-website/storage"
)
func NotificationsHandler(db *sql.DB) http.HandlerFunc {
@@ -18,7 +20,7 @@ func NotificationsHandler(db *sql.DB) http.HandlerFunc {
ParseFiles(
"templates/layout.html",
"templates/topbar.html",
"templates/notifications/index.html",
"templates/account/notifications/index.html",
))
err := tmpl.ExecuteTemplate(w, "layout", context)
@@ -27,3 +29,29 @@ func NotificationsHandler(db *sql.DB) http.HandlerFunc {
}
}
}
func MarkNotificationReadHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
notificationIDStr := r.URL.Query().Get("id")
notificationID, err := strconv.Atoi(notificationIDStr)
if err != nil {
http.Error(w, "Invalid notification ID", http.StatusBadRequest)
return
}
session, _ := helpers.GetSession(w, r)
userID, ok := session.Values["user_id"].(int)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
err = storage.MarkNotificationAsRead(db, userID, notificationID)
if err != nil {
http.Error(w, "Failed to update", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/account/notifications", http.StatusSeeOther)
}
}