1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
<?php
namespace Icinga\Module\Director\Web\Controller\Extension;
use Icinga\Exception\AuthenticationException;
use Icinga\Exception\NotFoundError;
use Icinga\Module\Director\Exception\JsonException;
use Icinga\Web\Response;
use InvalidArgumentException;
use Zend_Controller_Response_Exception;
trait RestApi
{
protected function isApified()
{
if (property_exists($this, 'isApified')) {
return $this->isApified;
} else {
return false;
}
}
/**
* @return bool
*/
protected function sendNotFoundForRestApi()
{
/** @var \Icinga\Web\Request $request */
$request = $this->getRequest();
if ($request->isApiRequest()) {
$this->sendJsonError($this->getResponse(), 'Not found', 404);
return true;
} else {
return false;
}
}
/**
* @return bool
*/
protected function sendNotFoundUnlessRestApi()
{
/** @var \Icinga\Web\Request $request */
$request = $this->getRequest();
if ($request->isApiRequest()) {
return false;
} else {
$this->sendJsonError($this->getResponse(), 'Not found', 404);
return true;
}
}
/**
* @throws AuthenticationException
*/
protected function assertApiPermission()
{
if (! $this->hasPermission('director/api')) {
throw new AuthenticationException('You are not allowed to access this API');
}
}
/**
* @throws AuthenticationException
* @throws NotFoundError
*/
protected function checkForRestApiRequest()
{
/** @var \Icinga\Web\Request $request */
$request = $this->getRequest();
if ($request->isApiRequest()) {
$this->assertApiPermission();
if (! $this->isApified()) {
throw new NotFoundError('No such API endpoint found');
}
}
}
/**
* @param Response $response
* @param $object
*/
protected function sendJson(Response $response, $object)
{
$response->setHeader('Content-Type', 'application/json', true);
echo json_encode($object, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
}
/**
* @param Response $response
* @param string $message
* @param int|null $code
*/
protected function sendJsonError(Response $response, $message, $code = null)
{
if ($code !== null) {
try {
$response->setHttpResponseCode((int) $code);
} catch (Zend_Controller_Response_Exception $e) {
throw new InvalidArgumentException($e->getMessage(), 0, $e);
}
}
$this->sendJson($response, (object) ['error' => $message]);
}
/**
* @return string
*/
protected function getLastJsonError()
{
return JsonException::getJsonErrorMessage(json_last_error());
}
}
|