admin page updates
This commit is contained in:
80
internal/handlers/admin_preview_role.go
Normal file
80
internal/handlers/admin_preview_role.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/oslstats/internal/config"
|
||||
"git.haelnorr.com/h/oslstats/internal/db"
|
||||
"git.haelnorr.com/h/oslstats/internal/rbac"
|
||||
"git.haelnorr.com/h/oslstats/internal/roles"
|
||||
"git.haelnorr.com/h/oslstats/internal/throw"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
// AdminPreviewRoleStart starts preview mode for a specific role
|
||||
func AdminPreviewRoleStart(s *hws.Server, conn *bun.DB, cfg *config.Config) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Get role ID from URL
|
||||
roleIDStr := r.PathValue("id")
|
||||
roleID, err := strconv.Atoi(roleIDStr)
|
||||
if err != nil {
|
||||
throw.BadRequest(s, w, r, "Invalid role ID", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Verify role exists and is not admin
|
||||
var role *db.Role
|
||||
if ok := db.WithReadTx(s, w, r, conn, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
||||
var err error
|
||||
role, err = db.GetRoleByID(ctx, tx, roleID)
|
||||
if err != nil {
|
||||
return false, errors.Wrap(err, "db.GetRoleByID")
|
||||
}
|
||||
if role == nil {
|
||||
throw.NotFound(s, w, r, "Role not found")
|
||||
return false, nil
|
||||
}
|
||||
// Cannot preview admin role
|
||||
if role.Name == roles.Admin {
|
||||
throw.BadRequest(s, w, r, "Cannot preview admin role", nil)
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Set preview role cookie
|
||||
rbac.SetPreviewRoleCookie(w, roleID, cfg.HWSAuth.SSL)
|
||||
|
||||
// Redirect to home page
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
})
|
||||
}
|
||||
|
||||
// AdminPreviewRoleStop stops preview mode and returns to normal view
|
||||
func AdminPreviewRoleStop(s *hws.Server) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Clear preview role cookie
|
||||
rbac.ClearPreviewRoleCookie(w)
|
||||
|
||||
// Check if we should stay on current page or redirect to admin
|
||||
stay := r.URL.Query().Get("stay")
|
||||
|
||||
if stay == "true" {
|
||||
// Get referer to redirect back to current page
|
||||
referer := r.Header.Get("Referer")
|
||||
if referer == "" {
|
||||
referer = "/"
|
||||
}
|
||||
http.Redirect(w, r, referer, http.StatusSeeOther)
|
||||
} else {
|
||||
// Redirect to admin roles page
|
||||
http.Redirect(w, r, "/admin/roles", http.StatusSeeOther)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user