threadr-rewritten/handlers/boards.go

67 lines
2.4 KiB
Go

package handlers
import (
"log"
"net/http"
"github.com/gorilla/sessions"
"threadr/models"
)
func BoardsHandler(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
userID, _ := session.Values["user_id"].(int)
publicBoards, err := models.GetAllBoards(app.DB, false)
if err != nil {
log.Printf("Error fetching public boards: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
var privateBoards []models.Board
if loggedIn {
privateBoards, err = models.GetAllBoards(app.DB, true)
if err != nil {
log.Printf("Error fetching private boards: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
var accessiblePrivateBoards []models.Board
for _, board := range privateBoards {
hasPerm, err := models.HasBoardPermission(app.DB, userID, board.ID, models.PermViewBoard)
if err != nil {
log.Printf("Error checking permission: %v", err)
continue
}
if hasPerm {
accessiblePrivateBoards = append(accessiblePrivateBoards, board)
}
}
privateBoards = accessiblePrivateBoards
}
data := struct {
PageData
PublicBoards []models.Board
PrivateBoards []models.Board
}{
PageData: PageData{
Title: "ThreadR - Boards",
Navbar: "boards",
LoggedIn: loggedIn,
ShowCookieBanner: true,
BasePath: app.Config.ThreadrDir,
StaticPath: app.Config.ThreadrDir + "/static",
CurrentURL: r.URL.Path,
},
PublicBoards: publicBoards,
PrivateBoards: privateBoards,
}
if err := app.Tmpl.ExecuteTemplate(w, "boards", data); err != nil {
log.Printf("Error executing template in BoardsHandler: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
}