90 lines
2.5 KiB
Go
90 lines
2.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"threadr/models"
|
|
|
|
"github.com/gorilla/sessions"
|
|
)
|
|
|
|
func AdminHandler(app *App) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
session := r.Context().Value("session").(*sessions.Session)
|
|
userID, ok := session.Values["user_id"].(int)
|
|
if !ok {
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/login/", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
user, err := models.GetUserByID(app.DB, userID)
|
|
if err != nil {
|
|
log.Printf("Error fetching user in AdminHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if user == nil || !models.HasGlobalPermission(user, models.PermManageUsers) {
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
cookie, _ := r.Cookie("threadr_cookie_banner")
|
|
|
|
if r.Method == http.MethodPost {
|
|
if !app.validateCSRFToken(r, session) {
|
|
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
allowSignup := r.FormValue("allow_signup") == "on"
|
|
if err := models.SetAllowSignup(app.DB, allowSignup); err != nil {
|
|
log.Printf("Error updating site settings in AdminHandler: %v", err)
|
|
http.Error(w, "Failed to save settings", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/admin/?saved=true", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
settings, err := models.GetSiteSettings(app.DB)
|
|
if err != nil {
|
|
log.Printf("Error fetching site settings in AdminHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
data := struct {
|
|
PageData
|
|
AllowSignup bool
|
|
ShowSuccess bool
|
|
}{
|
|
PageData: PageData{
|
|
Title: "ThreadR - Admin",
|
|
Navbar: "admin",
|
|
LoggedIn: true,
|
|
IsAdmin: true,
|
|
AllowSignup: settings.AllowSignup,
|
|
ShowCookieBanner: cookie == nil || cookie.Value != "accepted",
|
|
BasePath: app.Config.ThreadrDir,
|
|
StaticPath: app.Config.ThreadrDir + "/static",
|
|
CurrentURL: r.URL.RequestURI(),
|
|
CSRFToken: app.csrfToken(session),
|
|
},
|
|
AllowSignup: settings.AllowSignup,
|
|
ShowSuccess: r.URL.Query().Get("saved") == "true",
|
|
}
|
|
|
|
if err := app.Tmpl.ExecuteTemplate(w, "admin", data); err != nil {
|
|
log.Printf("Error executing template in AdminHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
}
|