- 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
58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"net/http"
|
|
"strconv"
|
|
"text/template"
|
|
|
|
"synlotto-website/helpers"
|
|
"synlotto-website/storage"
|
|
)
|
|
|
|
func NotificationsHandler(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
data := BuildTemplateData(db, w, r)
|
|
context := helpers.TemplateContext(w, r, data)
|
|
|
|
tmpl := template.Must(template.New("notifications.html").
|
|
Funcs(helpers.TemplateFuncs()).
|
|
ParseFiles(
|
|
"templates/layout.html",
|
|
"templates/topbar.html",
|
|
"templates/account/notifications/index.html",
|
|
))
|
|
|
|
err := tmpl.ExecuteTemplate(w, "layout", context)
|
|
if err != nil {
|
|
http.Error(w, "Error rendering notifications page", http.StatusInternalServerError)
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|