website/pkg/controller/forum/manage.go
Noah Petherbridge 1bf846e78b Forum Admin Page for Regular Users
Allow regular (non-admin) users access to the Manage Forums page so they can
create and manage their own forums.

Things that were already working:

* The admin forum page was already anticipating regular LoginRequired credential
* Users only see their owned forums, while admins can see and manage ALL forums

Improvements made to the Forum Admin page:

* Change the title color from admin-red to user-blue.
* Add ability to search (filter) and sort the forums.

Other changes:

* Turn the Forum tab bar into a reusable component.
2024-08-23 22:56:40 -07:00

80 lines
1.8 KiB
Go

package forum
import (
"net/http"
"code.nonshy.com/nonshy/website/pkg/config"
"code.nonshy.com/nonshy/website/pkg/models"
"code.nonshy.com/nonshy/website/pkg/session"
"code.nonshy.com/nonshy/website/pkg/templates"
)
// Manage page for forums -- admin only for now but may open up later.
func Manage() http.HandlerFunc {
tmpl := templates.Must("forum/admin.html")
// Whitelist for ordering options.
var sortWhitelist = []string{
"updated_at desc",
"created_at desc",
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
searchTerm = r.FormValue("q")
sort = r.FormValue("sort")
sortOK bool
)
// Sort options.
for _, v := range sortWhitelist {
if sort == v {
sortOK = true
break
}
}
if !sortOK {
sort = sortWhitelist[0]
}
// Get the current user.
currentUser, err := session.CurrentUser(r)
if err != nil {
session.FlashError(w, r, "Couldn't get current user: %s", err)
templates.Redirect(w, "/")
return
}
// Parse their search term.
var search = models.ParseSearchString(searchTerm)
// Get forums the user owns or can manage.
var pager = &models.Pagination{
Page: 1,
PerPage: config.PageSizeForumAdmin,
Sort: sort,
}
pager.ParsePage(r)
forums, err := models.PaginateOwnedForums(currentUser.ID, currentUser.IsAdmin, search, pager)
if err != nil {
session.FlashError(w, r, "Couldn't paginate owned forums: %s", err)
templates.Redirect(w, "/")
return
}
var vars = map[string]interface{}{
"Pager": pager,
"Forums": forums,
// Search filters.
"SearchTerm": searchTerm,
"Sort": sort,
}
if err := tmpl.Execute(w, r, vars); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
}