84 lines
1.9 KiB
Go

package routes
import (
"dk/internal/components"
"dk/internal/models/news"
"dk/internal/models/users"
"runtime"
"strings"
"time"
sushi "git.sharkk.net/Sharkk/Sushi"
"git.sharkk.net/Sharkk/Sushi/auth"
)
func RegisterAdminRoutes(app *sushi.App) {
group := app.Group("/admin")
group.Use(auth.RequireAuth())
group.Use(func(ctx sushi.Ctx, next func()) {
if ctx.GetCurrentUser().(*users.User).Auth < 4 {
ctx.Redirect("/")
return
}
next()
})
group.Get("/", adminIndex)
group.Get("/news", adminNewsForm)
group.Post("/news", adminNewsCreate)
}
func adminIndex(ctx sushi.Ctx) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
components.RenderAdminPage(ctx, "", "admin/home.html", map[string]any{
"alloc_mb": bToMb(m.Alloc),
"total_alloc_mb": bToMb(m.TotalAlloc),
"sys_mb": bToMb(m.Sys),
"heap_alloc_mb": bToMb(m.HeapAlloc),
"heap_sys_mb": bToMb(m.HeapSys),
"heap_released_mb": bToMb(m.HeapReleased),
"gc_cycles": m.NumGC,
"gc_pause_total": m.PauseTotalNs / 1000000, // ms
"goroutines": runtime.NumGoroutine(),
"cpu_cores": runtime.NumCPU(),
"go_version": runtime.Version(),
})
}
func adminNewsForm(ctx sushi.Ctx) {
components.RenderAdminPage(ctx, "", "admin/news.html", map[string]any{})
}
func adminNewsCreate(ctx sushi.Ctx) {
sess := ctx.GetCurrentSession()
content := strings.TrimSpace(ctx.Form("content").String())
if content == "" {
sess.SetFlash("error", "Content cannot be empty")
ctx.Redirect("/admin/news")
return
}
user := ctx.GetCurrentUser().(*users.User)
newsPost := &news.News{
Author: user.ID,
Content: content,
Posted: time.Now().Unix(),
}
if err := newsPost.Insert(); err != nil {
sess.SetFlash("error", "Failed to create news post")
ctx.Redirect("/admin/news")
return
}
sess.SetFlash("success", "News post created successfully")
ctx.Redirect("/admin")
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}