-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathclass-client.php
442 lines (386 loc) · 10.6 KB
/
class-client.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
<?php
namespace WP\OAuth2;
use WP\OAuth2\Tokens\Access_Token;
use WP\OAuth2\Tokens\Authorization_Code;
use WP_Error;
use WP_Post;
use WP_Query;
use WP_User;
class Client {
const POST_TYPE = 'oauth2_client';
const CLIENT_SECRET_KEY = '_oauth2_client_secret';
const TYPE_KEY = '_oauth2_client_type';
const REDIRECT_URI_KEY = '_oauth2_redirect_uri';
const AUTH_CODE_KEY_PREFIX = '_oauth2_authcode_';
const FORCE_PKCE = '_oauth2_force-pkce';
const AUTH_CODE_LENGTH = 12;
const CLIENT_ID_LENGTH = 12;
const CLIENT_SECRET_LENGTH = 48;
const AUTH_CODE_AGE = 600; // 10 * MINUTE_IN_SECONDS
/**
* @var WP_Post
*/
protected $post;
/**
* Constructor.
*
* @param WP_Post $post
*/
protected function __construct( WP_Post $post ) {
$this->post = $post;
}
/**
* Get the client's ID.
*
* @return string Client ID.
*/
public function get_id() {
return $this->post->post_name;
}
/**
* Get the client's post ID.
*
* For internal (WordPress) use only. For external use, use get_key()
*
* @return int Client ID.
*/
public function get_post_id() {
return $this->post->ID;
}
/**
* Get the client's name.
*
* @return string HTML string.
*/
public function get_name() {
return get_the_title( $this->get_post_id() );
}
/**
* Get the client's description.
*
* @param boolean $raw True to get raw database value for editing, false to get rendered value for display.
* @return string
*/
public function get_description( $raw = false ) {
// Replicate the_content()'s filters.
global $post;
$current_post = $post;
$the_post = get_post( $this->get_post_id() );
if ( $raw ) {
// Skip the filtering and globals.
return $the_post->post_content;
}
// Set up globals so the filters have context.
$post = $the_post;
setup_postdata( $post );
$content = get_the_content();
/** This filter is documented in wp-includes/post-template.php */
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
// Restore previous post.
$post = $current_post;
if ( $post ) {
setup_postdata( $post );
}
return $content;
}
/**
* Get the client's type.
*
* @return string Type ID if available, or an empty string.
*/
public function get_type() {
return get_post_meta( $this->get_post_id(), static::TYPE_KEY, true );
}
/**
* Get the Client Secret Key.
*
* @return string The Secret Key if available, or an empty string.
*/
public function get_secret() {
return get_post_meta( $this->get_post_id(), static::CLIENT_SECRET_KEY, true );
}
/**
* Get registered URI for the client.
*
* @return array List of valid redirect URIs.
*/
public function get_redirect_uris() {
return (array) get_post_meta( $this->get_post_id(), static::REDIRECT_URI_KEY, true );
}
/**
* Whether the client requires PKCE
*
* @return Boolean
*/
public function should_force_pkce() {
return 'true' === get_post_meta( $this->get_post_id(), static::FORCE_PKCE, true );
}
/**
* Validate a callback URL.
*
* Based on {@see wp_http_validate_url}, but less restrictive around ports
* and hosts. In particular, it allows any scheme, host or port rather than
* just HTTP with standard ports.
*
* @param string $url URL for the callback.
* @return bool True for a valid callback URL, false otherwise.
*/
public static function validate_callback( $url ) {
if ( strpos( $url, ':' ) === false ) {
return false;
}
$parsed_url = wp_parse_url( $url );
if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
return false;
}
if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) {
return false;
}
if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) {
return false;
}
return true;
}
/**
* Check if a redirect URI is valid for the client.
*
* @todo Implement this properly :)
*
* @param string $uri Supplied redirect URI to check.
* @return boolean True if the URI is valid, false otherwise.
*/
public function check_redirect_uri( $uri ) {
if ( ! $this->validate_callback( $uri ) ) {
return false;
}
$supplied = wp_parse_url( $uri );
$all_registered = $this->get_redirect_uris();
foreach ( $all_registered as $registered_uri ) {
$registered = wp_parse_url( $registered_uri );
// Double-check registered URI is valid.
if ( ! $registered ) {
continue;
}
// Check all components except query and fragment
$parts = [ 'scheme', 'host', 'port', 'user', 'pass', 'path' ];
$valid = true;
foreach ( $parts as $part ) {
if ( isset( $registered[ $part ] ) !== isset( $supplied[ $part ] ) ) {
$valid = false;
break;
}
if ( ! isset( $registered[ $part ] ) ) {
continue;
}
if ( $registered[ $part ] !== $supplied[ $part ] ) {
$valid = false;
break;
}
}
/**
* Filter whether a callback is counted as valid.
*
* By default, the URLs must match scheme, host, port, user, pass, and
* path. Query and fragment segments are allowed to be different.
*
* To change this behaviour, filter this value. Note that consumers must
* have a callback registered, even if you relax this restruction. It is
* highly recommended not to change this behaviour, as clients will
* expect the same behaviour across all WP sites.
*
* @param boolean $valid True if the callback URL is valid, false otherwise.
* @param string $url Supplied callback URL.
* @param string $registered_uri URI being checked.
* @param Client $client OAuth 2 client object.
*/
$valid = apply_filters( 'rest_oauth.check_callback', $valid, $uri, $registered_uri, $this );
if ( $valid ) {
// Stop checking, we have a match.
return true;
}
}
return false;
}
/**
* @param WP_User $user
*
* @return Authorization_Code|WP_Error
*/
public function generate_authorization_code( WP_User $user, $data ) {
return Authorization_Code::create( $this, $user, $data );
}
/**
* Get data stored for an authorization code.
*
* @param string $code Authorization code to fetch.
* @return Authorization_Code|WP_Error Data if available, error if invalid code.
*/
public function get_authorization_code( $code ) {
return Authorization_Code::get_by_code( $this, $code );
}
/**
* @return bool|WP_Error
*/
public function regenerate_secret() {
$result = update_post_meta( $this->get_post_id(), static::CLIENT_SECRET_KEY, wp_generate_password( static::CLIENT_SECRET_LENGTH, false ) );
if ( ! $result ) {
return new WP_Error( 'oauth2.client.create.failed_meta', __( 'Could not regenerate the client secret.', 'oauth2' ) );
}
return true;
}
/**
* Issue token for a user.
*
* @param \WP_User $user
*
* @return Access_Token
*/
public function issue_token( WP_User $user ) {
return Tokens\Access_Token::create( $this, $user );
}
/**
* Get a client by ID.
*
* @param string $id Client ID.
* @return static|null Token if ID is found, null otherwise.
*/
public static function get_by_id( $id ) {
$args = [
'post_type' => static::POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 1,
'no_found_rows' => true,
// Query by slug.
'name' => $id,
];
$query = new WP_Query( $args );
if ( empty( $query->posts ) ) {
return null;
}
return new static( $query->posts[0] );
}
/**
* Get a client by post ID.
*
* @param int $id Client/post ID.
* @return static|null Client instance on success, null if invalid/not found.
*/
public static function get_by_post_id( $id ) {
$post = get_post( $id );
if ( ! $post ) {
return null;
}
return new static( $post );
}
/**
* Create a new client.
*
* @param array $data {
* }
* @return WP_Error|Client Client instance on success, error otherwise.
*/
public static function create( $data ) {
$client_id = wp_generate_password( static::CLIENT_ID_LENGTH, false );
$post_data = [
'post_type' => static::POST_TYPE,
'post_title' => $data['name'],
'post_content' => $data['description'],
'post_name' => $client_id,
'post_status' => 'draft',
];
$post_id = wp_insert_post( wp_slash( $post_data ), true );
if ( is_wp_error( $post_id ) ) {
return $post_id;
}
// Generate ID and secret.
$meta = [
static::REDIRECT_URI_KEY => $data['meta']['callback'],
static::TYPE_KEY => $data['meta']['type'],
static::CLIENT_SECRET_KEY => wp_generate_password( static::CLIENT_SECRET_LENGTH, false ),
static::FORCE_PKCE => $data['meta']['force-pkce'],
];
foreach ( $meta as $key => $value ) {
$result = update_post_meta( $post_id, wp_slash( $key ), wp_slash( $value ) );
if ( ! $result ) {
// Failed, rollback.
return new WP_Error( 'oauth2.client.create.failed_meta', __( 'Could not save meta value.', 'oauth2' ) );
}
}
$post = get_post( $post_id );
return new static( $post );
}
/**
* @param array $data
*
* @return WP_Error|Client Client instance on success, error otherwise.
*/
public function update( $data ) {
$post_data = [
'ID' => $this->get_post_id(),
'post_type' => static::POST_TYPE,
'post_title' => $data['name'],
'post_content' => $data['description'],
];
$post_id = wp_update_post( wp_slash( $post_data ), true );
if ( is_wp_error( $post_id ) ) {
return $post_id;
}
$meta = [
static::REDIRECT_URI_KEY => $data['meta']['callback'],
static::TYPE_KEY => $data['meta']['type'],
static::FORCE_PKCE => $data['meta']['force-pkce'],
];
foreach ( $meta as $key => $value ) {
update_post_meta( $post_id, wp_slash( $key ), wp_slash( $value ) );
}
$post = get_post( $post_id );
return new static( $post );
}
/**
* Delete the client.
*
* @return bool
*/
public function delete() {
return (bool) wp_delete_post( $this->get_post_id(), true );
}
/**
* Approve a client.
*
* @return bool|WP_Error True if client was updated, error otherwise.
*/
public function approve() {
$data = [
'ID' => $this->get_post_id(),
'post_status' => 'publish',
];
$result = wp_update_post( wp_slash( $data ), true );
return is_wp_error( $result ) ? $result : true;
}
/**
* Register the underlying post type.
*/
public static function register_type() {
register_post_type( static::POST_TYPE, [
'public' => false,
'hierarchical' => true,
'capability_type' => [
'oauth2_client',
'oauth2_clients',
],
'capabilities' => [
'edit_posts' => 'edit_users',
'edit_others_posts' => 'edit_users',
'publish_posts' => 'edit_users',
],
'supports' => [
'title',
'editor',
'revisions',
'author',
'thumbnail',
],
] );
}
}