From 2b474823f8a2697d474e6e84f61e23cd70c17007 Mon Sep 17 00:00:00 2001
From: Michael Friedrich
Date: Wed, 11 May 2016 10:28:44 +0200
Subject: [PATCH] API: Fix that /v1 returns html if json is requested
fixes #10570
---
lib/remote/infohandler.cpp | 62 +++++++++++++++++++++++++-------------
1 file changed, 41 insertions(+), 21 deletions(-)
diff --git a/lib/remote/infohandler.cpp b/lib/remote/infohandler.cpp
index 058ca51de..04c0c90f4 100644
--- a/lib/remote/infohandler.cpp
+++ b/lib/remote/infohandler.cpp
@@ -42,43 +42,63 @@ bool InfoHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
return false;
response.SetStatus(200, "OK");
- response.AddHeader("Content-Type", "text/html");
-
- String body = "Icinga 2Hello from Icinga 2!
";
- body += "You are authenticated as " + user->GetName() + ". ";
-
- bool has_permissions = false;
- String perm_info;
+ std::vector permInfo;
Array::Ptr permissions = user->GetPermissions();
+
if (permissions) {
ObjectLock olock(permissions);
BOOST_FOREACH(const Value& permission, permissions) {
- has_permissions = true;
-
String name;
- bool has_filter = false;
+ bool hasFilter = false;
if (permission.IsObjectType()) {
Dictionary::Ptr dpermission = permission;
name = dpermission->Get("permission");
- has_filter = dpermission->Contains("filter");
+ hasFilter = dpermission->Contains("filter");
} else
name = permission;
- perm_info += "" + name;
- if (has_filter)
- perm_info += " (filtered)";
- perm_info += "";
+ if (hasFilter)
+ name += " (filtered)";
+
+ permInfo.push_back(name);
}
}
- if (has_permissions)
- body += "Your user has the following permissions:
";
- else
- body += "Your user does not have any permissions.
";
+ if (request.Headers->Get("accept") == "application/json") {
+ Dictionary::Ptr result1 = new Dictionary();
+
+ result1->Set("user", user->GetName());
+ result1->Set("permissions", Array::FromVector(permInfo));
+ result1->Set("info", "More information about API requests is available in the documentation at http://docs.icinga.org/icinga2/latest.");
+
+ Array::Ptr results = new Array();
+ results->Add(result1);
- body += "More information about API requests is available in the documentation.
";
- response.WriteBody(body.CStr(), body.GetLength());
+ Dictionary::Ptr result = new Dictionary();
+ result->Set("results", results);
+
+ HttpUtility::SendJsonBody(response, result);
+ } else {
+ response.AddHeader("Content-Type", "text/html");
+
+ String body = "Icinga 2Hello from Icinga 2!
";
+ body += "You are authenticated as " + user->GetName() + ". ";
+
+ if (!permInfo.empty()) {
+ body += "Your user has the following permissions:
";
+
+ BOOST_FOREACH(const String& perm, permInfo) {
+ body += "- " + perm + "
";
+ }
+
+ body += "
";
+ } else
+ body += "Your user does not have any permissions.";
+
+ body += "More information about API requests is available in the documentation.
";
+ response.WriteBody(body.CStr(), body.GetLength());
+ }
return true;
}
--
2.49.0