-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapi.php
96 lines (79 loc) · 2.23 KB
/
api.php
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
<?php
namespace Grav\Plugin;
use Grav\Common\Grav;
use Grav\Common\Plugin;
use Grav\Common\User\User;
class ApiPlugin extends Plugin
{
protected $route = 'api';
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPagesInitialized' => ['onPagesInitialized', 0],
];
}
public function onPagesInitialized()
{
$uri = $this->grav['uri'];
if (strpos($uri->path(), $this->config->get('plugins.api.route') . '/' . $this->route) === false) {
return;
}
if (!$this->isAuthorized()) {
header('HTTP/1.1 401 Unauthorized');
exit();
}
$paths = $this->grav['uri']->paths();
$paths = array_splice($paths, 1);
$resource = $paths[0];
if ($resource) {
$file = __DIR__ . '/resources/' . $resource . '.php';
if (file_exists($file)) {
require_once $file;
$resourceClassName = '\Grav\Plugin\Api\\' . ucfirst($resource);
$resource = new $resourceClassName($this->grav);
$output = $resource->execute();
$resource->setHeaders();
echo $output;
} else {
header('HTTP/1.1 404 Not Found');
}
}
exit();
}
private function isAuthorized()
{
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
return false;
}
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
$user = User::load($username);
$isAuthenticated = $user->authenticate($password);
if ($isAuthenticated) {
if ($this->authorize($user, ['admin.api', 'admin.super'])) {
return true;
}
}
return false;
}
/**
* Checks user authorisation to the action.
*
* @param string $action
*
* @return bool
*/
public function authorize($user, $action)
{
$action = (array)$action;
foreach ($action as $a) {
if ($user->authorize($a)) {
return true;
}
}
return false;
}
}