Skip to content

Commit 30ff08c

Browse files
authored
Merge pull request #39 from WP-API/add-convenience-redirect
Add convenience redirect for the authorize page
2 parents 92e71a1 + 25aba38 commit 30ff08c

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

inc/endpoints/namespace.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
namespace WP\OAuth2\Endpoints;
4+
5+
use WP\OAuth2;
6+
use WP_REST_Request;
7+
use WP_REST_Response;
8+
9+
/**
10+
* Register OAuth-specific endpoints.
11+
*/
12+
function register() {
13+
$token_endpoint = new Token();
14+
$token_endpoint->register_routes();
15+
16+
// Register convenience URL.
17+
register_rest_route( 'oauth2', '/authorize', [
18+
'methods' => 'GET',
19+
'callback' => __NAMESPACE__ . '\\redirect_to_authorize',
20+
]);
21+
}
22+
23+
/**
24+
* Handle authorize endpoint request.
25+
*
26+
* This endpoint exists as a convenience URL to avoid clients needing to find
27+
* wp-login.php.
28+
*
29+
* @param WP_REST_Request $request Request object.
30+
* @return WP_REST_Response Response object.
31+
*/
32+
function redirect_to_authorize( WP_REST_Request $request ) {
33+
$url = OAuth2\get_authorization_url();
34+
35+
$query = $request->get_query_params();
36+
if ( ! empty( $query ) ) {
37+
// Pass query arguments along.
38+
$url = add_query_arg(
39+
urlencode_deep( $query ),
40+
$url
41+
);
42+
}
43+
44+
return new WP_REST_Response( [ 'url' => $url ], 302, [ 'Location' => $url ] );
45+
}

plugin.php

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ function bootstrap() {
2525
// REST API integration.
2626
add_filter( 'rest_authentication_errors', __NAMESPACE__ . '\\Authentication\\maybe_report_errors' );
2727
add_filter( 'rest_index', __NAMESPACE__ . '\\register_in_index' );
28-
add_action( 'rest_api_init', __NAMESPACE__ . '\\register_routes' );
28+
add_action( 'rest_api_init', __NAMESPACE__ . '\\Endpoints\\register' );
2929

3030
// Internal default hooks.
3131
add_filter( 'oauth2.grant_types', __NAMESPACE__ . '\\register_grant_types', 0 );
@@ -40,6 +40,7 @@ function load() {
4040
require __DIR__ . '/inc/class-client.php';
4141
require __DIR__ . '/inc/class-scopes.php';
4242
require __DIR__ . '/inc/authentication/namespace.php';
43+
require __DIR__ . '/inc/endpoints/namespace.php';
4344
require __DIR__ . '/inc/endpoints/class-authorization.php';
4445
require __DIR__ . '/inc/endpoints/class-token.php';
4546
require __DIR__ . '/inc/tokens/namespace.php';
@@ -129,11 +130,6 @@ function register_in_index( WP_REST_Response $response ) {
129130
return $response;
130131
}
131132

132-
function register_routes() {
133-
$token_endpoint = new Endpoints\Token();
134-
$token_endpoint->register_routes();
135-
}
136-
137133
/**
138134
* Get the authorization endpoint URL.
139135
*

0 commit comments

Comments
 (0)