-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.php
150 lines (126 loc) · 4.81 KB
/
index.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<?php
/**
* Plugin Name: WordPress GraphQL
* Plugin URI: http://www.mohiohio.com/
* Description: GraphQL for WordPress
* Version: 0.8.2
* Author: Tim Field
* Author URI: http://www.mohiohio.com/
* License: GPL-3
*/
namespace Mohiohio\GraphQLWP;
use GraphQL\GraphQL;
use Mohiohio\WordPress\Router;
use ReallySimpleJWT\Token;
use WP_Error;
const ENDPOINT = '/graphql/';
if (file_exists(__DIR__ . '/vendor')) {
require __DIR__ . '/vendor/autoload.php';
}
Router::routes([
ENDPOINT => function () {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return '';
}
header('Content-Type: application/json');
$contentTypeIsJson = (isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] == 'application/json')
|| (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == 'application/json');
if ($contentTypeIsJson) {
$rawBody = file_get_contents('php://input');
try {
$data = json_decode($rawBody, true);
} catch (\Exception $exception) {
jsonResponse(['errors' => ['message' => 'Decoding body failed. Be sure to send valid json request.']]);
}
// Decoded response is still empty
if (strlen($rawBody) > 0 && null === $data) {
jsonResponse(['errors' => ['message' => 'Decoding body failed. Be sure to send valid json request. Check for line feeds in json (replace them with "\n" or remove them)']]);
}
} else {
$data = $_POST;
}
$requestString = isset($data['query']) ? $data['query'] : null;
$operationName = isset($data['operation']) ? $data['operation'] : null;
$variableValues = isset($data['variables']) ?
(is_array($data['variables']) ?
$data['variables'] :
json_decode($data['variables'], true)) :
null;
if ($requestString) {
try {
do_action('graphql-wp/before-execute', $requestString);
// Define your schema:
$schema = Schema::build();
$result = GraphQL::executeQuery(
$schema,
$requestString,
/* $rootValue */
null,
/* $contextValue */
null,
$variableValues,
$operationName
)->toArray();
do_action('graphql-wp/after-execute', $result);
} catch (\Exception $exception) {
$result = [
'errors' => [
['message' => $exception->getMessage()]
]
];
}
//log('result', $result);
jsonResponse($result);
}
jsonResponse(['errors' => ['message' => 'Wrong query format or empty query. Either send raw query _with_ Content-Type: \'application/json\' header or send query by posting www-form-data with a query="query{}..." parameter']]);
},
'/graphiql/' => function () {
if (current_user_can('administrator')) {
include __DIR__ . '/graphiql.html';
} else {
header("HTTP/1.1 401 Unauthorized");
}
}
]);
add_filter('authenticate', function ($user) {
$secret = getenv('JWT_SECRET', true);
if (!empty($_SERVER['HTTP_AUTHORIZATION']) && $secret) {
$token = explode(' ', $_SERVER['HTTP_AUTHORIZATION'])[1];
// See https://github.com/RobDWaller/ReallySimpleJWT#error-messages-and-codes
if ($token && Token::validate($token, $secret)) {
$payload = Token::getPayload($token, $secret);
$user = get_user_by('id', $payload['user_id']);
return $user;
}
return new WP_Error('authentication_failed', 'Graphql-WP: Invalid JWT token');
}
return $user;
}, 10, 3);
add_action('after_setup_theme', function () {
$secret = getenv('JWT_SECRET', true);
if (!empty($_SERVER['HTTP_AUTHORIZATION']) && $secret) {
// Don't auth with a cookie if Authorization header is set ?
// unset($_COOKIE[LOGGED_IN_COOKIE]);
$res = wp_signon(['password' => $secret], false);
if ($res && !is_wp_error($res)) {
wp_set_current_user($res->ID);
}
}
});
/**
* Sends a json object to the client
* @param array $resp response object
* @return [type] [description]
*/
function jsonResponse(array $resp)
{
try {
$jsonResponse = json_encode($resp);
} catch (\Exception $exception) {
jsonResponse(['errors' => ['message' => 'Failed to encode to JSON the response.']]);
}
echo $jsonResponse;
exit;
}