98 lines
3.6 KiB
Go
98 lines
3.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"threadr/models"
|
|
"github.com/gorilla/sessions"
|
|
)
|
|
|
|
func NewsHandler(app *App) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
session := r.Context().Value("session").(*sessions.Session)
|
|
loggedIn := session.Values["user_id"] != nil
|
|
cookie, _ := r.Cookie("threadr_cookie_banner")
|
|
userID, _ := session.Values["user_id"].(int)
|
|
isAdmin := false
|
|
|
|
if loggedIn {
|
|
user, err := models.GetUserByID(app.DB, userID)
|
|
if err != nil {
|
|
log.Printf("Error fetching user: %v", err)
|
|
} else if user != nil {
|
|
isAdmin = models.HasGlobalPermission(user, models.PermManageUsers)
|
|
}
|
|
}
|
|
|
|
if r.Method == http.MethodPost && loggedIn && isAdmin {
|
|
if action := r.URL.Query().Get("action"); action == "delete" {
|
|
newsIDStr := r.URL.Query().Get("id")
|
|
newsID, err := strconv.Atoi(newsIDStr)
|
|
if err != nil {
|
|
http.Error(w, "Invalid news ID", http.StatusBadRequest)
|
|
return
|
|
}
|
|
err = models.DeleteNews(app.DB, newsID)
|
|
if err != nil {
|
|
log.Printf("Error deleting news item: %v", err)
|
|
http.Error(w, "Failed to delete news item", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/news/", http.StatusFound)
|
|
return
|
|
} else {
|
|
title := r.FormValue("title")
|
|
content := r.FormValue("content")
|
|
if title != "" && content != "" {
|
|
news := models.News{
|
|
Title: title,
|
|
Content: content,
|
|
PostedBy: userID,
|
|
}
|
|
err := models.CreateNews(app.DB, news)
|
|
if err != nil {
|
|
log.Printf("Error creating news item: %v", err)
|
|
http.Error(w, "Failed to create news item", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/news/", http.StatusFound)
|
|
return
|
|
} else {
|
|
http.Error(w, "Title and content are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
newsItems, err := models.GetAllNews(app.DB)
|
|
if err != nil {
|
|
log.Printf("Error fetching news items: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
data := struct {
|
|
PageData
|
|
News []models.News
|
|
IsAdmin bool
|
|
}{
|
|
PageData: PageData{
|
|
Title: "ThreadR - News",
|
|
Navbar: "news",
|
|
LoggedIn: loggedIn,
|
|
ShowCookieBanner: cookie == nil || cookie.Value != "accepted",
|
|
BasePath: app.Config.ThreadrDir,
|
|
StaticPath: app.Config.ThreadrDir + "/static",
|
|
CurrentURL: r.URL.Path,
|
|
},
|
|
News: newsItems,
|
|
IsAdmin: isAdmin,
|
|
}
|
|
if err := app.Tmpl.ExecuteTemplate(w, "news", data); err != nil {
|
|
log.Printf("Error executing template in NewsHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
} |