| 1 |
<?php |
| 2 |
/** |
| 3 |
* Redirect related callbacks. |
| 4 |
* |
| 5 |
* @package FaustWP |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WPE\FaustWP\Auth; |
| 9 |
|
| 10 |
use function WPE\FaustWP\Settings\faustwp_get_setting; |
| 11 |
|
| 12 |
if ( ! defined( 'ABSPATH' ) ) { |
| 13 |
exit; |
| 14 |
} |
| 15 |
|
| 16 |
add_action( 'parse_request', __NAMESPACE__ . '\\handle_generate_endpoint' ); |
| 17 |
/** |
| 18 |
* Callback for WordPress 'parse_request' action. |
| 19 |
* |
| 20 |
* Generate an authorization code and redirect to the requested url. |
| 21 |
* |
| 22 |
* @return void |
| 23 |
*/ |
| 24 |
function handle_generate_endpoint() { |
| 25 |
if ( ! preg_match( '/^\/generate/', $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
if ( empty( $_GET['redirect_uri'] ) ) { // phpcs:ignore WordPress.Security |
| 30 |
return; |
| 31 |
} |
| 32 |
|
| 33 |
$redirect_uri = wp_unslash( $_GET['redirect_uri'] ); // phpcs:ignore WordPress.Security |
| 34 |
|
| 35 |
if ( ! is_user_logged_in() ) { |
| 36 |
wp_safe_redirect( |
| 37 |
wp_login_url( '/generate/?redirect_uri=' . rawurlencode( $redirect_uri ) ) |
| 38 |
); |
| 39 |
|
| 40 |
exit; |
| 41 |
} |
| 42 |
|
| 43 |
$auth_code = generate_authorization_code( |
| 44 |
wp_get_current_user(), |
| 45 |
MINUTE_IN_SECONDS * 1 |
| 46 |
); |
| 47 |
|
| 48 |
$redirect_uri = add_query_arg( 'code', rawurlencode( $auth_code ), $redirect_uri ); |
| 49 |
|
| 50 |
wp_safe_redirect( $redirect_uri ); |
| 51 |
|
| 52 |
exit; |
| 53 |
} |
| 54 |
|
| 55 |
add_filter( 'allowed_redirect_hosts', __NAMESPACE__ . '\\allowed_redirect_hosts', 10, 2 ); |
| 56 |
/** |
| 57 |
* Callback for WordPress 'allowed_redirect_hosts' filter. |
| 58 |
* |
| 59 |
* Add frontend_uri host and development domains to allowed redirects. |
| 60 |
* |
| 61 |
* @link https://developer.wordpress.org/reference/hooks/allowed_redirect_hosts/ |
| 62 |
* |
| 63 |
* @param string[] $hosts An array of allowed host names. |
| 64 |
* @param string $host The host name of the redirect destination; empty string if not set. |
| 65 |
* |
| 66 |
* @return string[] An array of allowed host names. |
| 67 |
*/ |
| 68 |
function allowed_redirect_hosts( $hosts, $host ) { |
| 69 |
$hosts = wp_parse_args( $hosts, array( 'localhost', '0.0.0.0' ) ); |
| 70 |
$frontend_host = wp_parse_url( faustwp_get_setting( 'frontend_uri' ), PHP_URL_HOST ); |
| 71 |
|
| 72 |
if ( $frontend_host ) { |
| 73 |
$hosts[] = $frontend_host; |
| 74 |
} |
| 75 |
|
| 76 |
return $hosts; |
| 77 |
} |
| 78 |
|