package handlers import ( "context" "net/http" "strconv" "git.haelnorr.com/h/golib/hws" "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 *db.DB, ssl bool) 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 := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error role, err = db.GetRoleByID(ctx, tx, roleID) if err != nil { if db.IsBadRequest(err) { throw.NotFound(s, w, r, "Role not found") return false, nil } return false, errors.Wrap(err, "db.GetRoleByID") } // 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, 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) } }) }