From 0e73efe983c7e654ae19a90bad8c8be98f13c59b Mon Sep 17 00:00:00 2001 From: Evan Sims Date: Mon, 8 Jul 2024 17:56:26 -0500 Subject: [PATCH] release: 4.6.1 --- .gitignore | 2 + WP_Auth0.php | 604 ++++++++++-------- composer.json | 10 +- examples/auth0_before_login.php | 11 +- examples/auth0_die_on_login_output.php | 16 +- examples/auth0_settings_fields.php | 21 +- examples/auth0_user_login.php | 20 +- examples/wpa0_user_created.php | 17 +- lib/WP_Auth0_Api_Client.php | 185 +++--- lib/WP_Auth0_Api_Operations.php | 45 +- lib/WP_Auth0_DBManager.php | 189 +++--- lib/WP_Auth0_Email_Verification.php | 36 +- lib/WP_Auth0_Embed_Widget.php | 68 +- lib/WP_Auth0_ErrorLog.php | 82 +-- lib/WP_Auth0_Import_Settings.php | 51 +- lib/WP_Auth0_Ip_Check.php | 77 ++- lib/WP_Auth0_Lock.php | 153 ++--- lib/WP_Auth0_LoginManager.php | 413 ++++++------ lib/WP_Auth0_Nonce_Handler.php | 82 ++- lib/WP_Auth0_Options.php | 200 +++--- lib/WP_Auth0_Popup_Widget.php | 20 +- lib/WP_Auth0_Routes.php | 183 +++--- lib/WP_Auth0_Serializer.php | 20 +- lib/WP_Auth0_State_Handler.php | 9 +- lib/WP_Auth0_Users.php | 61 +- lib/WP_Auth0_UsersRepo.php | 115 ++-- lib/WP_Auth0_WooCommerceOverrides.php | 38 +- lib/admin/WP_Auth0_Admin.php | 100 +-- lib/admin/WP_Auth0_Admin_Advanced.php | 277 ++++---- lib/admin/WP_Auth0_Admin_Appearance.php | 190 +++--- lib/admin/WP_Auth0_Admin_Basic.php | 210 +++--- lib/admin/WP_Auth0_Admin_Features.php | 89 +-- lib/admin/WP_Auth0_Admin_Generic.php | 214 ++++--- lib/api/WP_Auth0_Api_Abstract.php | 145 +++-- lib/api/WP_Auth0_Api_Change_Email.php | 30 +- lib/api/WP_Auth0_Api_Change_Password.php | 32 +- lib/api/WP_Auth0_Api_Client_Credentials.php | 58 +- lib/api/WP_Auth0_Api_Exchange_Code.php | 42 +- lib/api/WP_Auth0_Api_Get_Jwks.php | 20 +- lib/api/WP_Auth0_Api_Get_User.php | 24 +- lib/api/WP_Auth0_Api_Jobs_Verification.php | 26 +- lib/api/WP_Auth0_Api_Refresh_Access_Token.php | 42 +- .../WP_Auth0_BeforeLoginException.php | 4 +- .../WP_Auth0_CouldNotCreateUserException.php | 4 +- .../WP_Auth0_EmailNotVerifiedException.php | 6 +- .../WP_Auth0_InvalidIdTokenException.php | 4 +- .../WP_Auth0_LoginFlowValidationException.php | 4 +- ..._Auth0_RegistrationNotEnabledException.php | 4 +- lib/profile/WP_Auth0_Profile_Change_Email.php | 55 +- .../WP_Auth0_Profile_Change_Password.php | 46 +- lib/profile/WP_Auth0_Profile_Delete_Data.php | 43 +- lib/scripts-js/db-get-user.js | 23 +- lib/scripts-js/db-login.js | 27 +- .../WP_Auth0_AsymmetricVerifier.php | 24 +- .../WP_Auth0_IdTokenVerifier.php | 111 ++-- lib/token-verifier/WP_Auth0_JwksFetcher.php | 48 +- .../WP_Auth0_SignatureVerifier.php | 30 +- .../WP_Auth0_SymmetricVerifier.php | 17 +- templates/a0-error-log.php | 56 +- templates/a0-widget-setup-form.php | 120 ++-- templates/auth0-login-form.php | 30 +- templates/import_settings.php | 68 +- templates/login-interim.php | 16 +- templates/settings.php | 85 +-- tests/Unit/EmailVerificationTest.php | 93 +-- tests/Unit/LoginManagerRedirectLoginTest.php | 262 ++++---- tests/classes/Test_WP_Auth0_Api_Abstract.php | 32 +- tests/traits/ajaxHelpers.php | 54 +- tests/traits/httpHelpers.php | 77 ++- tests/traits/redirectHelpers.php | 19 +- tests/traits/wpDieHelper.php | 24 +- 71 files changed, 3049 insertions(+), 2564 deletions(-) diff --git a/.gitignore b/.gitignore index 081805943..9d6c9b8b1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ wp-phptidy.php /account_cleanup/vendor/ /vendor/ /rules/ +/build/ /tests-wordpress /tests-wordpress-config .phpcs.xml @@ -17,3 +18,4 @@ composer.local.json composer.local.json_ .phpunit.result.cache .vscode +private-signing-key.pem diff --git a/WP_Auth0.php b/WP_Auth0.php index c825a2aeb..f330785a3 100644 --- a/WP_Auth0.php +++ b/WP_Auth0.php @@ -1,4 +1,5 @@ install_db(); } -add_action( 'plugins_loaded', 'wp_auth0_plugins_loaded' ); +add_action('plugins_loaded', 'wp_auth0_plugins_loaded'); -function wp_auth0_init() { - $router = new WP_Auth0_Routes( WP_Auth0_Options::Instance() ); +function wp_auth0_init() +{ + $router = new WP_Auth0_Routes(WP_Auth0_Options::Instance()); $router->setup_rewrites(); } -add_action( 'init', 'wp_auth0_init' ); +add_action('init', 'wp_auth0_init'); -function wp_auth0_shortcode( $atts ) { - if ( empty( $atts ) ) { +function wp_auth0_shortcode($atts) +{ + if (empty($atts)) { $atts = []; } - if ( empty( $atts['redirect_to'] ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { - $atts['redirect_to'] = home_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ); + if (empty($atts['redirect_to']) && !empty($_SERVER['REQUEST_URI'])) { + $atts['redirect_to'] = home_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))); } ob_start(); - \WP_Auth0_Lock::render( false, $atts ); + \WP_Auth0_Lock::render(false, $atts); return ob_get_clean(); } -add_shortcode( 'auth0', 'wp_auth0_shortcode' ); +add_shortcode('auth0', 'wp_auth0_shortcode'); /* * Plugin install/uninstall/update actions */ -function wp_auth0_activation_hook() { +function wp_auth0_activation_hook() +{ $options = WP_Auth0_Options::Instance(); - $db_manager = new WP_Auth0_DBManager( $options ); - $router = new WP_Auth0_Routes( $options ); + $db_manager = new WP_Auth0_DBManager($options); + $router = new WP_Auth0_Routes($options); $db_manager->install_db(); $router->setup_rewrites(); @@ -90,86 +96,94 @@ function wp_auth0_activation_hook() { flush_rewrite_rules(); } -register_activation_hook( WPA0_PLUGIN_FILE, 'wp_auth0_activation_hook' ); +register_activation_hook(WPA0_PLUGIN_FILE, 'wp_auth0_activation_hook'); -function wp_auth0_deactivation_hook() { +function wp_auth0_deactivation_hook() +{ flush_rewrite_rules(); } -register_deactivation_hook( WPA0_PLUGIN_FILE, 'wp_auth0_deactivation_hook' ); +register_deactivation_hook(WPA0_PLUGIN_FILE, 'wp_auth0_deactivation_hook'); -function wp_auth0_uninstall_hook() { +function wp_auth0_uninstall_hook() +{ $a0_options = WP_Auth0_Options::Instance(); $a0_options->delete(); $error_log = new WP_Auth0_ErrorLog(); $error_log->delete(); - delete_option( 'auth0_db_version' ); + delete_option('auth0_db_version'); - delete_option( 'widget_wp_auth0_popup_widget' ); - delete_option( 'widget_wp_auth0_widget' ); - delete_option( 'widget_wp_auth0_social_amplification_widget' ); + delete_option('widget_wp_auth0_popup_widget'); + delete_option('widget_wp_auth0_widget'); + delete_option('widget_wp_auth0_social_amplification_widget'); - delete_transient( WPA0_JWKS_CACHE_TRANSIENT_NAME ); + delete_transient(WPA0_JWKS_CACHE_TRANSIENT_NAME); } -register_uninstall_hook( WPA0_PLUGIN_FILE, 'wp_auth0_uninstall_hook' ); +register_uninstall_hook(WPA0_PLUGIN_FILE, 'wp_auth0_uninstall_hook'); -function wp_auth0_activated_plugin_redirect( $plugin ) { +function wp_auth0_activated_plugin_redirect($plugin) +{ - if ( defined( 'WP_CLI' ) || $plugin !== WPA0_PLUGIN_BASENAME ) { + if (defined('WP_CLI') || $plugin !== WPA0_PLUGIN_BASENAME) { return; } $redirect_query = wp_auth0_is_ready() ? 'page=wpa0' : 'page=wpa0-setup&activation=1'; - wp_safe_redirect( admin_url( 'admin.php?' . $redirect_query ) ); + wp_safe_redirect(admin_url('admin.php?' . $redirect_query)); exit; } -add_action( 'activated_plugin', 'wp_auth0_activated_plugin_redirect' ); +add_action('activated_plugin', 'wp_auth0_activated_plugin_redirect'); /* * Core WP hooks */ -function wp_auth0_add_allowed_redirect_hosts( $hosts ) { +function wp_auth0_add_allowed_redirect_hosts($hosts) +{ $hosts[] = 'auth0.auth0.com'; - $hosts[] = wp_auth0_get_option( 'domain' ); - $hosts[] = wp_auth0_get_option( 'custom_domain' ); - $hosts[] = wp_auth0_get_option( 'auth0_server_domain' ); + $hosts[] = wp_auth0_get_option('domain'); + $hosts[] = wp_auth0_get_option('custom_domain'); + $hosts[] = wp_auth0_get_option('auth0_server_domain'); return $hosts; } -add_filter( 'allowed_redirect_hosts', 'wp_auth0_add_allowed_redirect_hosts' ); +add_filter('allowed_redirect_hosts', 'wp_auth0_add_allowed_redirect_hosts'); /** * Enqueue login page CSS if plugin is configured. */ -function wp_auth0_login_enqueue_scripts() { - if ( wp_auth0_is_ready() ) { - wp_enqueue_style( 'auth0', WPA0_PLUGIN_CSS_URL . 'login.css', false, WPA0_VERSION ); +function wp_auth0_login_enqueue_scripts() +{ + if (wp_auth0_is_ready()) { + wp_enqueue_style('auth0', WPA0_PLUGIN_CSS_URL . 'login.css', false, WPA0_VERSION); } } -add_action( 'login_enqueue_scripts', 'wp_auth0_login_enqueue_scripts' ); +add_action('login_enqueue_scripts', 'wp_auth0_login_enqueue_scripts'); /** * Enqueue login widget CSS if plugin is configured. */ -function wp_auth0_enqueue_scripts() { - if ( wp_auth0_is_ready() ) { - wp_enqueue_style( 'auth0-widget', WPA0_PLUGIN_CSS_URL . 'main.css' ); +function wp_auth0_enqueue_scripts() +{ + if (wp_auth0_is_ready()) { + wp_enqueue_style('auth0-widget', WPA0_PLUGIN_CSS_URL . 'main.css', false, WPA0_VERSION); } } -add_action( 'wp_enqueue_scripts', 'wp_auth0_enqueue_scripts' ); +add_action('wp_enqueue_scripts', 'wp_auth0_enqueue_scripts'); -function wp_auth0_register_widget() { - register_widget( 'WP_Auth0_Embed_Widget' ); - register_widget( 'WP_Auth0_Popup_Widget' ); +function wp_auth0_register_widget() +{ + register_widget('WP_Auth0_Embed_Widget'); + register_widget('WP_Auth0_Popup_Widget'); } -add_action( 'widgets_init', 'wp_auth0_register_widget' ); +add_action('widgets_init', 'wp_auth0_register_widget'); -function wp_auth0_register_query_vars( $qvars ) { - return array_merge( $qvars, [ 'error', 'error_description', 'a0_action', 'auth0', 'state', 'code', 'invitation', 'organization', 'organization_name' ] ); +function wp_auth0_register_query_vars($qvars) +{ + return array_merge($qvars, ['error', 'error_description', 'a0_action', 'auth0', 'state', 'code', 'invitation', 'organization', 'organization_name']); } -add_filter( 'query_vars', 'wp_auth0_register_query_vars' ); +add_filter('query_vars', 'wp_auth0_register_query_vars'); /** * Output the Auth0 form on wp-login.php @@ -180,31 +194,33 @@ function wp_auth0_register_query_vars( $qvars ) { * * @return string */ -function wp_auth0_render_lock_form( $html ) { +function wp_auth0_render_lock_form($html) +{ ob_start(); \WP_Auth0_Lock::render(); $auth0_form = ob_get_clean(); return $auth0_form ? $auth0_form : $html; } -add_filter( 'login_message', 'wp_auth0_render_lock_form', 5 ); +add_filter('login_message', 'wp_auth0_render_lock_form', 5); /** * Add settings link on plugin page. */ -function wp_auth0_plugin_action_links( $links ) { +function wp_auth0_plugin_action_links($links) +{ array_unshift( $links, - sprintf( + wp_kses(sprintf( '%s', - admin_url( 'admin.php?page=wpa0' ), - __( 'Settings', 'wp-auth0' ) - ) + admin_url('admin.php?page=wpa0'), + esc_html__('Settings', 'wp-auth0') + ), ['a' => ['href' => true]]) ); return $links; } -add_filter( 'plugin_action_links_' . WPA0_PLUGIN_BASENAME, 'wp_auth0_plugin_action_links' ); +add_filter('plugin_action_links_' . WPA0_PLUGIN_BASENAME, 'wp_auth0_plugin_action_links'); /** * Filter the avatar to use the Auth0 profile image @@ -217,180 +233,190 @@ function wp_auth0_plugin_action_links( $links ) { * * @return string */ -function wp_auth0_filter_get_avatar( $avatar, $id_or_email, $size, $default, $alt ) { - if ( ! wp_auth0_get_option( 'override_wp_avatars' ) ) { +function wp_auth0_filter_get_avatar($avatar, $id_or_email, $size, $default, $alt) +{ + if (!wp_auth0_get_option('override_wp_avatars')) { return $avatar; } $user_id = null; - if ( $id_or_email instanceof WP_User ) { + if ($id_or_email instanceof WP_User) { $user_id = $id_or_email->ID; - } elseif ( $id_or_email instanceof WP_Comment ) { + } elseif ($id_or_email instanceof WP_Comment) { $user_id = $id_or_email->user_id; - } elseif ( $id_or_email instanceof WP_Post ) { + } elseif ($id_or_email instanceof WP_Post) { $user_id = $id_or_email->post_author; - } elseif ( is_email( $id_or_email ) ) { - $maybe_user = get_user_by( 'email', $id_or_email ); + } elseif (is_email($id_or_email)) { + $maybe_user = get_user_by('email', $id_or_email); - if ( $maybe_user instanceof WP_User ) { + if ($maybe_user instanceof WP_User) { $user_id = $maybe_user->ID; } - } elseif ( is_numeric( $id_or_email ) ) { - $user_id = absint( $id_or_email ); + } elseif (is_numeric($id_or_email)) { + $user_id = absint($id_or_email); } - if ( ! $user_id ) { + if (!$user_id) { return $avatar; } - $auth0Profile = get_auth0userinfo( $user_id ); + $auth0Profile = get_auth0userinfo($user_id); - if ( ! $auth0Profile || empty( $auth0Profile->picture ) ) { + if (!$auth0Profile || empty($auth0Profile->picture)) { return $avatar; } - return sprintf( + return wp_kses(sprintf( '%s', - esc_attr( $alt ), - esc_url( $auth0Profile->picture ), - absint( $size ), - absint( $size ), - absint( $size ) - ); + esc_attr($alt), + esc_url($auth0Profile->picture), + absint($size), + absint($size), + absint($size) + ), ['img' => ['alt' => true, 'src' => true, 'class' => true, 'width' => true, 'height' => true]]); } -add_filter( 'get_avatar', 'wp_auth0_filter_get_avatar', 1, 5 ); +add_filter('get_avatar', 'wp_auth0_filter_get_avatar', 1, 5); /** * Function to call the method that clears out the error log. * * @hook admin_action_wpauth0_clear_error_log */ -function wp_auth0_errorlog_clear_error_log() { +function wp_auth0_errorlog_clear_error_log() +{ // Null coalescing validates input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - if ( ! wp_verify_nonce( wp_unslash( $_POST['_wpnonce'] ?? '' ), WP_Auth0_ErrorLog::CLEAR_LOG_NONCE ) ) { - wp_die( __( 'Not allowed.', 'wp-auth0' ) ); + if (!wp_verify_nonce(wp_unslash($_POST['_wpnonce'] ?? ''), WP_Auth0_ErrorLog::CLEAR_LOG_NONCE)) { + wp_die(esc_html__('Not allowed.', 'wp-auth0')); } - if ( ! current_user_can( 'manage_options' ) ) { - wp_die( __( 'Not authorized.', 'wp-auth0' ) ); + if (!current_user_can('manage_options')) { + wp_die(esc_html__('Not authorized.', 'wp-auth0')); } $error_log = new WP_Auth0_ErrorLog(); $error_log->clear(); - wp_safe_redirect( admin_url( 'admin.php?page=wpa0-errors&cleared=1' ) ); + wp_safe_redirect(admin_url('admin.php?page=wpa0-errors&cleared=1')); exit; } -add_action( 'admin_action_wpauth0_clear_error_log', 'wp_auth0_errorlog_clear_error_log' ); +add_action('admin_action_wpauth0_clear_error_log', 'wp_auth0_errorlog_clear_error_log'); -function wp_auth0_export_settings_admin_action() { +function wp_auth0_export_settings_admin_action() +{ // Null coalescing validates input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - if ( ! wp_verify_nonce( wp_unslash( $_POST['_wpnonce'] ?? '' ), WP_Auth0_Import_Settings::EXPORT_NONCE_ACTION ) ) { - wp_nonce_ays( WP_Auth0_Import_Settings::IMPORT_NONCE_ACTION ); + if (!wp_verify_nonce(wp_unslash($_POST['_wpnonce'] ?? ''), WP_Auth0_Import_Settings::EXPORT_NONCE_ACTION)) { + wp_nonce_ays(WP_Auth0_Import_Settings::IMPORT_NONCE_ACTION); exit; } - if ( ! current_user_can( 'manage_options' ) ) { - wp_die( __( 'Unauthorized.', 'wp-auth0' ) ); + if (!current_user_can('manage_options')) { + wp_die(esc_html__('Unauthorized.', 'wp-auth0')); exit; } $options = WP_Auth0_Options::Instance(); - $name = urlencode( get_auth0_curatedBlogName() ); - $settings = get_option( $options->get_options_name() ); + $name = urlencode(get_auth0_curatedBlogName()); + $settings = get_option($options->get_options_name()); - header( 'Content-Type: application/json' ); - header( "Content-Disposition: attachment; filename=auth0_for_wordpress_settings-$name.json" ); - header( 'Pragma: no-cache' ); + header('Content-Type: application/json'); + header("Content-Disposition: attachment; filename=auth0_for_wordpress_settings-$name.json"); + header('Pragma: no-cache'); - echo wp_json_encode( $settings ); + echo wp_json_encode($settings); exit; } -add_action( 'admin_action_wpauth0_export_settings', 'wp_auth0_export_settings_admin_action' ); +add_action('admin_action_wpauth0_export_settings', 'wp_auth0_export_settings_admin_action'); -function wp_auth0_import_settings_admin_action() { +function wp_auth0_import_settings_admin_action() +{ $options = WP_Auth0_Options::Instance(); - $import_settings = new WP_Auth0_Import_Settings( $options ); + $import_settings = new WP_Auth0_Import_Settings($options); $import_settings->import_settings(); } -add_action( 'admin_action_wpauth0_import_settings', 'wp_auth0_import_settings_admin_action' ); +add_action('admin_action_wpauth0_import_settings', 'wp_auth0_import_settings_admin_action'); -function wp_auth0_settings_admin_action_error() { +function wp_auth0_settings_admin_action_error() +{ // Not processing form data, using an error URL parameter to indicate a problem with the import. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification - if ( ! wp_auth0_is_admin_page( 'wpa0-import-settings' ) || empty( $_REQUEST['error'] ) ) { + if (!wp_auth0_is_admin_page('wpa0-import-settings') || empty($_REQUEST['error'])) { return false; } - printf( + echo wp_kses(sprintf( '

%s

', - sanitize_text_field( wp_unslash( $_REQUEST['error'] ) ) - ); + sanitize_text_field(wp_unslash($_REQUEST['error'])) + ), ['div' => ['class' => true], 'p' => [], 'strong' => []]); return true; // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification } -add_action( 'admin_notices', 'wp_auth0_settings_admin_action_error' ); +add_action('admin_notices', 'wp_auth0_settings_admin_action_error'); -function wp_auth0_profile_change_email( $wp_user_id, $old_user_data ) { +function wp_auth0_profile_change_email($wp_user_id, $old_user_data) +{ $options = WP_Auth0_Options::Instance(); - $api_client_creds = new WP_Auth0_Api_Client_Credentials( $options ); - $api_change_email = new WP_Auth0_Api_Change_Email( $options, $api_client_creds ); - $profile_change_email = new WP_Auth0_Profile_Change_Email( $api_change_email ); - return $profile_change_email->update_email( $wp_user_id, $old_user_data ); + $api_client_creds = new WP_Auth0_Api_Client_Credentials($options); + $api_change_email = new WP_Auth0_Api_Change_Email($options, $api_client_creds); + $profile_change_email = new WP_Auth0_Profile_Change_Email($api_change_email); + return $profile_change_email->update_email($wp_user_id, $old_user_data); } -add_action( 'profile_update', 'wp_auth0_profile_change_email', 100, 2 ); +add_action('profile_update', 'wp_auth0_profile_change_email', 100, 2); -function wp_auth0_validate_new_password( $errors, $user ) { +function wp_auth0_validate_new_password($errors, $user) +{ $options = WP_Auth0_Options::Instance(); - $api_client_creds = new WP_Auth0_Api_Client_Credentials( $options ); - $api_change_password = new WP_Auth0_Api_Change_Password( $options, $api_client_creds ); - $profile_change_pwd = new WP_Auth0_Profile_Change_Password( $api_change_password ); - return $profile_change_pwd->validate_new_password( $errors, $user ); + $api_client_creds = new WP_Auth0_Api_Client_Credentials($options); + $api_change_password = new WP_Auth0_Api_Change_Password($options, $api_client_creds); + $profile_change_pwd = new WP_Auth0_Profile_Change_Password($api_change_password); + return $profile_change_pwd->validate_new_password($errors, $user); } // Used during profile update in wp-admin. -add_action( 'user_profile_update_errors', 'wp_auth0_validate_new_password', 10, 2 ); +add_action('user_profile_update_errors', 'wp_auth0_validate_new_password', 10, 2); // Used during password reset on wp-login.php. -add_action( 'validate_password_reset', 'wp_auth0_validate_new_password', 10, 2 ); +add_action('validate_password_reset', 'wp_auth0_validate_new_password', 10, 2); // Used during WooCommerce edit account save. -add_action( 'woocommerce_save_account_details_errors', 'wp_auth0_validate_new_password', 10, 2 ); +add_action('woocommerce_save_account_details_errors', 'wp_auth0_validate_new_password', 10, 2); -function wp_auth0_show_delete_identity() { +function wp_auth0_show_delete_identity() +{ $profile_delete_data = new WP_Auth0_Profile_Delete_Data(); $profile_delete_data->show_delete_identity(); } -add_action( 'edit_user_profile', 'wp_auth0_show_delete_identity' ); -add_action( 'show_user_profile', 'wp_auth0_show_delete_identity' ); +add_action('edit_user_profile', 'wp_auth0_show_delete_identity'); +add_action('show_user_profile', 'wp_auth0_show_delete_identity'); -function wp_auth0_delete_user_data() { +function wp_auth0_delete_user_data() +{ $profile_delete_data = new WP_Auth0_Profile_Delete_Data(); $profile_delete_data->delete_user_data(); } -add_action( 'wp_ajax_auth0_delete_data', 'wp_auth0_delete_user_data' ); +add_action('wp_ajax_auth0_delete_data', 'wp_auth0_delete_user_data'); -function wp_auth0_init_admin_menu() { +function wp_auth0_init_admin_menu() +{ - if ( wp_auth0_is_admin_page( 'wpa0-help' ) ) { - wp_safe_redirect( admin_url( 'admin.php?page=wpa0#help' ), 301 ); + if (wp_auth0_is_admin_page('wpa0-help')) { + wp_safe_redirect(admin_url('admin.php?page=wpa0#help'), 301); exit; } $options = WP_Auth0_Options::Instance(); - $routes = new WP_Auth0_Routes( $options ); - $admin = new WP_Auth0_Admin( $options, $routes ); + $routes = new WP_Auth0_Routes($options); + $admin = new WP_Auth0_Admin($options, $routes); $settings_slug = 'wpa0'; - $settings_title = __( 'Settings', 'wp-auth0' ); - $settings_func = [ $admin, 'render_settings_page' ]; + $settings_title = esc_html__('Settings', 'wp-auth0'); + $settings_func = [$admin, 'render_settings_page']; $menu_parent = $settings_slug; $cap = 'manage_options'; @@ -405,14 +431,14 @@ function wp_auth0_init_admin_menu() { 86 ); - if ( ! wp_auth0_is_ready() ) { - add_submenu_page( $menu_parent, $settings_title, $settings_title, $cap, $settings_slug, $settings_func ); + if (!wp_auth0_is_ready()) { + add_submenu_page($menu_parent, $settings_title, $settings_title, $cap, $settings_slug, $settings_func); } else { - add_submenu_page( $menu_parent, $settings_title, $settings_title, $cap, $settings_slug, $settings_func ); + add_submenu_page($menu_parent, $settings_title, $settings_title, $cap, $settings_slug, $settings_func); add_submenu_page( $menu_parent, - __( 'Help', 'wp-auth0' ), - __( 'Help', 'wp-auth0' ), + esc_html__('Help', 'wp-auth0'), + esc_html__('Help', 'wp-auth0'), $cap, 'wpa0-help', '__return_false' @@ -421,152 +447,187 @@ function wp_auth0_init_admin_menu() { add_submenu_page( $menu_parent, - __( 'Error Log', 'wp-auth0' ), - __( 'Error Log', 'wp-auth0' ), + esc_html__('Error Log', 'wp-auth0'), + esc_html__('Error Log', 'wp-auth0'), $cap, 'wpa0-errors', - [ new WP_Auth0_ErrorLog(), 'render_settings_page' ] + [new WP_Auth0_ErrorLog(), 'render_settings_page'] ); add_submenu_page( $menu_parent, - __( 'Import-Export Settings', 'wp-auth0' ), - __( 'Import-Export settings', 'wp-auth0' ), + esc_html__('Import-Export Settings', 'wp-auth0'), + esc_html__('Import-Export settings', 'wp-auth0'), $cap, 'wpa0-import-settings', - [ new WP_Auth0_Import_Settings( $options ), 'render_import_settings_page' ] + [new WP_Auth0_Import_Settings($options), 'render_import_settings_page'] ); } -add_action( 'admin_menu', 'wp_auth0_init_admin_menu', 96, 0 ); +add_action('admin_menu', 'wp_auth0_init_admin_menu', 96, 0); -function wp_auth0_create_account_message() { +function wp_auth0_create_account_message() +{ // Not processing form data, just using a redirect parameter if present. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // Null coalescing validates input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated $current_page = $_GET['page'] ?? null; - $is_correct_admin = in_array( $current_page, [ 'wpa0', 'wpa0-errors', 'wpa0-import-settings' ] ); - if ( wp_auth0_is_ready() || ! $is_correct_admin ) { + $is_correct_admin = in_array($current_page, ['wpa0', 'wpa0-errors', 'wpa0-import-settings']); + if (wp_auth0_is_ready() || !$is_correct_admin) { return false; } - printf( - '
%s - + echo wp_kses(sprintf( + '
%s + %s.
', - __( 'Plugin is not yet configured. Please follow the ', 'wp-auth0' ), - __( 'setup instructions', 'wp-auth0' ) - ); + esc_html__('Plugin is not yet configured. Please follow the ', 'wp-auth0'), + esc_html__('setup instructions', 'wp-auth0') + ), ['div' => ['style' => true], 'strong' => [], 'a' => ['href' => true, 'target' => true, 'style' => true]]); + return true; + + // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification +} +function wp_auth0_deprecated_version() +{ + // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification + + // Null coalescing validates input variable. + // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated + $current_page = $_GET['page'] ?? null; + $is_correct_admin = in_array($current_page, ['wpa0', 'wpa0-errors', 'wpa0-import-settings']); + if (wp_auth0_is_ready() || !$is_correct_admin) { + return false; + } + + echo wp_kses(sprintf( + '
%s + + %s.
', + esc_html__('This version of the Auth0 WordPress plugin is no longer supported. Please ', 'wp-auth0'), + esc_html__('upgrade to v5.', 'wp-auth0') + ), ['div' => ['style' => true], 'strong' => [], 'a' => ['href' => true, 'target' => true, 'style' => true]]); return true; // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification } -add_action( 'admin_notices', 'wp_auth0_create_account_message' ); +// add_action('admin_notices', 'wp_auth0_deprecated_version'); +add_action('admin_notices', 'wp_auth0_create_account_message'); -function wp_auth0_init_admin() { +function wp_auth0_init_admin() +{ $options = WP_Auth0_Options::Instance(); - $routes = new WP_Auth0_Routes( $options ); - $admin = new WP_Auth0_Admin( $options, $routes ); + $routes = new WP_Auth0_Routes($options); + $admin = new WP_Auth0_Admin($options, $routes); $admin->init_admin(); } -add_action( 'admin_init', 'wp_auth0_init_admin' ); +add_action('admin_init', 'wp_auth0_init_admin'); -function wp_auth0_admin_enqueue_scripts() { +function wp_auth0_admin_enqueue_scripts() +{ $options = WP_Auth0_Options::Instance(); - $routes = new WP_Auth0_Routes( $options ); - $admin = new WP_Auth0_Admin( $options, $routes ); + $routes = new WP_Auth0_Routes($options); + $admin = new WP_Auth0_Admin($options, $routes); return $admin->admin_enqueue(); } -add_action( 'admin_enqueue_scripts', 'wp_auth0_admin_enqueue_scripts', 1 ); +add_action('admin_enqueue_scripts', 'wp_auth0_admin_enqueue_scripts', 1); -function wp_auth0_custom_requests( $wp, $return = false ) { - $routes = new WP_Auth0_Routes( WP_Auth0_Options::Instance() ); - return $routes->custom_requests( $wp, $return ); +function wp_auth0_custom_requests($wp, $return = false) +{ + $routes = new WP_Auth0_Routes(WP_Auth0_Options::Instance()); + return $routes->custom_requests($wp, $return); } -add_action( 'parse_request', 'wp_auth0_custom_requests' ); +add_action('parse_request', 'wp_auth0_custom_requests'); -function wp_auth0_profile_enqueue_scripts() { +function wp_auth0_profile_enqueue_scripts() +{ global $pagenow; - if ( ! in_array( $pagenow, [ 'profile.php', 'user-edit.php' ] ) ) { + if (!in_array($pagenow, ['profile.php', 'user-edit.php'])) { return false; } wp_enqueue_script( 'wpa0_user_profile', WPA0_PLUGIN_JS_URL . 'edit-user-profile.js', - [ 'jquery' ], - WPA0_VERSION + ['jquery'], + WPA0_VERSION, + true ); - $profile = get_auth0userinfo( $GLOBALS['user_id'] ); - $strategy = isset( $profile->sub ) ? WP_Auth0_Users::get_strategy( $profile->sub ) : ''; + $profile = get_auth0userinfo($GLOBALS['user_id']); + $strategy = isset($profile->sub) ? WP_Auth0_Users::get_strategy($profile->sub) : ''; wp_localize_script( 'wpa0_user_profile', 'wpa0UserProfile', [ - 'userId' => intval( $GLOBALS['user_id'] ), - 'userStrategy' => sanitize_text_field( $strategy ), - 'deleteIdNonce' => wp_create_nonce( 'delete_auth0_identity' ), - 'ajaxUrl' => admin_url( 'admin-ajax.php' ), + 'userId' => intval($GLOBALS['user_id']), + 'userStrategy' => sanitize_text_field($strategy), + 'deleteIdNonce' => wp_create_nonce('delete_auth0_identity'), + 'ajaxUrl' => admin_url('admin-ajax.php'), 'i18n' => [ - 'confirmDeleteId' => __( 'Are you sure you want to delete the Auth0 user data for this user?', 'wp-auth0' ), - 'actionComplete' => __( 'Deleted', 'wp-auth0' ), - 'actionFailed' => __( 'Action failed, please see the Auth0 error log for details.', 'wp-auth0' ), - 'cannotChangeEmail' => __( 'Email cannot be changed for non-database connections.', 'wp-auth0' ), + 'confirmDeleteId' => esc_html__('Are you sure you want to delete the Auth0 user data for this user?', 'wp-auth0'), + 'actionComplete' => esc_html__('Deleted', 'wp-auth0'), + 'actionFailed' => esc_html__('Action failed, please see the Auth0 error log for details.', 'wp-auth0'), + 'cannotChangeEmail' => esc_html__('Email cannot be changed for non-database connections.', 'wp-auth0'), ], ] ); return true; } -add_action( 'admin_enqueue_scripts', 'wp_auth0_profile_enqueue_scripts' ); +add_action('admin_enqueue_scripts', 'wp_auth0_profile_enqueue_scripts'); -function wp_auth0_process_auth_callback() { - $users_repo = new WP_Auth0_UsersRepo( WP_Auth0_Options::Instance() ); - $login_manager = new WP_Auth0_LoginManager( $users_repo, WP_Auth0_Options::Instance() ); +function wp_auth0_process_auth_callback() +{ + $users_repo = new WP_Auth0_UsersRepo(WP_Auth0_Options::Instance()); + $login_manager = new WP_Auth0_LoginManager($users_repo, WP_Auth0_Options::Instance()); return $login_manager->init_auth0(); } -add_action( 'template_redirect', 'wp_auth0_process_auth_callback', 1 ); +add_action('template_redirect', 'wp_auth0_process_auth_callback', 1); -function wp_auth0_login_ulp_redirect() { - $users_repo = new WP_Auth0_UsersRepo( WP_Auth0_Options::Instance() ); - $login_manager = new WP_Auth0_LoginManager( $users_repo, WP_Auth0_Options::Instance() ); +function wp_auth0_login_ulp_redirect() +{ + $users_repo = new WP_Auth0_UsersRepo(WP_Auth0_Options::Instance()); + $login_manager = new WP_Auth0_LoginManager($users_repo, WP_Auth0_Options::Instance()); return $login_manager->login_auto(); } -add_action( 'login_init', 'wp_auth0_login_ulp_redirect' ); +add_action('login_init', 'wp_auth0_login_ulp_redirect'); -function wp_auth0_process_logout() { - $users_repo = new WP_Auth0_UsersRepo( WP_Auth0_Options::Instance() ); - $login_manager = new WP_Auth0_LoginManager( $users_repo, WP_Auth0_Options::Instance() ); +function wp_auth0_process_logout() +{ + $users_repo = new WP_Auth0_UsersRepo(WP_Auth0_Options::Instance()); + $login_manager = new WP_Auth0_LoginManager($users_repo, WP_Auth0_Options::Instance()); $login_manager->logout(); } -add_action( 'wp_logout', 'wp_auth0_process_logout' ); +add_action('wp_logout', 'wp_auth0_process_logout'); -function wp_auth0_ajax_delete_cache_transient() { - check_ajax_referer( 'auth0_delete_cache_transient' ); - delete_transient( WPA0_JWKS_CACHE_TRANSIENT_NAME ); +function wp_auth0_ajax_delete_cache_transient() +{ + check_ajax_referer('auth0_delete_cache_transient'); + delete_transient(WPA0_JWKS_CACHE_TRANSIENT_NAME); wp_send_json_success(); } -add_action( 'wp_ajax_auth0_delete_cache_transient', 'wp_auth0_ajax_delete_cache_transient' ); +add_action('wp_ajax_auth0_delete_cache_transient', 'wp_auth0_ajax_delete_cache_transient'); /** * AJAX endpoint to rotate the migration token. */ -function wp_auth0_ajax_rotate_migration_token() { - check_ajax_referer( WP_Auth0_Admin_Advanced::ROTATE_TOKEN_NONCE_ACTION ); +function wp_auth0_ajax_rotate_migration_token() +{ + check_ajax_referer(WP_Auth0_Admin_Advanced::ROTATE_TOKEN_NONCE_ACTION); - if ( ! current_user_can( 'manage_options' ) ) { - wp_send_json_error( [ 'error' => __( 'Not authorized.', 'wp-auth0' ) ] ); + if (!current_user_can('manage_options')) { + wp_send_json_error(['error' => esc_html__('Not authorized.', 'wp-auth0')]); return; } - WP_Auth0_Options::Instance()->set( 'migration_token', wp_auth0_generate_token() ); + WP_Auth0_Options::Instance()->set('migration_token', wp_auth0_generate_token()); wp_send_json_success(); } -add_action( 'wp_ajax_auth0_rotate_migration_token', 'wp_auth0_ajax_rotate_migration_token' ); +add_action('wp_ajax_auth0_rotate_migration_token', 'wp_auth0_ajax_rotate_migration_token'); /** * AJAX handler to re-send verification email. @@ -574,26 +635,27 @@ function wp_auth0_ajax_rotate_migration_token() { * * @codeCoverageIgnore - Tested in TestEmailVerification::testResendVerificationEmail() */ -function wp_auth0_ajax_resend_verification_email() { - check_ajax_referer( WP_Auth0_Email_Verification::RESEND_NONCE_ACTION ); +function wp_auth0_ajax_resend_verification_email() +{ + check_ajax_referer(WP_Auth0_Email_Verification::RESEND_NONCE_ACTION); $options = WP_Auth0_Options::Instance(); - $api_client_creds = new WP_Auth0_Api_Client_Credentials( $options ); - $api_jobs_verification = new WP_Auth0_Api_Jobs_Verification( $options, $api_client_creds ); + $api_client_creds = new WP_Auth0_Api_Client_Credentials($options); + $api_jobs_verification = new WP_Auth0_Api_Jobs_Verification($options, $api_client_creds); - if ( empty( $_POST['sub'] ) ) { - wp_send_json_error( [ 'error' => __( 'No Auth0 user ID provided.', 'wp-auth0' ) ] ); + if (empty($_POST['sub'])) { + wp_send_json_error(['error' => esc_html__('No Auth0 user ID provided.', 'wp-auth0')]); } // Validated above and only sent to the change signup API endpoint. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - if ( ! $api_jobs_verification->call( wp_unslash( $_POST['sub'] ) ) ) { - wp_send_json_error( [ 'error' => __( 'API call failed.', 'wp-auth0' ) ] ); + if (!$api_jobs_verification->call(wp_unslash($_POST['sub']))) { + wp_send_json_error(['error' => esc_html__('API call failed.', 'wp-auth0')]); } wp_send_json_success(); } -add_action( 'wp_ajax_nopriv_resend_verification_email', 'wp_auth0_ajax_resend_verification_email' ); +add_action('wp_ajax_nopriv_resend_verification_email', 'wp_auth0_ajax_resend_verification_email'); /** * Redirect a successful lost password submission to a login override page. @@ -602,34 +664,35 @@ function wp_auth0_ajax_resend_verification_email() { * * @return string */ -function wp_auth0_filter_wp_redirect_lostpassword( $location ) { +function wp_auth0_filter_wp_redirect_lostpassword($location) +{ // Make sure we're going to the check email action on the wp-login page. - if ( 'wp-login.php?checkemail=confirm' !== $location ) { + if ('wp-login.php?checkemail=confirm' !== $location) { return $location; } // Make sure we're on the lost password action on the wp-login page. - if ( ! wp_auth0_is_current_login_action( [ 'lostpassword' ] ) ) { + if (!wp_auth0_is_current_login_action(['lostpassword'])) { return $location; } // Make sure plugin settings allow core WP login form overrides - if ( 'never' === wp_auth0_get_option( 'wordpress_login_enabled' ) ) { + if ('never' === wp_auth0_get_option('wordpress_login_enabled')) { return $location; } // Make sure we're coming from an override page. - $required_referrer = remove_query_arg( 'wle', wp_login_url() ); - $required_referrer = add_query_arg( 'action', 'lostpassword', $required_referrer ); - $required_referrer = wp_auth0_login_override_url( $required_referrer ); - if ( ! isset( $_SERVER['HTTP_REFERER'] ) || $required_referrer !== $_SERVER['HTTP_REFERER'] ) { + $required_referrer = remove_query_arg('wle', wp_login_url()); + $required_referrer = add_query_arg('action', 'lostpassword', $required_referrer); + $required_referrer = wp_auth0_login_override_url($required_referrer); + if (!isset($_SERVER['HTTP_REFERER']) || $required_referrer !== $_SERVER['HTTP_REFERER']) { return $location; } - return wp_auth0_login_override_url( $location ); + return wp_auth0_login_override_url($location); } -add_filter( 'wp_redirect', 'wp_auth0_filter_wp_redirect_lostpassword', 100 ); +add_filter('wp_redirect', 'wp_auth0_filter_wp_redirect_lostpassword', 100); /** * Add an override code to the lost password URL if authorized. @@ -638,46 +701,48 @@ function wp_auth0_filter_wp_redirect_lostpassword( $location ) { * * @return string */ -function wp_auth0_filter_login_override_url( $wp_login_url ) { +function wp_auth0_filter_login_override_url($wp_login_url) +{ // Not processing form data, just using a redirect parameter if present. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $options = WP_Auth0_Options::Instance(); - $wle = $options->get( 'wle_code' ); + $wle = $options->get('wle_code'); - if ( wp_auth0_can_show_wp_login_form() && $wle !== null ) { + if (wp_auth0_can_show_wp_login_form() && $wle !== null) { // We are on an override page. - } elseif ( wp_auth0_is_current_login_action( [ 'resetpass' ] ) ) { + } elseif (wp_auth0_is_current_login_action(['resetpass'])) { // We are on the reset password page with a link to login. // This page will not be shown unless we get here via a valid reset password request. - $wp_login_url = wp_auth0_login_override_url( $wp_login_url ); + $wp_login_url = wp_auth0_login_override_url($wp_login_url); } return esc_url($wp_login_url); // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification } -add_filter( 'lostpassword_url', 'wp_auth0_filter_login_override_url', 100 ); -add_filter( 'login_url', 'wp_auth0_filter_login_override_url', 100 ); +add_filter('lostpassword_url', 'wp_auth0_filter_login_override_url', 100); +add_filter('login_url', 'wp_auth0_filter_login_override_url', 100); /** * Add the core WP form override to the lost password and login forms. */ -function wp_auth0_filter_login_override_form() { +function wp_auth0_filter_login_override_form() +{ // Not processing form data, just using a redirect parameter if present. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification - if ( wp_auth0_can_show_wp_login_form() && isset( $_REQUEST['wle'] ) ) { + if (wp_auth0_can_show_wp_login_form() && isset($_REQUEST['wle'])) { // Input is being output, not stored. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - printf( '', esc_attr( wp_unslash( $_REQUEST['wle'] ) ) ); + echo wp_kses(sprintf('', esc_attr(wp_unslash($_REQUEST['wle']))), ['input' => ['type' => true, 'name' => true, 'value' => true]]); } // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification } -add_action( 'login_form', 'wp_auth0_filter_login_override_form', 100 ); -add_action( 'lostpassword_form', 'wp_auth0_filter_login_override_form', 100 ); +add_action('login_form', 'wp_auth0_filter_login_override_form', 100); +add_action('lostpassword_form', 'wp_auth0_filter_login_override_form', 100); /** * Add new classes to the body element on all front-end and login pages. @@ -686,14 +751,15 @@ function wp_auth0_filter_login_override_form() { * * @return array */ -function wp_auth0_filter_body_class( array $classes ) { - if ( wp_auth0_can_show_wp_login_form() ) { +function wp_auth0_filter_body_class(array $classes) +{ + if (wp_auth0_can_show_wp_login_form()) { $classes[] = 'a0-show-core-login'; } return $classes; } -add_filter( 'body_class', 'wp_auth0_filter_body_class' ); -add_filter( 'login_body_class', 'wp_auth0_filter_body_class' ); +add_filter('body_class', 'wp_auth0_filter_body_class'); +add_filter('login_body_class', 'wp_auth0_filter_body_class'); /* * WooCommerce hooks @@ -706,11 +772,12 @@ function wp_auth0_filter_body_class( array $classes ) { * * @return mixed */ -function wp_auth0_filter_woocommerce_checkout_login_message( $html ) { - $wp_auth0_woocommerce = new WP_Auth0_WooCommerceOverrides( WP_Auth0_Options::Instance() ); - return $wp_auth0_woocommerce->override_woocommerce_checkout_login_form( $html ); +function wp_auth0_filter_woocommerce_checkout_login_message($html) +{ + $wp_auth0_woocommerce = new WP_Auth0_WooCommerceOverrides(WP_Auth0_Options::Instance()); + return $wp_auth0_woocommerce->override_woocommerce_checkout_login_form($html); } -add_filter( 'woocommerce_checkout_login_message', 'wp_auth0_filter_woocommerce_checkout_login_message' ); +add_filter('woocommerce_checkout_login_message', 'wp_auth0_filter_woocommerce_checkout_login_message'); /** * Add the Auth0 login form to the account page. @@ -719,16 +786,17 @@ function wp_auth0_filter_woocommerce_checkout_login_message( $html ) { * * @return mixed */ -function wp_auth0_filter_woocommerce_before_customer_login_form( $html ) { - $wp_auth0_woocommerce = new WP_Auth0_WooCommerceOverrides( WP_Auth0_Options::Instance() ); - return $wp_auth0_woocommerce->override_woocommerce_login_form( $html ); +function wp_auth0_filter_woocommerce_before_customer_login_form($html) +{ + $wp_auth0_woocommerce = new WP_Auth0_WooCommerceOverrides(WP_Auth0_Options::Instance()); + return $wp_auth0_woocommerce->override_woocommerce_login_form($html); } -add_filter( 'woocommerce_before_customer_login_form', 'wp_auth0_filter_woocommerce_before_customer_login_form' ); +add_filter('woocommerce_before_customer_login_form', 'wp_auth0_filter_woocommerce_before_customer_login_form'); /* * Beta plugin deactivation */ // Passwordless beta testing - https://github.com/auth0/wp-auth0/issues/400 -remove_filter( 'login_message', 'wp_auth0_pwl_plugin_login_message_before', 5 ); -remove_filter( 'login_message', 'wp_auth0_pwl_plugin_login_message_after', 6 ); +remove_filter('login_message', 'wp_auth0_pwl_plugin_login_message_before', 5); +remove_filter('login_message', 'wp_auth0_pwl_plugin_login_message_after', 6); diff --git a/composer.json b/composer.json index c7c34ddf3..bd0ffa647 100644 --- a/composer.json +++ b/composer.json @@ -32,13 +32,13 @@ "composer/installers": "^2.0" }, "require-dev": { - "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "dealerdirect/phpcodesniffer-composer-installer": "^1", "phpcompatibility/phpcompatibility-wp": "*", - "phpstan/phpstan": "^1.0", - "phpunit/phpunit": "^9.0", - "szepeviktor/phpstan-wordpress": "^1.0", + "phpstan/phpstan": "^1", + "phpunit/phpunit": "^9", + "szepeviktor/phpstan-wordpress": "^1", "wp-coding-standards/wpcs": "*", - "yoast/phpunit-polyfills": "^1.0" + "yoast/phpunit-polyfills": "^1" }, "config": { "classmap-authoritative": true, diff --git a/examples/auth0_before_login.php b/examples/auth0_before_login.php index 64834ef8a..533d4644c 100644 --- a/examples/auth0_before_login.php +++ b/examples/auth0_before_login.php @@ -9,9 +9,10 @@ * @param WP_User $user - WordPress user object. * @param stdClass $userinfo - user information object from Auth0 */ -function example_auth0_before_login( $user, $userinfo ) { - echo 'WP user:
' . print_r( $user, true ) . '

'; - echo 'Auth0 user info:
' . print_r( $userinfo, true ) . '

'; - wp_die( 'Login process started!' ); +function example_auth0_before_login($user, $userinfo) +{ + echo 'WP user:
' . esc_html(print_r($user, true)) . '

'; + echo 'Auth0 user info:
' . esc_html(print_r($userinfo, true)) . '

'; + wp_die('Login process started!'); } - add_action( 'auth0_before_login', 'example_auth0_before_login', 10, 2 ); +add_action('auth0_before_login', 'example_auth0_before_login', 10, 2); diff --git a/examples/auth0_die_on_login_output.php b/examples/auth0_die_on_login_output.php index 45d49d30c..4fdda1e5c 100644 --- a/examples/auth0_die_on_login_output.php +++ b/examples/auth0_die_on_login_output.php @@ -1,4 +1,5 @@ %s Message: %s
Code: %s
Link: %s
', - esc_html( $html ), - sanitize_text_field( $msg ), - sanitize_text_field( $code ), + esc_html($html), + sanitize_text_field($msg), + sanitize_text_field($code), $login_link ? 'TRUE' : 'FALSE' - ); + ), ['code' => ['style' => true], 'strong' => [], 'br' => []]); } -add_filter( 'auth0_die_on_login_output', 'example_auth0_die_on_login_output', 10, 4 ); +add_filter('auth0_die_on_login_output', 'example_auth0_die_on_login_output', 10, 4); diff --git a/examples/auth0_settings_fields.php b/examples/auth0_settings_fields.php index 247507195..f7d114b34 100644 --- a/examples/auth0_settings_fields.php +++ b/examples/auth0_settings_fields.php @@ -1,4 +1,5 @@ __( 'A Custom Basic Setting', 'wp-auth0' ), + 'name' => esc_html__('A Custom Basic Setting', 'wp-auth0'), 'opt' => 'custom_basic_opt_name', 'id' => 'wpa0_custom_basic_opt_name', 'function' => 'example_render_custom_basic_opt_name', @@ -28,7 +30,7 @@ function example_auth0_settings_fields( $options, $id ) { } return $options; } - add_filter( 'auth0_settings_fields', 'example_auth0_settings_fields', 10, 2 ); +add_filter('auth0_settings_fields', 'example_auth0_settings_fields', 10, 2); /** * Callback for add_settings_field @@ -37,13 +39,14 @@ function example_auth0_settings_fields( $options, $id ) { * * @see example_auth0_settings_fields() */ -function example_render_custom_basic_opt_name( $args ) { +function example_render_custom_basic_opt_name($args) +{ $options = WP_Auth0_Options::Instance(); printf( '', - esc_attr( $options->get_options_name() ), - esc_attr( $args['opt_name'] ), - esc_attr( $args['label_for'] ), - esc_attr( $options->get( $args['opt_name'] ) ) + esc_attr($options->get_options_name()), + esc_attr($args['opt_name']), + esc_attr($args['label_for']), + esc_attr($options->get($args['opt_name'])) ); } diff --git a/examples/auth0_user_login.php b/examples/auth0_user_login.php index a1ad1f4d9..9d61778ea 100644 --- a/examples/auth0_user_login.php +++ b/examples/auth0_user_login.php @@ -1,4 +1,5 @@ WP user ID
:
' . $user_id . '
'; - echo 'Auth0 user info:
' . print_r( $userinfo, true ) . '

'; - echo 'Added to WP DB?:
' . ( $is_new ? 'yep' : 'nope' ) . '
'; - echo 'ID Token:
' . ( $id_token ? $id_token : 'not provided' ) . '
'; - echo 'Access Token:
' . ( $access_token ? $access_token : 'not provided' ) . '
'; - echo 'Refresh Token:
' . ( $refresh_token ? $refresh_token : 'not provided' ) . '
'; - wp_die( 'Login successful! Home' ); +function example_auth0_user_login($user_id, $userinfo, $is_new, $id_token, $access_token, $refresh_token) +{ + echo 'WP user ID:
' . esc_html($user_id) . '
'; + echo 'Auth0 user info:
' . esc_html(print_r($userinfo, true)) . '

'; + echo 'Added to WP DB?:
' . ($is_new ? 'yep' : 'nope') . '
'; + echo 'ID Token:
' . ($id_token ? esc_html($id_token) : 'not provided') . '
'; + echo 'Access Token:
' . ($access_token ? esc_html($access_token) : 'not provided') . '
'; + echo 'Refresh Token:
' . ($refresh_token ? esc_html($refresh_token) : 'not provided') . '
'; + wp_die(wp_kses('Login successful! Home', ['a' => ['href' => true]])); } -add_action( 'auth0_user_login', 'example_auth0_user_login', 10, 6 ); +add_action('auth0_user_login', 'example_auth0_user_login', 10, 6); diff --git a/examples/wpa0_user_created.php b/examples/wpa0_user_created.php index c191add95..c5e97b75b 100644 --- a/examples/wpa0_user_created.php +++ b/examples/wpa0_user_created.php @@ -12,12 +12,13 @@ * @param string $f_name - first name for created user * @param string $l_name - last name for created user */ -function example_wpa0_user_created( $user_id, $email, $password, $f_name, $l_name ) { - echo 'User ID:
' . $user_id . '
'; - echo 'Email:
' . $email . '
'; - echo 'Password:
' . $password . '
'; - echo 'First name:
' . $f_name . '
'; - echo 'Last name:
' . $l_name . '
'; - wp_die( 'User created!' ); +function example_wpa0_user_created($user_id, $email, $password, $f_name, $l_name) +{ + echo 'User ID:
' . esc_html($user_id) . '
'; + echo 'Email:
' . esc_html($email) . '
'; + echo 'Password:
' . esc_html($password) . '
'; + echo 'First name:
' . esc_html($f_name) . '
'; + echo 'Last name:
' . esc_html($l_name) . '
'; + wp_die('User created!'); } - add_action( 'wpa0_user_created', 'example_wpa0_user_created', 10, 5 ); +add_action('wpa0_user_created', 'example_wpa0_user_created', 10, 5); diff --git a/lib/WP_Auth0_Api_Client.php b/lib/WP_Auth0_Api_Client.php index 77c9b5512..3d92a9254 100755 --- a/lib/WP_Auth0_Api_Client.php +++ b/lib/WP_Auth0_Api_Client.php @@ -1,4 +1,5 @@ wp_auth0_get_option( 'domain' ), - 'client_id' => wp_auth0_get_option( 'client_id' ), - 'client_secret' => wp_auth0_get_option( 'client_secret' ), + 'domain' => wp_auth0_get_option('domain'), + 'client_id' => wp_auth0_get_option('client_id'), + 'client_secret' => wp_auth0_get_option('client_secret'), 'app_token' => null, - 'audience' => self::get_endpoint( 'api/v2/' ), + 'audience' => self::get_endpoint('api/v2/'), ]; } - if ( empty( $opt ) ) { + if (empty($opt)) { return self::$connect_info; } else { - return ! empty( self::$connect_info[ $opt ] ) ? self::$connect_info[ $opt ] : ''; + return !empty(self::$connect_info[$opt]) ? self::$connect_info[$opt] : ''; } } @@ -82,15 +86,16 @@ public static function get_connect_info( $opt = '' ) { * * @return array */ - private static function get_headers( $token = '', $content_type = 'application/json' ) { + private static function get_headers($token = '', $content_type = 'application/json') + { $headers = WP_Auth0_Api_Abstract::get_info_headers(); - if ( ! empty( $token ) ) { + if (!empty($token)) { $headers['Authorization'] = "Bearer {$token}"; } - if ( ! empty( $content_type ) ) { + if (!empty($content_type)) { $headers['Content-Type'] = $content_type; } @@ -105,7 +110,8 @@ private static function get_headers( $token = '', $content_type = 'application/j * * @return mixed */ - public static function signup_user( $domain, $data ) { + public static function signup_user($domain, $data) + { $endpoint = "https://$domain/dbconnections/signup"; @@ -117,21 +123,21 @@ public static function signup_user( $domain, $data ) { $endpoint, [ 'headers' => $headers, - 'body' => json_encode( $data ), + 'body' => json_encode($data), ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response); return false; } - if ( $response['response']['code'] !== 200 ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + if ($response['response']['code'] !== 200) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } /** @@ -139,7 +145,8 @@ public static function signup_user( $domain, $data ) { * * @return array */ - public static function get_required_scopes() { + public static function get_required_scopes() + { return [ 'read:users', 'update:users', @@ -158,7 +165,8 @@ public static function get_required_scopes() { * * @return bool|object|array */ - public static function create_client( $domain, $app_token, $name ) { + public static function create_client($domain, $app_token, $name) + { $options = WP_Auth0_Options::Instance(); @@ -175,7 +183,7 @@ public static function create_client( $domain, $app_token, $name ) { 'web_origins' => $options->get_web_origins(), // Force SSL, will not work without it - 'cross_origin_loc' => add_query_arg( 'auth0fallback', '1', site_url( 'index.php', 'https' ) ), + 'cross_origin_loc' => add_query_arg('auth0fallback', '1', site_url('index.php', 'https')), 'cross_origin_auth' => true, // A set of URLs that are valid to redirect to after logout from Auth0 @@ -201,24 +209,24 @@ public static function create_client( $domain, $app_token, $name ) { ]; $response = wp_remote_post( - self::get_endpoint( 'api/v2/clients', $domain ), + self::get_endpoint('api/v2/clients', $domain), [ - 'headers' => self::get_headers( $app_token ), - 'body' => json_encode( $payload ), + 'headers' => self::get_headers($app_token), + 'body' => json_encode($payload), ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response->get_error_message() ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response->get_error_message()); return false; } - if ( $response['response']['code'] != 201 ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + if ($response['response']['code'] != 201) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } @@ -230,50 +238,50 @@ public static function create_client( $domain, $app_token, $name ) { * * @return array|bool|mixed|object */ - public static function create_client_grant( $app_token, $client_id ) { + public static function create_client_grant($app_token, $client_id) + { $data = [ 'client_id' => $client_id, - 'audience' => self::get_connect_info( 'audience' ), + 'audience' => self::get_connect_info('audience'), 'scope' => self::get_required_scopes(), ]; $response = wp_remote_post( - self::get_endpoint( 'api/v2/client-grants' ), + self::get_endpoint('api/v2/client-grants'), [ - 'headers' => self::get_headers( $app_token ), - 'body' => json_encode( $data ), + 'headers' => self::get_headers($app_token), + 'body' => json_encode($data), ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response); return false; } - if ( 409 === $response['response']['code'] ) { + if (409 === $response['response']['code']) { // Client grant from WP-created client to Management API already exists WP_Auth0_ErrorLog::insert_error( __METHOD__, - sprintf( + esc_html(sprintf( // translators: placeholders are machine names stored for this WP instance and must be included. - __( 'A client grant for %1$s to %2$s already exists. Make sure this grant at least includes %3$s.', 'wp-auth0' ), - self::get_connect_info( 'client_id' ), - self::get_connect_info( 'audience' ), - implode( ', ', self::get_required_scopes() ) - ) + esc_html__('A client grant for %1$s to %2$s already exists. Make sure this grant at least includes %3$s.', 'wp-auth0'), + self::get_connect_info('client_id'), + self::get_connect_info('audience'), + implode(', ', self::get_required_scopes()) + )) ); - return json_decode( $response['body'] ); - - } elseif ( $response['response']['code'] != 201 ) { + return json_decode($response['body']); + } elseif ($response['response']['code'] != 201) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } /** @@ -285,7 +293,8 @@ public static function create_client_grant( $app_token, $client_id ) { * * @return mixed */ - public static function create_connection( $domain, $app_token, $payload ) { + public static function create_connection($domain, $app_token, $payload) + { $endpoint = "https://$domain/api/v2/connections"; $headers = WP_Auth0_Api_Abstract::get_info_headers(); @@ -298,21 +307,21 @@ public static function create_connection( $domain, $app_token, $payload ) { [ 'method' => 'POST', 'headers' => $headers, - 'body' => json_encode( $payload ), + 'body' => json_encode($payload), ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response); return false; } - if ( $response['response']['code'] != 201 ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + if ($response['response']['code'] != 201) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } /** @@ -325,14 +334,15 @@ public static function create_connection( $domain, $app_token, $payload ) { * * @return array|bool|mixed|object */ - public static function search_connection( $domain, $app_token, $strategy = null, $name = null ) { + public static function search_connection($domain, $app_token, $strategy = null, $name = null) + { $add_queries = []; - if ( $strategy ) { + if ($strategy) { $add_queries['strategy'] = $strategy; } - if ( $name ) { + if ($name) { $add_queries['name'] = $name; } @@ -341,27 +351,27 @@ public static function search_connection( $domain, $app_token, $strategy = null, $headers['Authorization'] = "Bearer $app_token"; $response = wp_remote_get( - add_query_arg( $add_queries, 'https://' . $domain . '/api/v2/connections' ), + add_query_arg($add_queries, 'https://' . $domain . '/api/v2/connections'), [ 'headers' => $headers, ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response); return false; } - if ( $response['response']['code'] != 200 ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + if ($response['response']['code'] != 200) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - if ( $response['response']['code'] >= 300 ) { + if ($response['response']['code'] >= 300) { return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } /** @@ -375,7 +385,8 @@ public static function search_connection( $domain, $app_token, $strategy = null, * * @return bool|object */ - public static function update_connection( $domain, $app_token, $id, $payload ) { + public static function update_connection($domain, $app_token, $id, $payload) + { $endpoint = "https://$domain/api/v2/connections/$id"; $headers = WP_Auth0_Api_Abstract::get_info_headers(); @@ -383,12 +394,12 @@ public static function update_connection( $domain, $app_token, $id, $payload ) { $headers['Authorization'] = "Bearer $app_token"; $headers['content-type'] = 'application/json'; - unset( $payload->name ); - unset( $payload->strategy ); - unset( $payload->id ); + unset($payload->name); + unset($payload->strategy); + unset($payload->id); - if ( ! empty( $payload->enabled_clients ) ) { - $payload->enabled_clients = array_values( $payload->enabled_clients ); + if (!empty($payload->enabled_clients)) { + $payload->enabled_clients = array_values($payload->enabled_clients); } $response = wp_remote_post( @@ -396,25 +407,25 @@ public static function update_connection( $domain, $app_token, $id, $payload ) { [ 'method' => 'PATCH', 'headers' => $headers, - 'body' => json_encode( $payload ), + 'body' => json_encode($payload), ] ); - if ( $response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response ); + if ($response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response); return false; } - if ( $response['response']['code'] != 200 ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $response['body'] ); + if ($response['response']['code'] != 200) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $response['body']); return false; } - if ( $response['response']['code'] >= 300 ) { + if ($response['response']['code'] >= 300) { return false; } - return json_decode( $response['body'] ); + return json_decode($response['body']); } /** @@ -422,7 +433,8 @@ public static function update_connection( $domain, $app_token, $id, $payload ) { * * @return array */ - public static function ConsentRequiredScopes() { + public static function ConsentRequiredScopes() + { return [ 'create:clients', 'create:client_grants', @@ -439,7 +451,8 @@ public static function ConsentRequiredScopes() { * * @return array */ - public static function get_client_grant_types() { + public static function get_client_grant_types() + { return [ 'authorization_code', diff --git a/lib/WP_Auth0_Api_Operations.php b/lib/WP_Auth0_Api_Operations.php index f1607e77b..84c031298 100644 --- a/lib/WP_Auth0_Api_Operations.php +++ b/lib/WP_Auth0_Api_Operations.php @@ -1,16 +1,19 @@ a0_options = $a0_options; } - public function create_wordpress_connection( $app_token, $migration_enabled, $password_policy = '', $migration_token = null ) { + public function create_wordpress_connection($app_token, $migration_enabled, $password_policy = '', $migration_token = null) + { - $domain = $this->a0_options->get( 'domain' ); - $client_id = $this->a0_options->get( 'client_id' ); + $domain = $this->a0_options->get('domain'); + $client_id = $this->a0_options->get('client_id'); $db_connection_name = 'DB-' . get_auth0_curatedBlogName(); $body = [ @@ -24,17 +27,17 @@ public function create_wordpress_connection( $app_token, $migration_enabled, $pa ], ]; - if ( $migration_enabled ) { + if ($migration_enabled) { $ipCheck = new WP_Auth0_Ip_Check(); - $ips = $ipCheck->get_ips_by_domain( $domain ); + $ips = $ipCheck->get_ips_by_domain($domain); - if ( $ips ) { - $this->a0_options->set( 'migration_ips', $ips ); - $this->a0_options->set( 'migration_ips_filter', true ); + if ($ips) { + $this->a0_options->set('migration_ips', $ips); + $this->a0_options->set('migration_ips_filter', true); } else { - $this->a0_options->set( 'migration_ips', null ); - $this->a0_options->set( 'migration_ips_filter', false ); + $this->a0_options->set('migration_ips', null); + $this->a0_options->set('migration_ips_filter', false); } $body['options'] = [ @@ -50,23 +53,22 @@ public function create_wordpress_connection( $app_token, $migration_enabled, $pa ], ], 'customScripts' => [ - 'login' => $this->get_script( 'login' ), - 'get_user' => $this->get_script( 'get-user' ), + 'login' => $this->get_script('login'), + 'get_user' => $this->get_script('get-user'), ], 'bareConfiguration' => [ - 'endpointUrl' => site_url( 'index.php?a0_action=' ), + 'endpointUrl' => site_url('index.php?a0_action='), 'migrationToken' => $migration_token, 'userNamespace' => 'DB-' . get_auth0_curatedBlogName(), ], ]; - } - $this->a0_options->set( 'db_connection_name', $db_connection_name ); + $this->a0_options->set('db_connection_name', $db_connection_name); - $response = WP_Auth0_Api_Client::create_connection( $domain, $app_token, $body ); + $response = WP_Auth0_Api_Client::create_connection($domain, $app_token, $body); - if ( $response === false ) { + if ($response === false) { return false; } @@ -81,7 +83,8 @@ public function create_wordpress_connection( $app_token, $migration_enabled, $pa * * @return string */ - protected function get_script( $name ) { - return (string) file_get_contents( WPA0_PLUGIN_DIR . 'lib/scripts-js/db-' . $name . '.js' ); + protected function get_script($name) + { + return (string) file_get_contents(WPA0_PLUGIN_DIR . 'lib/scripts-js/db-' . $name . '.js'); } } diff --git a/lib/WP_Auth0_DBManager.php b/lib/WP_Auth0_DBManager.php index 2b987c002..483823884 100644 --- a/lib/WP_Auth0_DBManager.php +++ b/lib/WP_Auth0_DBManager.php @@ -1,185 +1,188 @@ a0_options = $a0_options; } - public function install_db( $version_to_install = null ) { + public function install_db($version_to_install = null) + { - $current_ver = (int) get_option( 'auth0_db_version', 0 ); - if ( $current_ver === 0 ) { - $current_ver = (int) get_site_option( 'auth0_db_version', 0 ); + $current_ver = (int) get_option('auth0_db_version', 0); + if ($current_ver === 0) { + $current_ver = (int) get_site_option('auth0_db_version', 0); } - if ( empty( $current_ver ) || $current_ver === AUTH0_DB_VERSION ) { - update_option( 'auth0_db_version', AUTH0_DB_VERSION ); + if (empty($current_ver) || $current_ver === AUTH0_DB_VERSION) { + update_option('auth0_db_version', AUTH0_DB_VERSION); return; } - wp_cache_set( 'doing_db_update', true, WPA0_CACHE_GROUP ); + wp_cache_set('doing_db_update', true, WPA0_CACHE_GROUP); $options = $this->a0_options; // Plugin version < 3.4.0 - if ( $current_ver < 15 || 15 === $version_to_install ) { - $options->set( 'cdn_url', WPA0_LOCK_CDN_URL, false ); - $options->set( 'cache_expiration', 1440, false ); + if ($current_ver < 15 || 15 === $version_to_install) { + $options->set('cdn_url', WPA0_LOCK_CDN_URL, false); + $options->set('cache_expiration', 1440, false); // Update Client - if ( wp_auth0_is_ready() ) { - $options->set( 'client_signing_algorithm', 'HS256', false ); + if (wp_auth0_is_ready()) { + $options->set('client_signing_algorithm', 'HS256', false); } } // Plugin version < 3.5.0 - if ( $current_ver < 16 || 16 === $version_to_install ) { + if ($current_ver < 16 || 16 === $version_to_install) { // Update Lock and Auth versions - if ( '//cdn.auth0.com/js/lock/11.0.0/lock.min.js' === $options->get( 'cdn_url' ) ) { - $options->set( 'cdn_url', WPA0_LOCK_CDN_URL, false ); + if ('//cdn.auth0.com/js/lock/11.0.0/lock.min.js' === $options->get('cdn_url')) { + $options->set('cdn_url', WPA0_LOCK_CDN_URL, false); } } // Plugin version < 3.6.0 - if ( $current_ver < 18 || 18 === $version_to_install ) { + if ($current_ver < 18 || 18 === $version_to_install) { // Migrate passwordless_method - if ( $options->get( 'passwordless_enabled', false ) ) { - $pwl_method = $options->get( 'passwordless_method' ); - switch ( $pwl_method ) { + if ($options->get('passwordless_enabled', false)) { + $pwl_method = $options->get('passwordless_method'); + switch ($pwl_method) { - // SMS passwordless just needs 'sms' as a connection + // SMS passwordless just needs 'sms' as a connection case 'sms': - $options->set( 'lock_connections', 'sms', false ); + $options->set('lock_connections', 'sms', false); break; - // Social + SMS means there are existing social connections we want to keep + // Social + SMS means there are existing social connections we want to keep case 'socialOrSms': - $options->add_lock_connection( 'sms' ); + $options->add_lock_connection('sms'); break; - // Email link passwordless just needs 'email' as a connection + // Email link passwordless just needs 'email' as a connection case 'emailcode': case 'magiclink': - $options->set( 'lock_connections', 'email', false ); + $options->set('lock_connections', 'email', false); break; - // Social + Email means there are social connections be want to keep + // Social + Email means there are social connections be want to keep case 'socialOrMagiclink': case 'socialOrEmailcode': - $options->add_lock_connection( 'email' ); + $options->add_lock_connection('email'); break; } // Need to set a special passwordlessMethod flag if using email code - $lock_json = trim( $options->get( 'extra_conf' ) ); - $lock_json_decoded = ! empty( $lock_json ) ? json_decode( $lock_json, true ) : []; - $lock_json_decoded['passwordlessMethod'] = strpos( $pwl_method, 'code' ) ? 'code' : 'link'; - $options->set( 'extra_conf', json_encode( $lock_json_decoded ), false ); + $lock_json = trim($options->get('extra_conf')); + $lock_json_decoded = !empty($lock_json) ? json_decode($lock_json, true) : []; + $lock_json_decoded['passwordlessMethod'] = strpos($pwl_method, 'code') ? 'code' : 'link'; + $options->set('extra_conf', json_encode($lock_json_decoded), false); } - $options->remove( 'passwordless_method' ); + $options->remove('passwordless_method'); } // 3.9.0 - if ( $current_ver < 20 || 20 === $version_to_install ) { + if ($current_ver < 20 || 20 === $version_to_install) { // Remove default IP addresses from saved field. - $migration_ips = trim( $options->get( 'migration_ips' ) ); - if ( $migration_ips ) { - $migration_ips = array_map( 'trim', explode( ',', $migration_ips ) ); - $ip_check = new WP_Auth0_Ip_Check( $options ); - $default_ips = explode( ',', $ip_check->get_ips_by_domain() ); - $custom_ips = array_diff( $migration_ips, $default_ips ); - $options->set( 'migration_ips', implode( ',', $custom_ips ), false ); + $migration_ips = trim($options->get('migration_ips')); + if ($migration_ips) { + $migration_ips = array_map('trim', explode(',', $migration_ips)); + $ip_check = new WP_Auth0_Ip_Check($options); + $default_ips = explode(',', $ip_check->get_ips_by_domain()); + $custom_ips = array_diff($migration_ips, $default_ips); + $options->set('migration_ips', implode(',', $custom_ips), false); } } // 3.10.0 - if ( $current_ver < 21 || 21 === $version_to_install ) { + if ($current_ver < 21 || 21 === $version_to_install) { - if ( 'https://cdn.auth0.com/js/lock/11.5/lock.min.js' === $options->get( 'cdn_url' ) ) { - $options->set( 'cdn_url', WPA0_LOCK_CDN_URL, false ); - $options->set( 'custom_cdn_url', false, false ); + if ('https://cdn.auth0.com/js/lock/11.5/lock.min.js' === $options->get('cdn_url')) { + $options->set('cdn_url', WPA0_LOCK_CDN_URL, false); + $options->set('custom_cdn_url', false, false); } else { - $options->set( 'custom_cdn_url', true, false ); + $options->set('custom_cdn_url', true, false); } // Nullify and delete all removed options. - $options->remove( 'auth0js-cdn' ); - $options->remove( 'passwordless_cdn_url' ); - $options->remove( 'cdn_url_legacy' ); - - $options->remove( 'social_twitter_key' ); - $options->remove( 'social_twitter_secret' ); - $options->remove( 'social_facebook_key' ); - $options->remove( 'social_facebook_secret' ); - $options->remove( 'connections' ); - - $options->remove( 'chart_idp_type' ); - $options->remove( 'chart_gender_type' ); - $options->remove( 'chart_age_type' ); - $options->remove( 'chart_age_from' ); - $options->remove( 'chart_age_to' ); - $options->remove( 'chart_age_step' ); + $options->remove('auth0js-cdn'); + $options->remove('passwordless_cdn_url'); + $options->remove('cdn_url_legacy'); + + $options->remove('social_twitter_key'); + $options->remove('social_twitter_secret'); + $options->remove('social_facebook_key'); + $options->remove('social_facebook_secret'); + $options->remove('connections'); + + $options->remove('chart_idp_type'); + $options->remove('chart_gender_type'); + $options->remove('chart_age_type'); + $options->remove('chart_age_from'); + $options->remove('chart_age_to'); + $options->remove('chart_age_step'); // Migrate WLE setting - $new_wle_value = $options->get( 'wordpress_login_enabled' ) ? 'link' : 'isset'; - $options->set( 'wordpress_login_enabled', $new_wle_value, false ); - $options->set( 'wle_code', str_shuffle( uniqid() . uniqid() ), false ); + $new_wle_value = $options->get('wordpress_login_enabled') ? 'link' : 'isset'; + $options->set('wordpress_login_enabled', $new_wle_value, false); + $options->set('wle_code', str_shuffle(uniqid() . uniqid()), false); // Remove Client Grant update notifications. - delete_option( 'wp_auth0_client_grant_failed' ); - delete_option( 'wp_auth0_grant_types_failed' ); - delete_option( 'wp_auth0_client_grant_success' ); - delete_option( 'wp_auth0_grant_types_success' ); + delete_option('wp_auth0_client_grant_failed'); + delete_option('wp_auth0_grant_types_failed'); + delete_option('wp_auth0_client_grant_success'); + delete_option('wp_auth0_grant_types_success'); } // 3.11.0 - if ( $current_ver < 22 || 22 === $version_to_install ) { - $options->remove( 'social_big_buttons' ); + if ($current_ver < 22 || 22 === $version_to_install) { + $options->remove('social_big_buttons'); } // 4.0.0 - if ( $current_ver < 23 || 23 === $version_to_install ) { - $extra_conf = json_decode( $options->get( 'extra_conf' ), true ); - if ( empty( $extra_conf ) ) { + if ($current_ver < 23 || 23 === $version_to_install) { + $extra_conf = json_decode($options->get('extra_conf'), true); + if (empty($extra_conf)) { $extra_conf = []; } - $language = $options->get( 'language' ); - if ( $language ) { + $language = $options->get('language'); + if ($language) { $extra_conf['language'] = $language; } - $options->remove( 'language' ); + $options->remove('language'); - $language_dict = json_decode( $options->get( 'language_dictionary' ), true ); - if ( $language_dict ) { + $language_dict = json_decode($options->get('language_dictionary'), true); + if ($language_dict) { $extra_conf['languageDictionary'] = $language_dict; } - $options->remove( 'language_dictionary' ); + $options->remove('language_dictionary'); - if ( ! empty( $extra_conf ) ) { - $options->set( 'extra_conf', wp_json_encode( $extra_conf ) ); + if (!empty($extra_conf)) { + $options->set('extra_conf', wp_json_encode($extra_conf)); } - $options->remove( 'jwt_auth_integration' ); - $options->remove( 'link_auth0_users' ); - $options->remove( 'custom_css' ); - $options->remove( 'custom_js' ); - $options->remove( 'auth0_implicit_workflow' ); - $options->remove( 'client_secret_b64_encoded' ); - $options->remove( 'custom_signup_fields' ); - $options->remove( 'migration_token_id' ); + $options->remove('jwt_auth_integration'); + $options->remove('link_auth0_users'); + $options->remove('custom_css'); + $options->remove('custom_js'); + $options->remove('auth0_implicit_workflow'); + $options->remove('client_secret_b64_encoded'); + $options->remove('custom_signup_fields'); + $options->remove('migration_token_id'); } $options->update_all(); - update_option( 'auth0_db_version', AUTH0_DB_VERSION ); - wp_cache_set( 'doing_db_update', false, WPA0_CACHE_GROUP ); + update_option('auth0_db_version', AUTH0_DB_VERSION); + wp_cache_set('doing_db_update', false, WPA0_CACHE_GROUP); } } diff --git a/lib/WP_Auth0_Email_Verification.php b/lib/WP_Auth0_Email_Verification.php index 525ffc843..3f8ef97b2 100644 --- a/lib/WP_Auth0_Email_Verification.php +++ b/lib/WP_Auth0_Email_Verification.php @@ -1,4 +1,5 @@ user_id ) ? $userinfo->user_id : $userinfo->sub; + public static function render_die($userinfo) + { + $user_id = isset($userinfo->user_id) ? $userinfo->user_id : $userinfo->sub; - $html = sprintf( '

%s

', __( 'This site requires a verified email address.', 'wp-auth0' ) ); + $html = wp_kses(sprintf('

%s

', esc_html__('This site requires a verified email address.', 'wp-auth0')), ['p' => []]); // Only provide resend verification link for DB connection users. - if ( 0 === strpos( $user_id, 'auth0|' ) ) { - $html .= sprintf( + if (0 === strpos($user_id, 'auth0|')) { + $html .= wp_kses(sprintf( '

%s

%s

', - __( 'Resend verification email.', 'wp-auth0' ), + esc_html__('Resend verification email.', 'wp-auth0'), wp_login_url(), time(), - __( '← Login', 'wp-auth0' ), - esc_url( admin_url( 'admin-ajax.php' ) ), - esc_js( $user_id ), - esc_js( wp_create_nonce( self::RESEND_NONCE_ACTION ) ), - esc_js( __( 'Something went wrong; please login and try again.', 'wp-auth0' ) ), - esc_js( __( 'Email successfully re-sent to ', 'wp-auth0' ) . $userinfo->email ), + esc_html__('← Login', 'wp-auth0'), + esc_url(admin_url('admin-ajax.php')), + esc_js($user_id), + esc_js(wp_create_nonce(self::RESEND_NONCE_ACTION)), + esc_js(esc_html__('Something went wrong; please login and try again.', 'wp-auth0')), + esc_js(esc_html__('Email successfully re-sent to ', 'wp-auth0') . $userinfo->email), '//code.jquery.com/jquery-1.12.4.js', WPA0_PLUGIN_URL . 'assets/js/die-with-verify-email.js?ver=' . WPA0_VERSION - ); + ), ['p', 'a' => ['id' => true, 'href' => true], 'script' => ['src' => true]]); } - $html = apply_filters( 'auth0_verify_email_page', $html, $userinfo, '' ); - wp_die( $html ); + $html = apply_filters('auth0_verify_email_page', $html, $userinfo, ''); + + wp_die(wp_kses($html, ['p' => [], 'a' => ['id' => true, 'href' => true], 'script' => ['src' => true]])); } } diff --git a/lib/WP_Auth0_Embed_Widget.php b/lib/WP_Auth0_Embed_Widget.php index 06404a802..449424a62 100644 --- a/lib/WP_Auth0_Embed_Widget.php +++ b/lib/WP_Auth0_Embed_Widget.php @@ -1,78 +1,86 @@ getWidgetId(), $this->getWidgetName(), - [ 'description' => $this->getWidgetDescription() ] + ['description' => $this->getWidgetDescription()] ); } - protected function getWidgetId() { + protected function getWidgetId() + { return 'wp_auth0_widget'; } - protected function getWidgetName() { - return __( 'Auth0 Login', 'wp-auth0' ); + protected function getWidgetName() + { + return esc_html__('Auth0 Login', 'wp-auth0'); } - protected function getWidgetDescription() { - return __( 'Shows Auth0 login form in your sidebar', 'wp-auth0' ); + protected function getWidgetDescription() + { + return esc_html__('Shows Auth0 login form in your sidebar', 'wp-auth0'); } - protected function showAsModal() { + protected function showAsModal() + { return false; } - public function form( $instance ) { + public function form($instance) + { wp_enqueue_media(); - wp_enqueue_script( 'wpa0_admin' ); - wp_enqueue_style( 'media' ); + wp_enqueue_script('wpa0_admin'); + wp_enqueue_style('media'); require WPA0_PLUGIN_DIR . 'templates/a0-widget-setup-form.php'; return 'form'; } - public function widget( $args, $instance ) { + public function widget($args, $instance) + { - if ( wp_auth0_is_ready() ) { + if (wp_auth0_is_ready()) { $instance['show_as_modal'] = $this->showAsModal(); - $instance['modal_trigger_name'] = isset( $instance['modal_trigger_name'] ) + $instance['modal_trigger_name'] = isset($instance['modal_trigger_name']) ? $instance['modal_trigger_name'] - : __( 'Login', 'wp-auth0' ); + : esc_html__('Login', 'wp-auth0'); - if ( ! isset( $instance['redirect_to'] ) || empty( $instance['redirect_to'] ) ) { + if (!isset($instance['redirect_to']) || empty($instance['redirect_to'])) { // Null coalescing validates the input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - $instance['redirect_to'] = home_url( $_SERVER['REQUEST_URI'] ?? '' ); + $instance['redirect_to'] = home_url($_SERVER['REQUEST_URI'] ?? ''); } - echo $args['before_widget']; - \WP_Auth0_Lock::render( false, $instance ); - echo $args['after_widget']; - + echo wp_kses_post($args['before_widget']); + \WP_Auth0_Lock::render(false, $instance); + echo wp_kses_post($args['after_widget']); } else { - _e( 'Please check your Auth0 configuration', 'wp-auth0' ); + esc_html_e('Please check your Auth0 configuration', 'wp-auth0'); } } - public function update( $new_instance, $old_instance ) { - $new_instance['dict'] = trim( $new_instance['dict'] ); - if ( $new_instance['dict'] && json_decode( $new_instance['dict'] ) === null ) { + public function update($new_instance, $old_instance) + { + $new_instance['dict'] = trim($new_instance['dict']); + if ($new_instance['dict'] && json_decode($new_instance['dict']) === null) { $new_instance['dict'] = $old_instance['dict']; } - $new_instance['extra_conf'] = trim( $new_instance['extra_conf'] ); - if ( $new_instance['extra_conf'] && json_decode( $new_instance['extra_conf'] ) === null ) { + $new_instance['extra_conf'] = trim($new_instance['extra_conf']); + if ($new_instance['extra_conf'] && json_decode($new_instance['extra_conf']) === null) { $new_instance['extra_conf'] = $old_instance['extra_conf']; } - if ( ! empty( $new_instance['redirect_to'] ) ) { + if (!empty($new_instance['redirect_to'])) { $admin_advanced = new WP_Auth0_Admin_Advanced( WP_Auth0_Options::Instance(), - new WP_Auth0_Routes( WP_Auth0_Options::Instance() ) + new WP_Auth0_Routes(WP_Auth0_Options::Instance()) ); $new_instance['redirect_to'] = $admin_advanced->validate_login_redirect( diff --git a/lib/WP_Auth0_ErrorLog.php b/lib/WP_Auth0_ErrorLog.php index 51165d658..ec8d61318 100644 --- a/lib/WP_Auth0_ErrorLog.php +++ b/lib/WP_Auth0_ErrorLog.php @@ -1,4 +1,5 @@ get(); // Prepare the last error log entry to compare with the new one. $last_entry = null; - if ( ! empty( $log ) ) { + if (!empty($log)) { // Get the last error logged. $last_entry = $log[0]; // Remove date and count fields so it can be compared with the new error. - $last_entry = array_diff_key( $last_entry, array_flip( [ 'date', 'count' ] ) ); + $last_entry = array_diff_key($last_entry, array_flip(['date', 'count'])); } - if ( serialize( $last_entry ) === serialize( $new_entry ) ) { + if (serialize($last_entry) === serialize($new_entry)) { // New error and last error are the same so set the current time and increment the counter. $log[0]['date'] = time(); - $log[0]['count'] = isset( $log[0]['count'] ) ? intval( $log[0]['count'] ) + 1 : 2; + $log[0]['count'] = isset($log[0]['count']) ? intval($log[0]['count']) + 1 : 2; } else { // New error is not a repeat to set required fields. $new_entry['date'] = time(); $new_entry['count'] = 1; - array_unshift( $log, $new_entry ); + array_unshift($log, $new_entry); } - return $this->update( $log ); + return $this->update($log); } /** @@ -90,8 +95,9 @@ public function add( array $new_entry ) { * * @return bool */ - public function clear() { - return update_option( self::OPTION_NAME, [] ); + public function clear() + { + return update_option(self::OPTION_NAME, []); } /** @@ -99,8 +105,9 @@ public function clear() { * * @return bool */ - public function delete() { - return delete_option( self::OPTION_NAME ); + public function delete() + { + return delete_option(self::OPTION_NAME); } /** @@ -110,16 +117,18 @@ public function delete() { * * @return bool */ - private function update( array $log ) { - if ( count( $log ) > self::ERROR_LOG_ENTRY_LIMIT ) { - array_pop( $log ); + private function update(array $log) + { + if (count($log) > self::ERROR_LOG_ENTRY_LIMIT) { + array_pop($log); } - return update_option( self::OPTION_NAME, $log ); + return update_option(self::OPTION_NAME, $log); } - public static function check_is_disabled() { - $flag = wp_auth0_get_option( 'disable_logging' ); - if ( is_bool( $flag ) ) { + public static function check_is_disabled() + { + $flag = wp_auth0_get_option('disable_logging'); + if (is_bool($flag)) { return $flag; } return false; @@ -133,36 +142,37 @@ public static function check_is_disabled() { * * @return bool */ - public static function insert_error( $section, $error ) { + public static function insert_error($section, $error) + { - if ( self::check_is_disabled() ) { + if (self::check_is_disabled()) { return false; } $new_entry = [ 'section' => $section, 'code' => 'unknown_code', - 'message' => __( 'Unknown error message', 'wp-auth0' ), + 'message' => esc_html__('Unknown error message', 'wp-auth0'), ]; - if ( $error instanceof WP_Error ) { + if ($error instanceof WP_Error) { $new_entry['code'] = $error->get_error_code(); $new_entry['message'] = $error->get_error_message(); - } elseif ( $error instanceof Exception ) { + } elseif ($error instanceof Exception) { $new_entry['code'] = $error->getCode(); $new_entry['message'] = $error->getMessage(); - } elseif ( is_array( $error ) && ! empty( $error['response'] ) ) { - if ( ! empty( $error['response']['code'] ) ) { - $new_entry['code'] = sanitize_text_field( $error['response']['code'] ); + } elseif (is_array($error) && !empty($error['response'])) { + if (!empty($error['response']['code'])) { + $new_entry['code'] = sanitize_text_field($error['response']['code']); } - if ( ! empty( $error['response']['message'] ) ) { - $new_entry['message'] = sanitize_text_field( $error['response']['message'] ); + if (!empty($error['response']['message'])) { + $new_entry['message'] = sanitize_text_field($error['response']['message']); } } else { - $new_entry['message'] = is_object( $error ) || is_array( $error ) ? serialize( $error ) : $error; + $new_entry['message'] = is_object($error) || is_array($error) ? serialize($error) : $error; } - do_action( 'auth0_insert_error', $new_entry, $error, $section ); - return ( new self() )->add( $new_entry ); + do_action('auth0_insert_error', $new_entry, $error, $section); + return (new self())->add($new_entry); } } diff --git a/lib/WP_Auth0_Import_Settings.php b/lib/WP_Auth0_Import_Settings.php index 1536116d7..26fc490c6 100644 --- a/lib/WP_Auth0_Import_Settings.php +++ b/lib/WP_Auth0_Import_Settings.php @@ -1,6 +1,7 @@ a0_options = $a0_options; } - public function render_import_settings_page() { + public function render_import_settings_page() + { include WPA0_PLUGIN_DIR . 'templates/import_settings.php'; } - public function import_settings() { + public function import_settings() + { // Null coalescing validates input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - if ( ! wp_verify_nonce( wp_unslash( $_POST['_wpnonce'] ?? '' ), self::IMPORT_NONCE_ACTION ) ) { - wp_nonce_ays( self::IMPORT_NONCE_ACTION ); + if (!wp_verify_nonce(wp_unslash($_POST['_wpnonce'] ?? ''), self::IMPORT_NONCE_ACTION)) { + wp_nonce_ays(self::IMPORT_NONCE_ACTION); } - if ( ! current_user_can( 'manage_options' ) ) { - wp_die( __( 'Unauthorized.', 'wp-auth0' ) ); + if (!current_user_can('manage_options')) { + wp_die(esc_html__('Unauthorized.', 'wp-auth0')); } // Null coalescing validates input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - $settings_json = trim( stripslashes( $_POST['settings-json'] ?? '' ) ); - if ( empty( $settings_json ) ) { - wp_safe_redirect( $this->make_error_url( __( 'No settings JSON entered.', 'wp-auth0' ) ) ); + $settings_json = trim(stripslashes($_POST['settings-json'] ?? '')); + if (empty($settings_json)) { + wp_safe_redirect(esc_url($this->make_error_url(esc_html__('No settings JSON entered.', 'wp-auth0')))); exit; } - $settings = json_decode( $settings_json, true ); - if ( ! $settings || ! is_array( $settings ) ) { - wp_safe_redirect( $this->make_error_url( __( 'Settings JSON entered is not valid.', 'wp-auth0' ) ) ); + $settings = json_decode($settings_json, true); + if (!$settings || !is_array($settings)) { + wp_safe_redirect(esc_url($this->make_error_url(esc_html__('Settings JSON entered is not valid.', 'wp-auth0')))); exit; } // Keep original settings keys so we only save imported values. - $settings_keys = array_keys( $settings ); + $settings_keys = array_keys($settings); - $admin = new WP_Auth0_Admin( $this->a0_options, new WP_Auth0_Routes( $this->a0_options ) ); + $admin = new WP_Auth0_Admin($this->a0_options, new WP_Auth0_Routes($this->a0_options)); // Default setting values will be added to the array. - $settings_validated = $admin->input_validator( $settings ); + $settings_validated = $admin->input_validator($settings); - foreach ( $settings_keys as $settings_key ) { + foreach ($settings_keys as $settings_key) { // Invalid settings keys are removed in WP_Auth0_Admin::input_validator(). - if ( isset( $settings_validated[ $settings_key ] ) ) { - $this->a0_options->set( $settings_key, $settings_validated[ $settings_key ], false ); + if (isset($settings_validated[$settings_key])) { + $this->a0_options->set($settings_key, $settings_validated[$settings_key], false); } } $this->a0_options->update_all(); - wp_safe_redirect( admin_url( 'admin.php?page=wpa0' ) ); + wp_safe_redirect(admin_url('admin.php?page=wpa0')); exit; } /** * @codeCoverageIgnore */ - private function make_error_url( $error ) { - return admin_url( 'admin.php?page=wpa0-import-settings&error=' . rawurlencode( $error ) ); + private function make_error_url($error) + { + return admin_url('admin.php?page=wpa0-import-settings&error=' . rawurlencode($error)); } } diff --git a/lib/WP_Auth0_Ip_Check.php b/lib/WP_Auth0_Ip_Check.php index 8527baef7..b31c12f9f 100644 --- a/lib/WP_Auth0_Ip_Check.php +++ b/lib/WP_Auth0_Ip_Check.php @@ -1,4 +1,5 @@ a0_options = $a0_options; } @@ -107,12 +110,13 @@ public function __construct( WP_Auth0_Options $a0_options = null ) { * * @return string|array */ - public function get_ips_by_domain( $domain = null, $glue = self::IP_STRING_GLUE ) { - if ( empty( $domain ) ) { - $domain = $this->a0_options->get( 'domain' ); + public function get_ips_by_domain($domain = null, $glue = self::IP_STRING_GLUE) + { + if (empty($domain)) { + $domain = $this->a0_options->get('domain'); } - $region = wp_auth0_get_tenant_region( $domain ); - return $this->get_ip_by_region( $region, $glue ); + $region = wp_auth0_get_tenant_region($domain); + return $this->get_ip_by_region($region, $glue); } /** @@ -123,9 +127,10 @@ public function get_ips_by_domain( $domain = null, $glue = self::IP_STRING_GLUE * * @return string|array */ - public function get_ip_by_region( $region, $glue = self::IP_STRING_GLUE ) { - $ip_addresses = $this->valid_webtask_ips[ $region ]; - return is_null( $glue ) ? $ip_addresses : implode( $glue, $ip_addresses ); + public function get_ip_by_region($region, $glue = self::IP_STRING_GLUE) + { + $ip_addresses = $this->valid_webtask_ips[$region]; + return is_null($glue) ? $ip_addresses : implode($glue, $ip_addresses); } /** @@ -133,14 +138,15 @@ public function get_ip_by_region( $region, $glue = self::IP_STRING_GLUE ) { * * @return string */ - protected function get_request_ip() { - $valid_proxy_ip = $this->a0_options->get( 'valid_proxy_ip' ); + protected function get_request_ip() + { + $valid_proxy_ip = $this->a0_options->get('valid_proxy_ip'); // Null coalescing validates the input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated $remote_addr = $_SERVER['REMOTE_ADDR'] ?? null; - if ( $valid_proxy_ip && $remote_addr === $valid_proxy_ip ) { + if ($valid_proxy_ip && $remote_addr === $valid_proxy_ip) { // Null coalescing validates the input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated @@ -157,22 +163,23 @@ protected function get_request_ip() { * * @return array */ - protected function process_ip_list( $ip_list ) { - $raw = is_array( $ip_list ) ? $ip_list : explode( self::IP_STRING_GLUE, $ip_list ); + protected function process_ip_list($ip_list) + { + $raw = is_array($ip_list) ? $ip_list : explode(self::IP_STRING_GLUE, $ip_list); $ranges = []; - foreach ( $raw as $r ) { - $d = explode( '-', $r ); + foreach ($raw as $r) { + $d = explode('-', $r); - if ( count( $d ) < 2 ) { + if (count($d) < 2) { $ranges[] = [ - 'from' => trim( $d[0] ), - 'to' => trim( $d[0] ), + 'from' => trim($d[0]), + 'to' => trim($d[0]), ]; } else { $ranges[] = [ - 'from' => trim( $d[0] ), - 'to' => trim( $d[1] ), + 'from' => trim($d[0]), + 'to' => trim($d[1]), ]; } } @@ -186,14 +193,15 @@ protected function process_ip_list( $ip_list ) { * * @return bool */ - public function connection_is_valid( $valid_ips = '' ) { - $valid_ips = explode( self::IP_STRING_GLUE, $valid_ips ); - $default_ips = explode( self::IP_STRING_GLUE, $this->get_ips_by_domain() ); - $allowed_ips = array_merge( $valid_ips, $default_ips ); - $allowed_ips = array_unique( $allowed_ips ); - - foreach ( $this->process_ip_list( $allowed_ips ) as $range ) { - if ( $this->in_range( $this->get_request_ip(), $range ) ) { + public function connection_is_valid($valid_ips = '') + { + $valid_ips = explode(self::IP_STRING_GLUE, $valid_ips); + $default_ips = explode(self::IP_STRING_GLUE, $this->get_ips_by_domain()); + $allowed_ips = array_merge($valid_ips, $default_ips); + $allowed_ips = array_unique($allowed_ips); + + foreach ($this->process_ip_list($allowed_ips) as $range) { + if ($this->in_range($this->get_request_ip(), $range)) { return true; } } @@ -209,10 +217,11 @@ public function connection_is_valid( $valid_ips = '' ) { * * @return bool */ - private function in_range( $ip, array $range ) { - $from = ip2long( $range['from'] ); - $to = ip2long( $range['to'] ); - $ip = ip2long( $ip ); + private function in_range($ip, array $range) + { + $from = ip2long($range['from']); + $to = ip2long($range['to']); + $ip = ip2long($ip); return $ip >= $from && $ip <= $to; } diff --git a/lib/WP_Auth0_Lock.php b/lib/WP_Auth0_Lock.php index c55fe1aa3..dd1b0eced 100644 --- a/lib/WP_Auth0_Lock.php +++ b/lib/WP_Auth0_Lock.php @@ -1,6 +1,7 @@ wp_options = ! empty( $opts ) ? $opts : WP_Auth0_Options::Instance(); + public function __construct($extended_settings = [], $opts = null) + { + $this->wp_options = !empty($opts) ? $opts : WP_Auth0_Options::Instance(); $this->extended_settings = $extended_settings; } - public function get_state_obj( $redirect_to = null ) { + public function get_state_obj($redirect_to = null) + { // Nonce is not needed here as this is not processing form data. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $stateObj = [ - 'interim' => ( isset( $_GET['interim-login'] ) && $_GET['interim-login'] === 1 ), + 'interim' => (isset($_GET['interim-login']) && $_GET['interim-login'] === 1), 'nonce' => WP_Auth0_State_Handler::get_instance()->get_unique(), ]; - if ( ! empty( $redirect_to ) ) { - $stateObj['redirect_to'] = addslashes( $redirect_to ); - } elseif ( isset( $_GET['redirect_to'] ) ) { - $stateObj['redirect_to'] = addslashes( sanitize_text_field( wp_unslash( $_GET['redirect_to'] ) ) ); + if (!empty($redirect_to)) { + $stateObj['redirect_to'] = addslashes($redirect_to); + } elseif (isset($_GET['redirect_to'])) { + $stateObj['redirect_to'] = addslashes(sanitize_text_field(wp_unslash($_GET['redirect_to']))); } - return base64_encode( json_encode( $stateObj ) ); + return base64_encode(json_encode($stateObj)); // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification } - protected function _is_valid( $array, $key ) { - return isset( $array[ $key ] ) && trim( $array[ $key ] ) !== ''; + protected function _is_valid($array, $key) + { + return isset($array[$key]) && trim($array[$key]) !== ''; } - protected function build_settings( $settings ) { + protected function build_settings($settings) + { $options_obj = []; // Widget or shortcode languageDictionary. - if ( ! empty( $settings['dict'] ) ) { + if (!empty($settings['dict'])) { $options_obj['languageDictionary'] = $settings['dict']; } - if ( isset( $settings['form_title'] ) && trim( $settings['form_title'] ) !== '' ) { + if (isset($settings['form_title']) && trim($settings['form_title']) !== '') { - if ( ! isset( $options_obj['languageDictionary'] ) ) { + if (!isset($options_obj['languageDictionary'])) { $options_obj['languageDictionary'] = []; } @@ -62,95 +67,96 @@ protected function build_settings( $settings ) { $options_obj['socialButtonStyle'] = 'big'; - if ( isset( $settings['gravatar'] ) && '' !== $settings['gravatar'] && empty( $settings['gravatar'] ) ) { + if (isset($settings['gravatar']) && '' !== $settings['gravatar'] && empty($settings['gravatar'])) { $options_obj['avatar'] = null; } - if ( ! empty( $settings['gravatar'] ) ) { + if (!empty($settings['gravatar'])) { $options_obj['avatar'] = true; } - if ( $this->_is_valid( $settings, 'username_style' ) ) { + if ($this->_is_valid($settings, 'username_style')) { $options_obj['usernameStyle'] = $settings['username_style']; } - if ( $this->_is_valid( $settings, 'icon_url' ) || $this->_is_valid( $settings, 'primary_color' ) ) { + if ($this->_is_valid($settings, 'icon_url') || $this->_is_valid($settings, 'primary_color')) { $options_obj['theme'] = []; - if ( $this->_is_valid( $settings, 'icon_url' ) ) { + if ($this->_is_valid($settings, 'icon_url')) { $options_obj['theme']['logo'] = $settings['icon_url']; } - if ( $this->_is_valid( $settings, 'primary_color' ) ) { + if ($this->_is_valid($settings, 'primary_color')) { $options_obj['theme']['primaryColor'] = $settings['primary_color']; } } - if ( $this->_is_valid( $settings, 'lock_connections' ) ) { + if ($this->_is_valid($settings, 'lock_connections')) { $options_obj['allowedConnections'] = $this->wp_options->get_lock_connections(); } - if ( isset( $settings['extra_conf'] ) && trim( $settings['extra_conf'] ) !== '' ) { - $extra_conf_arr = json_decode( $settings['extra_conf'], true ); - $options_obj = array_merge_recursive( $extra_conf_arr, $options_obj ); + if (isset($settings['extra_conf']) && trim($settings['extra_conf']) !== '') { + $extra_conf_arr = json_decode($settings['extra_conf'], true); + $options_obj = array_merge_recursive($extra_conf_arr, $options_obj); } return $options_obj; } - public function get_lock_options() { + public function get_lock_options() + { $extended_settings = $this->extended_settings; - if ( isset( $extended_settings['show_as_modal'] ) ) { - unset( $extended_settings['show_as_modal'] ); + if (isset($extended_settings['show_as_modal'])) { + unset($extended_settings['show_as_modal']); } - if ( isset( $extended_settings['modal_trigger_name'] ) ) { - unset( $extended_settings['modal_trigger_name'] ); + if (isset($extended_settings['modal_trigger_name'])) { + unset($extended_settings['modal_trigger_name']); } $redirect_to = null; - if ( isset( $this->extended_settings['redirect_to'] ) ) { + if (isset($this->extended_settings['redirect_to'])) { $redirect_to = $this->extended_settings['redirect_to']; } $extraOptions = [ 'auth' => [ 'params' => [ - 'state' => $this->get_state_obj( $redirect_to ), - 'scope' => WP_Auth0_LoginManager::get_userinfo_scope( 'lock' ), + 'state' => $this->get_state_obj($redirect_to), + 'scope' => WP_Auth0_LoginManager::get_userinfo_scope('lock'), ], ], ]; $extraOptions['auth']['params']['nonce'] = WP_Auth0_Nonce_Handler::get_instance()->get_unique(); $extraOptions['auth']['responseType'] = 'code'; - $extraOptions['auth']['redirectUrl'] = $this->wp_options->get_wp_auth0_url( $this->get_callback_protocol() ); + $extraOptions['auth']['redirectUrl'] = $this->wp_options->get_wp_auth0_url($this->get_callback_protocol()); - if ( $this->wp_options->get( 'custom_domain' ) ) { + if ($this->wp_options->get('custom_domain')) { $extraOptions['configurationBaseUrl'] = sprintf( 'https://%s', - $this->wp_options->get( 'custom_domain' ) + $this->wp_options->get('custom_domain') ); } - $options_obj = $this->build_settings( $this->wp_options->get_options() ); - $extended_settings = $this->build_settings( $extended_settings ); + $options_obj = $this->build_settings($this->wp_options->get_options()); + $extended_settings = $this->build_settings($extended_settings); - $options_obj = array_replace_recursive( $extraOptions, $options_obj, $extended_settings ); + $options_obj = array_replace_recursive($extraOptions, $options_obj, $extended_settings); - if ( ! $this->wp_options->is_wp_registration_enabled() && ! isset( $options_obj['allowSignUp'] ) ) { + if (!$this->wp_options->is_wp_registration_enabled() && !isset($options_obj['allowSignUp'])) { $options_obj['allowSignUp'] = false; } - $show_as_modal = isset( $this->extended_settings['show_as_modal'] ) && $this->extended_settings['show_as_modal']; - if ( ! $show_as_modal ) { + $show_as_modal = isset($this->extended_settings['show_as_modal']) && $this->extended_settings['show_as_modal']; + if (!$show_as_modal) { $options_obj['container'] = WPA0_AUTH0_LOGIN_FORM_ID; } - if ( ! $this->wp_options->is_wp_registration_enabled() ) { + if (!$this->wp_options->is_wp_registration_enabled()) { $options_obj['disableSignupAction'] = true; } - if ( wp_auth0_is_current_login_action( [ 'register' ] ) ) { + if (wp_auth0_is_current_login_action(['register'])) { $options_obj['initialScreen'] = 'signUp'; } - return apply_filters( 'auth0_lock_options', $options_obj ); + return apply_filters('auth0_lock_options', $options_obj); } /** @@ -158,24 +164,26 @@ public function get_lock_options() { * * @return null|string - Returns 'https' if forced, null (use site default) if not. */ - private function get_callback_protocol() { - return $this->wp_options->get( 'force_https_callback' ) ? 'https' : null; + private function get_callback_protocol() + { + return $this->wp_options->get('force_https_callback') ? 'https' : null; } /** * Render a link at the bottom of a WordPress core login form back to Lock. */ - public static function render_back_to_lock() { - $title = wp_auth0_get_option( 'form_title' ); - if ( empty( $title ) ) { + public static function render_back_to_lock() + { + $title = wp_auth0_get_option('form_title'); + if (empty($title)) { $title = 'Auth0'; } - printf( + echo wp_kses(sprintf( '', // translators: The $title variable is the admin-controlled form title. - sanitize_text_field( sprintf( __( '← Back to %s login', 'wp-auth0' ), $title ) ) - ); + sanitize_text_field(sprintf(esc_html__('← Back to %s login', 'wp-auth0'), $title)) + ), ['div' => ['id' => true], 'a' => ['href' => true]]); } /** @@ -184,23 +192,24 @@ public static function render_back_to_lock() { * @param bool $canShowLegacyLogin - Is the legacy login form allowed? Only on wp-login.php. * @param array $specialSettings - Additional settings from widget or shortcode. */ - public static function render( $canShowLegacyLogin = true, $specialSettings = [] ) { - if ( is_user_logged_in() ) { + public static function render($canShowLegacyLogin = true, $specialSettings = []) + { + if (is_user_logged_in()) { return; } - if ( $canShowLegacyLogin && wp_auth0_can_show_wp_login_form() ) { - add_action( 'login_footer', [ 'WP_Auth0_Lock', 'render_back_to_lock' ] ); - add_action( 'woocommerce_after_customer_login_form', [ 'WP_Auth0_Lock', 'render_back_to_lock' ] ); + if ($canShowLegacyLogin && wp_auth0_can_show_wp_login_form()) { + add_action('login_footer', ['WP_Auth0_Lock', 'render_back_to_lock']); + add_action('woocommerce_after_customer_login_form', ['WP_Auth0_Lock', 'render_back_to_lock']); return; } $options = WP_Auth0_Options::Instance(); - $lock_options = new self( $specialSettings ); + $lock_options = new self($specialSettings); - wp_enqueue_script( 'wpa0_lock', $options->get_lock_url(), [ 'jquery' ], null, true ); - wp_enqueue_script( 'js-cookie', WPA0_PLUGIN_LIB_URL . 'js.cookie.min.js', [], '2.2.0', true ); - wp_enqueue_script( 'wpa0_lock_init', WPA0_PLUGIN_JS_URL . 'lock-init.js', [ 'jquery' ], WPA0_VERSION, true ); + wp_enqueue_script('wpa0_lock', $options->get_lock_url(), ['jquery'], WPA0_VERSION, true); + wp_enqueue_script('js-cookie', WPA0_PLUGIN_LIB_URL . 'js.cookie.min.js', [], '2.2.0', true); + wp_enqueue_script('wpa0_lock_init', WPA0_PLUGIN_JS_URL . 'lock-init.js', ['jquery'], WPA0_VERSION, true); wp_localize_script( 'wpa0_lock_init', @@ -209,24 +218,24 @@ public static function render( $canShowLegacyLogin = true, $specialSettings = [] 'settings' => $lock_options->get_lock_options(), 'ready' => wp_auth0_is_ready(), 'domain' => $options->get_auth_domain(), - 'clientId' => $options->get( 'client_id' ), + 'clientId' => $options->get('client_id'), 'stateCookieName' => WP_Auth0_State_Handler::get_storage_cookie_name(), 'nonceCookieName' => WP_Auth0_Nonce_Handler::get_storage_cookie_name(), - 'usePasswordless' => $options->get( 'passwordless_enabled' ), + 'usePasswordless' => $options->get('passwordless_enabled'), 'loginFormId' => WPA0_AUTH0_LOGIN_FORM_ID, - 'showAsModal' => ! empty( $specialSettings['show_as_modal'] ), + 'showAsModal' => !empty($specialSettings['show_as_modal']), 'i18n' => [ - 'notReadyText' => __( 'Auth0 is not configured', 'wp-auth0' ), - 'cannotFindNodeText' => __( 'Auth0 cannot find node with id ', 'wp-auth0' ), - 'modalButtonText' => ! empty( $specialSettings['modal_trigger_name'] ) - ? sanitize_text_field( $specialSettings['modal_trigger_name'] ) - : __( 'Login', 'wp-auth0' ), + 'notReadyText' => esc_html__('Auth0 is not configured', 'wp-auth0'), + 'cannotFindNodeText' => esc_html__('Auth0 cannot find node with id ', 'wp-auth0'), + 'modalButtonText' => !empty($specialSettings['modal_trigger_name']) + ? sanitize_text_field($specialSettings['modal_trigger_name']) + : esc_html__('Login', 'wp-auth0'), ], ] ); $login_tpl = WPA0_PLUGIN_DIR . 'templates/auth0-login-form.php'; - $login_tpl = apply_filters( 'auth0_login_form_tpl', $login_tpl, $lock_options, $canShowLegacyLogin ); + $login_tpl = apply_filters('auth0_login_form_tpl', $login_tpl, $lock_options, $canShowLegacyLogin); require $login_tpl; } } diff --git a/lib/WP_Auth0_LoginManager.php b/lib/WP_Auth0_LoginManager.php index edf34c1f2..fcc162f97 100755 --- a/lib/WP_Auth0_LoginManager.php +++ b/lib/WP_Auth0_LoginManager.php @@ -1,4 +1,5 @@ users_repo = $users_repo; $this->a0_options = $a0_options; } @@ -45,50 +48,51 @@ public function __construct( WP_Auth0_UsersRepo $users_repo, WP_Auth0_Options $a * * @return bool */ - public function login_auto() { + public function login_auto() + { // Not processing form data, just using a redirect parameter if present. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // Do not redirect anywhere if this is a logout action. - if ( wp_auth0_is_current_login_action( [ 'logout' ] ) ) { + if (wp_auth0_is_current_login_action(['logout'])) { return false; } // Do not redirect login page override. - if ( wp_auth0_can_show_wp_login_form() ) { + if (wp_auth0_can_show_wp_login_form()) { return false; } // If the user has a WP session, determine where they should end up and redirect. - if ( is_user_logged_in() ) { - if ( isset($_REQUEST['reauth']) && $_REQUEST['reauth']==1 ) { + if (is_user_logged_in()) { + if (isset($_REQUEST['reauth']) && $_REQUEST['reauth'] == 1) { // Skip the default login redirection as 'reauth' has been requsted } else { - $login_redirect = empty( $_REQUEST['redirect_to'] ) ? - $this->a0_options->get( 'default_login_redirection' ) : - filter_var( wp_unslash( $_REQUEST['redirect_to'] ), FILTER_SANITIZE_URL ); + $login_redirect = empty($_REQUEST['redirect_to']) ? + $this->a0_options->get('default_login_redirection') : + filter_var(wp_unslash($_REQUEST['redirect_to']), FILTER_SANITIZE_URL); // Add a cache buster to avoid an infinite redirect loop on pages that check for auth. - $login_redirect = add_query_arg( time(), '', $login_redirect ); - wp_safe_redirect( $login_redirect ); + $login_redirect = add_query_arg(time(), '', $login_redirect); + wp_safe_redirect($login_redirect); exit; } } // Do not use the ULP if the setting is off or if the plugin is not configured. - if ( ! $this->a0_options->get( 'auto_login', false ) ) { + if (!$this->a0_options->get('auto_login', false)) { return false; } - $connection = apply_filters( 'auth0_get_auto_login_connection', $this->a0_options->get( 'auto_login_method' ) ); - $auth_params = self::get_authorize_params( $connection ); + $connection = apply_filters('auth0_get_auto_login_connection', $this->a0_options->get('auto_login_method')); + $auth_params = self::get_authorize_params($connection); - WP_Auth0_State_Handler::get_instance()->set_cookie( $auth_params['state'] ); - WP_Auth0_Nonce_Handler::get_instance()->set_cookie( $auth_params['nonce'] ); + WP_Auth0_State_Handler::get_instance()->set_cookie($auth_params['state']); + WP_Auth0_Nonce_Handler::get_instance()->set_cookie($auth_params['nonce']); - $auth_url = self::build_authorize_url( $auth_params ); + $auth_url = self::build_authorize_url($auth_params); - wp_safe_redirect( $auth_url ); + wp_safe_redirect($auth_url); exit; // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification @@ -99,78 +103,79 @@ public function login_auto() { * Auth0 must be configured and 'auth0' URL parameter not empty. * Handles errors and state validation */ - public function init_auth0() { + public function init_auth0() + { // WP nonce is not needed here, nonce and state parameters provide replay and CSRF protection. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification - set_query_var( 'auth0_login_successful', false ); + set_query_var('auth0_login_successful', false); - $invitation = $this->query_vars( 'invitation' ); - $organization = $this->query_vars( 'organization' ); + $invitation = $this->query_vars('invitation'); + $organization = $this->query_vars('organization'); - if ( $invitation && $organization ) { - $connection = apply_filters( 'auth0_get_auto_login_connection', $this->a0_options->get( 'auto_login_method' ) ); - $auth_params = self::get_authorize_params( $connection ); + if ($invitation && $organization) { + $connection = apply_filters('auth0_get_auto_login_connection', $this->a0_options->get('auto_login_method')); + $auth_params = self::get_authorize_params($connection); - WP_Auth0_State_Handler::get_instance()->set_cookie( $auth_params['state'] ); - WP_Auth0_Nonce_Handler::get_instance()->set_cookie( $auth_params['nonce'] ); + WP_Auth0_State_Handler::get_instance()->set_cookie($auth_params['state']); + WP_Auth0_Nonce_Handler::get_instance()->set_cookie($auth_params['nonce']); $auth_params['invitation'] = $invitation; - $auth_url = self::build_authorize_url( $auth_params ); + $auth_url = self::build_authorize_url($auth_params); - wp_safe_redirect( $auth_url ); + wp_safe_redirect($auth_url); exit; } - $cb_type = $this->query_vars( 'auth0' ); + $cb_type = $this->query_vars('auth0'); // Not an Auth0 login process or settings are not configured to allow logins. - if ( ! $cb_type || ! wp_auth0_is_ready() ) { + if (!$cb_type || !wp_auth0_is_ready()) { return false; } // Catch any incoming errors and stop the login process. // See https://auth0.com/docs/libraries/error-messages for more info. - if ( ! empty( $_REQUEST['error'] ) || ! empty( $_REQUEST['error_description'] ) ) { + if (!empty($_REQUEST['error']) || !empty($_REQUEST['error_description'])) { // Input variable is sanitized. // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $error_msg = sanitize_text_field( rawurldecode( wp_unslash( $_REQUEST['error_description'] ) ) ); - $error_code = sanitize_text_field( rawurldecode( wp_unslash( $_REQUEST['error'] ) ) ); + $error_msg = sanitize_text_field(rawurldecode(wp_unslash($_REQUEST['error_description']))); + $error_code = sanitize_text_field(rawurldecode(wp_unslash($_REQUEST['error']))); // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $this->die_on_login( $error_msg, $error_code ); + $this->die_on_login($error_msg, $error_code); } // Check for valid state value returned from Auth0. // Null coalescing validates; value is checked in validate, not stored or output. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - $state = wp_unslash( $_GET['state'] ?? '' ); - if ( ! $state ) { - $this->die_on_login( __( 'Missing state', 'wp-auth0' ) ); + $state = wp_unslash($_GET['state'] ?? ''); + if (!$state) { + $this->die_on_login(esc_html__('Missing state', 'wp-auth0')); } - if ( ! WP_Auth0_State_Handler::get_instance()->validate( $state ) ) { - $this->die_on_login( __( 'Invalid state', 'wp-auth0' ) ); + if (!WP_Auth0_State_Handler::get_instance()->validate($state)) { + $this->die_on_login(esc_html__('Invalid state', 'wp-auth0')); } try { $this->redirect_login(); - } catch ( WP_Auth0_LoginFlowValidationException $e ) { + } catch (WP_Auth0_LoginFlowValidationException $e) { // Errors encountered during the OAuth login flow. - $this->die_on_login( $e->getMessage(), $e->getCode() ); - } catch ( WP_Auth0_BeforeLoginException $e ) { + $this->die_on_login($e->getMessage(), $e->getCode()); + } catch (WP_Auth0_BeforeLoginException $e) { // Errors encountered during the WordPress login flow. - $this->die_on_login( $e->getMessage(), $e->getCode() ); - } catch ( WP_Auth0_InvalidIdTokenException $e ) { + $this->die_on_login($e->getMessage(), $e->getCode()); + } catch (WP_Auth0_InvalidIdTokenException $e) { $code = 'invalid_id_token'; - $display_message = __( 'Invalid ID token', 'wp-auth0' ); + $display_message = esc_html__('Invalid ID token', 'wp-auth0'); WP_Auth0_ErrorLog::insert_error( __METHOD__ . ' L:' . __LINE__, - new WP_Error( $code, $display_message . ': ' . $e->getMessage() ) + new WP_Error($code, $display_message . ': ' . $e->getMessage()) ); - $this->die_on_login( $display_message, $code ); + $this->die_on_login($display_message, $code); } // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification @@ -185,55 +190,56 @@ public function init_auth0() { * * @link https://auth0.com/docs/api-auth/tutorials/authorization-code-grant */ - public function redirect_login() { + public function redirect_login() + { // Exchange authorization code for tokens. - $exchange_api = new WP_Auth0_Api_Exchange_Code( $this->a0_options, $this->a0_options->get_auth_domain() ); - $exchange_resp_body = $exchange_api->call( $this->query_vars( 'code' ) ); + $exchange_api = new WP_Auth0_Api_Exchange_Code($this->a0_options, $this->a0_options->get_auth_domain()); + $exchange_resp_body = $exchange_api->call($this->query_vars('code')); - if ( ! $exchange_resp_body ) { - throw new WP_Auth0_LoginFlowValidationException( __( 'Error exchanging code', 'wp-auth0' ) ); + if (!$exchange_resp_body) { + throw new WP_Auth0_LoginFlowValidationException(esc_html__('Error exchanging code', 'wp-auth0')); } - $data = json_decode( $exchange_resp_body ); + $data = json_decode($exchange_resp_body); - $access_token = isset( $data->access_token ) ? $data->access_token : null; + $access_token = isset($data->access_token) ? $data->access_token : null; $id_token = $data->id_token; - $refresh_token = isset( $data->refresh_token ) ? $data->refresh_token : null; + $refresh_token = isset($data->refresh_token) ? $data->refresh_token : null; // Decode the incoming ID token for the Auth0 user. - $decoded_token = $this->decode_id_token( $id_token ); + $decoded_token = $this->decode_id_token($id_token); // Attempt to authenticate with the Management API, if allowed. $userinfo = null; - if ( apply_filters( 'auth0_use_management_api_for_userinfo', true ) ) { - $cc_api = new WP_Auth0_Api_Client_Credentials( $this->a0_options ); - $get_user_api = new WP_Auth0_Api_Get_User( $this->a0_options, $cc_api ); - $get_user_resp = $get_user_api->call( $decoded_token->sub ); - $userinfo = ! empty( $get_user_resp ) ? json_decode( $get_user_resp ) : null; + if (apply_filters('auth0_use_management_api_for_userinfo', true)) { + $cc_api = new WP_Auth0_Api_Client_Credentials($this->a0_options); + $get_user_api = new WP_Auth0_Api_Get_User($this->a0_options, $cc_api); + $get_user_resp = $get_user_api->call($decoded_token->sub); + $userinfo = !empty($get_user_resp) ? json_decode($get_user_resp) : null; } // Management API call failed, fallback to ID token. - if ( ! $userinfo ) { - $userinfo = $this->clean_id_token( $decoded_token ); + if (!$userinfo) { + $userinfo = $this->clean_id_token($decoded_token); } // Populate sub property, if not provided. - if ( ! isset( $userinfo->sub ) ) { + if (!isset($userinfo->sub)) { $userinfo->sub = $userinfo->user_id; } - if ( $this->login_user( $userinfo, $id_token, $access_token, $refresh_token ) ) { + if ($this->login_user($userinfo, $id_token, $access_token, $refresh_token)) { $state_decoded = $this->get_state(); - if ( ! empty( $state_decoded->interim ) ) { + if (!empty($state_decoded->interim)) { include WPA0_PLUGIN_DIR . 'templates/login-interim.php'; } else { - if ( ! empty( $state_decoded->redirect_to ) && wp_login_url() !== $state_decoded->redirect_to ) { + if (!empty($state_decoded->redirect_to) && wp_login_url() !== $state_decoded->redirect_to) { $redirect_url = $state_decoded->redirect_to; } else { - $redirect_url = $this->a0_options->get( 'default_login_redirection' ); + $redirect_url = $this->a0_options->get('default_login_redirection'); } - wp_safe_redirect( $redirect_url ); + wp_safe_redirect($redirect_url); } exit(); } @@ -252,67 +258,68 @@ public function redirect_login() { * @throws WP_Auth0_LoginFlowValidationException - OAuth login flow errors. * @throws WP_Auth0_BeforeLoginException - Errors encountered during the auth0_before_login action. */ - public function login_user( $userinfo, $id_token = null, $access_token = null, $refresh_token = null ) { + public function login_user($userinfo, $id_token = null, $access_token = null, $refresh_token = null) + { $auth0_sub = $userinfo->sub; - list( $strategy ) = explode( '|', $auth0_sub ); + list($strategy) = explode('|', $auth0_sub); $user = null; // Check that the user has a verified email, if required. if ( // Admin settings enforce verified email. - $this->a0_options->get( 'requires_verified_email' ) && + $this->a0_options->get('requires_verified_email') && // Strategy for the user is not skipped. - ! $this->a0_options->strategy_skips_verified_email( $strategy ) + !$this->a0_options->strategy_skips_verified_email($strategy) ) { // Email address is empty so cannot proceed. - if ( empty( $userinfo->email ) ) { + if (empty($userinfo->email)) { throw new WP_Auth0_LoginFlowValidationException( - __( 'This account does not have an email associated, as required by your site administrator.', 'wp-auth0' ) + esc_html__('This account does not have an email associated, as required by your site administrator.', 'wp-auth0') ); } // Die with an action to re-send email verification. - if ( empty( $userinfo->email_verified ) ) { - WP_Auth0_Email_Verification::render_die( $userinfo ); + if (empty($userinfo->email_verified)) { + WP_Auth0_Email_Verification::render_die($userinfo); } } // See if there is a user linked to the same Auth0 user_id. - if ( isset( $userinfo->identities ) ) { - foreach ( $userinfo->identities as $identity ) { - $user = $this->users_repo->find_auth0_user( "{$identity->provider}|{$identity->user_id}" ); - if ( $user ) { + if (isset($userinfo->identities)) { + foreach ($userinfo->identities as $identity) { + $user = $this->users_repo->find_auth0_user("{$identity->provider}|{$identity->user_id}"); + if ($user) { break; } } } else { - $user = $this->users_repo->find_auth0_user( $auth0_sub ); + $user = $this->users_repo->find_auth0_user($auth0_sub); } - $user = apply_filters( 'auth0_get_wp_user', $user, $userinfo ); + $user = apply_filters('auth0_get_wp_user', $user, $userinfo); - if ( ! is_null( $user ) ) { + if (!is_null($user)) { // User exists so log them in. - if ( isset( $userinfo->email ) && $user->data->user_email !== $userinfo->email ) { + if (isset($userinfo->email) && $user->data->user_email !== $userinfo->email) { $description = $user->data->description; - if ( empty( $description ) ) { - if ( isset( $userinfo->headline ) ) { + if (empty($description)) { + if (isset($userinfo->headline)) { $description = $userinfo->headline; } - if ( isset( $userinfo->description ) ) { + if (isset($userinfo->description)) { $description = $userinfo->description; } - if ( isset( $userinfo->bio ) ) { + if (isset($userinfo->bio)) { $description = $userinfo->bio; } - if ( isset( $userinfo->about ) ) { + if (isset($userinfo->about)) { $description = $userinfo->about; } } // Temporarily disable the email sync, since the changes are coming from Auth0, no need to update them there. - remove_action( 'profile_update', 'wp_auth0_profile_change_email', 100 ); + remove_action('profile_update', 'wp_auth0_profile_change_email', 100); wp_update_user( (object) [ @@ -323,34 +330,34 @@ public function login_user( $userinfo, $id_token = null, $access_token = null, $ ); // Turn the email sync back on - add_action( 'profile_update', 'wp_auth0_profile_change_email', 100, 2 ); + add_action('profile_update', 'wp_auth0_profile_change_email', 100, 2); } - $this->users_repo->update_auth0_object( $user->data->ID, $userinfo ); - $user = apply_filters( 'auth0_get_wp_user', $user, $userinfo ); - $this->do_login( $user, $userinfo, false, $id_token, $access_token, $refresh_token ); + $this->users_repo->update_auth0_object($user->data->ID, $userinfo); + $user = apply_filters('auth0_get_wp_user', $user, $userinfo); + $this->do_login($user, $userinfo, false, $id_token, $access_token, $refresh_token); return true; } else { try { - $creator = new WP_Auth0_UsersRepo( $this->a0_options ); - $user_id = $creator->create( $userinfo, $id_token ); - $user = get_user_by( 'id', $user_id ); - $this->do_login( $user, $userinfo, true, $id_token, $access_token, $refresh_token ); - } catch ( WP_Auth0_CouldNotCreateUserException $e ) { + $creator = new WP_Auth0_UsersRepo($this->a0_options); + $user_id = $creator->create($userinfo, $id_token); + $user = get_user_by('id', $user_id); + $this->do_login($user, $userinfo, true, $id_token, $access_token, $refresh_token); + } catch (WP_Auth0_CouldNotCreateUserException $e) { - throw new WP_Auth0_LoginFlowValidationException( $e->getMessage() ); - } catch ( WP_Auth0_RegistrationNotEnabledException $e ) { + throw new WP_Auth0_LoginFlowValidationException(esc_html($e->getMessage())); + } catch (WP_Auth0_RegistrationNotEnabledException $e) { - $msg = __( + $msg = esc_html__( 'Could not create user. The registration process is not available. Please contact your site’s administrator.', 'wp-auth0' ); - throw new WP_Auth0_LoginFlowValidationException( $msg ); - } catch ( WP_Auth0_EmailNotVerifiedException $e ) { + throw new WP_Auth0_LoginFlowValidationException(esc_html($msg)); + } catch (WP_Auth0_EmailNotVerifiedException $e) { - WP_Auth0_Email_Verification::render_die( $e->userinfo ); + WP_Auth0_Email_Verification::render_die($e->userinfo); } return true; } @@ -368,16 +375,17 @@ public function login_user( $userinfo, $id_token = null, $access_token = null, $ * * @throws WP_Auth0_BeforeLoginException - Errors encountered during the auth0_before_login action. */ - private function do_login( $user, $userinfo, $is_new, $id_token, $access_token, $refresh_token ) { - $remember_users_session = $this->a0_options->get( 'remember_users_session' ); + private function do_login($user, $userinfo, $is_new, $id_token, $access_token, $refresh_token) + { + $remember_users_session = $this->a0_options->get('remember_users_session'); try { - do_action( 'auth0_before_login', $user, $userinfo ); - } catch ( Exception $e ) { - throw new WP_Auth0_BeforeLoginException( $e->getMessage() ); + do_action('auth0_before_login', $user, $userinfo); + } catch (Exception $e) { + throw new WP_Auth0_BeforeLoginException(esc_html($e->getMessage())); } - set_query_var( 'auth0_login_successful', true ); + set_query_var('auth0_login_successful', true); $secure_cookie = is_ssl(); @@ -392,9 +400,9 @@ private function do_login( $user, $userinfo, $is_new, $id_token, $access_token, ] ); - wp_set_auth_cookie( $user->ID, $remember_users_session, $secure_cookie ); - do_action( 'wp_login', $user->user_login, $user ); - do_action( 'auth0_user_login', $user->ID, $userinfo, $is_new, $id_token, $access_token, $refresh_token ); + wp_set_auth_cookie($user->ID, $remember_users_session, $secure_cookie); + do_action('wp_login', $user->user_login, $user); + do_action('auth0_user_login', $user->ID, $userinfo, $is_new, $id_token, $access_token, $refresh_token); } /** @@ -406,23 +414,24 @@ private function do_login( $user, $userinfo, $is_new, $id_token, $access_token, * * @link https://codex.wordpress.org/Plugin_API/Action_Reference/wp_logout */ - public function logout() { - if ( ! wp_auth0_is_ready() ) { + public function logout() + { + if (!wp_auth0_is_ready()) { return; } // If SLO is in use, redirect to Auth0 to logout there as well. - if ( $this->a0_options->get( 'singlelogout' ) ) { - $return_to = apply_filters( 'auth0_slo_return_to', home_url() ); - $redirect_url = $this->auth0_logout_url( $return_to ); - $redirect_url = apply_filters( 'auth0_logout_url', $redirect_url ); - wp_safe_redirect( $redirect_url ); + if ($this->a0_options->get('singlelogout')) { + $return_to = apply_filters('auth0_slo_return_to', home_url()); + $redirect_url = $this->auth0_logout_url($return_to); + $redirect_url = apply_filters('auth0_logout_url', $redirect_url); + wp_safe_redirect($redirect_url); exit; } // If auto-login is in use, cannot redirect back to login page. - if ( $this->a0_options->get( 'auto_login' ) ) { - wp_safe_redirect( home_url() ); + if ($this->a0_options->get('auto_login')) { + wp_safe_redirect(home_url()); exit; } } @@ -434,10 +443,11 @@ public function logout() { * * @return string */ - public static function get_userinfo_scope( $context = '' ) { - $default_scope = [ 'openid', 'email', 'profile' ]; - $filtered_scope = apply_filters( 'auth0_auth_scope', $default_scope, $context ); - return implode( ' ', $filtered_scope ); + public static function get_userinfo_scope($context = '') + { + $default_scope = ['openid', 'email', 'profile']; + $filtered_scope = apply_filters('auth0_auth_scope', $default_scope, $context); + return implode(' ', $filtered_scope); } /** @@ -448,27 +458,28 @@ public static function get_userinfo_scope( $context = '' ) { * * @return array */ - public static function get_authorize_params( $connection = null, $redirect_to = null ) { + public static function get_authorize_params($connection = null, $redirect_to = null) + { // Nonce is not needed here as this is not processing form data. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $opts = WP_Auth0_Options::Instance(); - $customParams = trim( $opts->get( 'auto_login_params' ) ?? '' ); + $customParams = trim($opts->get('auto_login_params') ?? ''); $params = []; - if ( $customParams ) { - parse_str( $customParams, $params ); + if ($customParams) { + parse_str($customParams, $params); } $params = array_merge( $params, [ 'connection' => $connection, - 'client_id' => $opts->get( 'client_id' ), - 'organization' => $opts->get( 'organization' ), - 'scope' => self::get_userinfo_scope( 'authorize_url' ), + 'client_id' => $opts->get('client_id'), + 'organization' => $opts->get('organization'), + 'scope' => self::get_userinfo_scope('authorize_url'), 'nonce' => WP_Auth0_Nonce_Handler::get_instance()->get_unique(), - 'max_age' => absint( apply_filters( 'auth0_jwt_max_age', null ) ), + 'max_age' => absint(apply_filters('auth0_jwt_max_age', null)), 'response_type' => 'code', 'response_mode' => 'query', 'redirect_uri' => $opts->get_wp_auth0_url(), @@ -476,26 +487,26 @@ public static function get_authorize_params( $connection = null, $redirect_to = ); // Where should the user be redirected after logging in? - if ( empty( $redirect_to ) ) { - $redirect_to = empty( $_GET['redirect_to'] ) - ? $opts->get( 'default_login_redirection' ) - : filter_var( wp_unslash( $_GET['redirect_to'] ), FILTER_SANITIZE_URL ); + if (empty($redirect_to)) { + $redirect_to = empty($_GET['redirect_to']) + ? $opts->get('default_login_redirection') + : filter_var(wp_unslash($_GET['redirect_to']), FILTER_SANITIZE_URL); } - $filtered_params = apply_filters( 'auth0_authorize_url_params', $params, $connection, $redirect_to ); + $filtered_params = apply_filters('auth0_authorize_url_params', $params, $connection, $redirect_to); // State parameter, checked during login callback. - if ( empty( $filtered_params['state'] ) ) { + if (empty($filtered_params['state'])) { $state = [ 'interim' => false, 'nonce' => WP_Auth0_State_Handler::get_instance()->get_unique(), 'redirect_to' => $redirect_to, ]; - $filtered_state = apply_filters( 'auth0_authorize_state', $state, $filtered_params ); - $filtered_params['state'] = base64_encode( json_encode( $filtered_state ) ); + $filtered_state = apply_filters('auth0_authorize_state', $state, $filtered_params); + $filtered_params['state'] = base64_encode(json_encode($filtered_state)); } - return array_filter( $filtered_params ); + return array_filter($filtered_params); // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification } @@ -507,10 +518,11 @@ public static function get_authorize_params( $connection = null, $redirect_to = * * @return string */ - public static function build_authorize_url( array $params = [] ) { + public static function build_authorize_url(array $params = []) + { $auth_url = 'https://' . WP_Auth0_Options::Instance()->get_auth_domain() . '/authorize'; - $auth_url = add_query_arg( array_map( 'rawurlencode', $params ), $auth_url ); - return apply_filters( 'auth0_authorize_url', $auth_url, $params ); + $auth_url = add_query_arg(array_map('rawurlencode', $params), $auth_url); + return apply_filters('auth0_authorize_url', $auth_url, $params); } /** @@ -527,19 +539,20 @@ public static function build_authorize_url( array $params = [] ) { * * @return string|null */ - protected function query_vars( $key ) { + protected function query_vars($key) + { // Neither nonce nor sanitization is needed here as this is not processing form data, just returning it. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized global $wp_query; - if ( isset( $wp_query->query_vars[ $key ] ) ) { - return $wp_query->query_vars[ $key ]; + if (isset($wp_query->query_vars[$key])) { + return $wp_query->query_vars[$key]; } - if ( isset( $_REQUEST[ $key ] ) ) { - return wp_unslash( $_REQUEST[ $key ] ); + if (isset($_REQUEST[$key])) { + return wp_unslash($_REQUEST[$key]); } return null; @@ -554,19 +567,20 @@ protected function query_vars( $key ) { * * @return string|object|null */ - protected function get_state() { + protected function get_state() + { // Neither nonce nor sanitization is needed here as this is not processing form data, just returning it. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - if ( ! isset( $_REQUEST['state'] ) ) { + if (!isset($_REQUEST['state'])) { return null; } - $state_val = wp_unslash( $_REQUEST['state'] ); - $state_val = rawurldecode( $state_val ); - $state_val = base64_decode( $state_val ); - $state_val = json_decode( $state_val ); + $state_val = wp_unslash($_REQUEST['state']); + $state_val = rawurldecode($state_val); + $state_val = base64_decode($state_val); + $state_val = json_decode($state_val); return $state_val; @@ -580,27 +594,29 @@ protected function get_state() { * @param string $msg - translated error message to display. * @param string|int $code - error code, if given. */ - protected function die_on_login( $msg = '', $code = 0 ) { + protected function die_on_login($msg = '', $code = 0) + { // Log the user out completely. wp_destroy_current_session(); wp_clear_auth_cookie(); - wp_set_current_user( 0 ); + wp_set_current_user(0); - $html = sprintf( + $html = wp_kses(sprintf( '%s: %s [%s: %s]

%s', - __( 'There was a problem with your log in', 'wp-auth0' ), - ! empty( $msg ) - ? sanitize_text_field( $msg ) - : __( 'Please see the site administrator', 'wp-auth0' ), - __( 'error code', 'wp-auth0' ), - $code ? sanitize_text_field( $code ) : __( 'unknown', 'wp-auth0' ), - $this->auth0_logout_url( wp_login_url() ), - __( '← Login', 'wp-auth0' ) - ); - - $html = apply_filters( 'auth0_die_on_login_output', $html, $msg, $code, false ); - wp_die( $html ); + esc_html__('There was a problem with your log in', 'wp-auth0'), + !empty($msg) + ? sanitize_text_field($msg) + : esc_html__('Please see the site administrator', 'wp-auth0'), + esc_html__('error code', 'wp-auth0'), + esc_html($code ? sanitize_text_field($code) : esc_html__('unknown', 'wp-auth0')), + $this->auth0_logout_url(wp_login_url()), + esc_html__('← Login', 'wp-auth0') + ), ['br' => [], 'a' => ['href' => []]]); + + $html = apply_filters('auth0_die_on_login_output', esc_html($html), esc_html($msg), esc_html($code), false); + + wp_die(wp_kses($html, ['br' => [], 'a' => ['href' => []]])); } /** @@ -608,26 +624,27 @@ protected function die_on_login( $msg = '', $code = 0 ) { * @return object * @throws WP_Auth0_InvalidIdTokenException */ - private function decode_id_token( $id_token ) { - $expectedIss = apply_filters( 'auth0_id_token_issuer', 'https://' . $this->a0_options->get_auth_domain() . '/' ); - $expectedAlg = $this->a0_options->get( 'client_signing_algorithm' ); - if ( 'RS256' === $expectedAlg ) { - $sigVerifier = new WP_Auth0_AsymmetricVerifier( new WP_Auth0_JwksFetcher() ); - } elseif ( 'HS256' === $expectedAlg ) { - $sigVerifier = new WP_Auth0_SymmetricVerifier( $this->a0_options->get( 'client_secret' ) ); + private function decode_id_token($id_token) + { + $expectedIss = apply_filters('auth0_id_token_issuer', 'https://' . $this->a0_options->get_auth_domain() . '/'); + $expectedAlg = $this->a0_options->get('client_signing_algorithm'); + if ('RS256' === $expectedAlg) { + $sigVerifier = new WP_Auth0_AsymmetricVerifier(new WP_Auth0_JwksFetcher()); + } elseif ('HS256' === $expectedAlg) { + $sigVerifier = new WP_Auth0_SymmetricVerifier($this->a0_options->get('client_secret')); } else { - throw new WP_Auth0_InvalidIdTokenException( 'Signing algorithm of "' . $expectedAlg . '" is not supported.' ); + throw new WP_Auth0_InvalidIdTokenException(esc_html('Signing algorithm of "' . $expectedAlg . '" is not supported.')); } $verifierOptions = [ 'nonce' => WP_Auth0_Nonce_Handler::get_instance()->get_once(), - 'leeway' => absint( apply_filters( 'auth0_jwt_leeway', null ) ), - 'max_age' => absint( apply_filters( 'auth0_jwt_max_age', null ) ), - 'org_id' => apply_filters( 'auth0_jwt_org_id', $this->a0_options->get_auth_organization() ), + 'leeway' => absint(apply_filters('auth0_jwt_leeway', null)), + 'max_age' => absint(apply_filters('auth0_jwt_max_age', null)), + 'org_id' => apply_filters('auth0_jwt_org_id', $this->a0_options->get_auth_organization()), ]; - $idTokenVerifier = new WP_Auth0_IdTokenVerifier( $expectedIss, $this->a0_options->get( 'client_id' ), $sigVerifier ); - return (object) $idTokenVerifier->verify( $id_token, $verifierOptions ); + $idTokenVerifier = new WP_Auth0_IdTokenVerifier($expectedIss, $this->a0_options->get('client_id'), $sigVerifier); + return (object) $idTokenVerifier->verify($id_token, $verifierOptions); } /** @@ -639,13 +656,14 @@ private function decode_id_token( $id_token ) { * * @codeCoverageIgnore - Private method */ - private function clean_id_token( $id_token_obj ) { - foreach ( [ 'iss', 'aud', 'iat', 'exp', 'nonce' ] as $attr ) { - unset( $id_token_obj->$attr ); + private function clean_id_token($id_token_obj) + { + foreach (['iss', 'aud', 'iat', 'exp', 'nonce'] as $attr) { + unset($id_token_obj->$attr); } - if ( ! isset( $id_token_obj->user_id ) && isset( $id_token_obj->sub ) ) { + if (!isset($id_token_obj->user_id) && isset($id_token_obj->sub)) { $id_token_obj->user_id = $id_token_obj->sub; - } elseif ( ! isset( $id_token_obj->sub ) && isset( $id_token_obj->user_id ) ) { + } elseif (!isset($id_token_obj->sub) && isset($id_token_obj->user_id)) { $id_token_obj->sub = $id_token_obj->user_id; } return $id_token_obj; @@ -660,12 +678,13 @@ private function clean_id_token( $id_token_obj ) { * * @codeCoverageIgnore - Private method */ - private function auth0_logout_url( $return_to = null ) { + private function auth0_logout_url($return_to = null) + { return sprintf( 'https://%s/v2/logout?client_id=%s&returnTo=%s', $this->a0_options->get_auth_domain(), - $this->a0_options->get( 'client_id' ), - rawurlencode( $return_to ?: home_url() ) + $this->a0_options->get('client_id'), + rawurlencode($return_to ?: home_url()) ); } } diff --git a/lib/WP_Auth0_Nonce_Handler.php b/lib/WP_Auth0_Nonce_Handler.php index 71ddbb0a0..78ae9f174 100644 --- a/lib/WP_Auth0_Nonce_Handler.php +++ b/lib/WP_Auth0_Nonce_Handler.php @@ -1,4 +1,5 @@ init(); } /** * Start-up process to make sure we have something stored. */ - protected function init() { + protected function init() + { // If a NONCE_COOKIE_NAME is not defined then we don't need to persist the nonce value. - if ( defined( static::NONCE_COOKIE_NAME ) && isset( $_COOKIE[ static::get_storage_cookie_name() ] ) ) { + if (defined(static::NONCE_COOKIE_NAME) && isset($_COOKIE[static::get_storage_cookie_name()])) { // Have a cookie, don't want to generate a new one. // TODO: validate whether we need to persist this value and sanitize if so. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - $this->unique = $_COOKIE[ static::get_storage_cookie_name() ]; + $this->unique = $_COOKIE[static::get_storage_cookie_name()]; } else { // No cookie, need to create one. $this->unique = $this->generate_unique(); @@ -75,8 +83,9 @@ protected function init() { * * @return WP_Auth0_State_Handler|WP_Auth0_Nonce_Handler */ - final public static function get_instance() { - if ( is_null( static::$_instance ) ) { + final public static function get_instance() + { + if (is_null(static::$_instance)) { static::$_instance = new static(); } return static::$_instance; @@ -87,7 +96,8 @@ final public static function get_instance() { * * @return string */ - public function get_unique() { + public function get_unique() + { return $this->unique; } @@ -96,7 +106,8 @@ public function get_unique() { * * @return integer */ - public function get_cookie_exp() { + public function get_cookie_exp() + { return time() + self::COOKIE_EXPIRES; } @@ -107,11 +118,12 @@ public function get_cookie_exp() { * * @return bool */ - public function set_cookie( $value = null ) { - if ( is_null( $value ) ) { + public function set_cookie($value = null) + { + if (is_null($value)) { $value = $this->unique; } - return $this->handle_cookie( static::get_storage_cookie_name(), $value, $this->get_cookie_exp() ); + return $this->handle_cookie(static::get_storage_cookie_name(), $value, $this->get_cookie_exp()); } /** @@ -121,9 +133,10 @@ public function set_cookie( $value = null ) { * * @return bool */ - public function validate( $value ) { + public function validate($value) + { $cookie_name = static::get_storage_cookie_name(); - $valid = isset( $_COOKIE[ $cookie_name ] ) ? $_COOKIE[ $cookie_name ] === $value : false; + $valid = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] === $value : false; $this->reset(); return $valid; } @@ -133,11 +146,12 @@ public function validate( $value ) { * * @return string|null */ - public function get_once() { + public function get_once() + { $cookie_name = static::get_storage_cookie_name(); // Null coalescing validates the input variable. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated - $value = $_COOKIE[ $cookie_name ] ?? null; + $value = $_COOKIE[$cookie_name] ?? null; $this->reset(); return $value; } @@ -147,8 +161,9 @@ public function get_once() { * * @return bool */ - public function reset() { - return $this->handle_cookie( static::get_storage_cookie_name(), '', 0 ); + public function reset() + { + return $this->handle_cookie(static::get_storage_cookie_name(), '', 0); } /** @@ -160,8 +175,9 @@ public function reset() { * * @return string */ - public function generate_unique( $bytes = 32 ) { - return bin2hex( random_bytes( $bytes ) ); + public function generate_unique($bytes = 32) + { + return bin2hex(random_bytes($bytes)); } /** @@ -173,21 +189,22 @@ public function generate_unique( $bytes = 32 ) { * * @return bool */ - protected function handle_cookie( $cookie_name, $cookie_value, $cookie_exp, $cookie_domain = null ) { + protected function handle_cookie($cookie_name, $cookie_value, $cookie_exp, $cookie_domain = null) + { $options = WP_Auth0_Options::Instance(); - $cookie_domain ??= $options->get( 'cookie_domain' ) ?? ''; + $cookie_domain ??= $options->get('cookie_domain') ?? ''; $cookie_domain = trim($cookie_domain); if ('' === $cookie_domain) { - $cookie_domain = trim($options->get( 'cookie_domain' ) ?? ''); + $cookie_domain = trim($options->get('cookie_domain') ?? ''); } - if ( $cookie_exp <= time() ) { - unset( $_COOKIE[ $cookie_name ] ); - return setcookie( $cookie_name, $cookie_value, 0, '/', $cookie_domain ?? '' ); + if ($cookie_exp <= time()) { + unset($_COOKIE[$cookie_name]); + return setcookie($cookie_name, $cookie_value, 0, '/', $cookie_domain ?? ''); } else { - $_COOKIE[ $cookie_name ] = $cookie_value; - return setcookie( $cookie_name, $cookie_value, $cookie_exp, '/', $cookie_domain ?? '', false, true ); + $_COOKIE[$cookie_name] = $cookie_value; + return setcookie($cookie_name, $cookie_value, $cookie_exp, '/', $cookie_domain ?? '', false, true); } } @@ -196,7 +213,8 @@ protected function handle_cookie( $cookie_name, $cookie_value, $cookie_exp, $coo * * @return string */ - public static function get_storage_cookie_name() { - return apply_filters( 'auth0_nonce_cookie_name', static::NONCE_COOKIE_NAME ); + public static function get_storage_cookie_name() + { + return apply_filters('auth0_nonce_cookie_name', static::NONCE_COOKIE_NAME); } } diff --git a/lib/WP_Auth0_Options.php b/lib/WP_Auth0_Options.php index 5154dbe7d..673b072ab 100755 --- a/lib/WP_Auth0_Options.php +++ b/lib/WP_Auth0_Options.php @@ -1,6 +1,7 @@ get_defaults( true ); - foreach ( $option_keys as $key ) { - $setting_const = $this->get_constant_name( $key ); - if ( defined( $setting_const ) ) { - $this->constant_opts[ $key ] = constant( $setting_const ); + public function __construct() + { + $option_keys = $this->get_defaults(true); + foreach ($option_keys as $key) { + $setting_const = $this->get_constant_name($key); + if (defined($setting_const)) { + $this->constant_opts[$key] = constant($setting_const); } } } @@ -45,8 +47,9 @@ public function __construct() { /** * @return WP_Auth0_Options */ - public static function Instance() { - if ( null === self::$_instance ) { + public static function Instance() + { + if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; @@ -59,10 +62,11 @@ public static function Instance() { * * @return string */ - public function get_constant_name( $key ) { + public function get_constant_name($key) + { // NOTE: the add_filter call must load before WP_Auth0::init() so it cannot be used in a theme. - $constant_prefix = apply_filters( 'auth0_settings_constant_prefix', 'AUTH0_ENV_' ); - return $constant_prefix . strtoupper( $key ); + $constant_prefix = apply_filters('auth0_settings_constant_prefix', 'AUTH0_ENV_'); + return $constant_prefix . strtoupper($key); } /** @@ -72,8 +76,9 @@ public function get_constant_name( $key ) { * * @return boolean */ - public function has_constant_val( $key ) { - return isset( $this->constant_opts[ $key ] ); + public function has_constant_val($key) + { + return isset($this->constant_opts[$key]); } /** @@ -83,8 +88,9 @@ public function has_constant_val( $key ) { * * @return string|null */ - public function get_constant_val( $key ) { - return $this->has_constant_val( $key ) ? constant( $this->get_constant_name( $key ) ) : null; + public function get_constant_val($key) + { + return $this->has_constant_val($key) ? constant($this->get_constant_name($key)) : null; } /** @@ -92,8 +98,9 @@ public function get_constant_val( $key ) { * * @return array */ - public function get_all_constant_keys() { - return array_keys( $this->constant_opts ); + public function get_all_constant_keys() + { + return array_keys($this->constant_opts); } /** @@ -101,7 +108,8 @@ public function get_all_constant_keys() { * * @return string */ - public function get_options_name() { + public function get_options_name() + { return $this->_options_name; } @@ -110,17 +118,18 @@ public function get_options_name() { * * @return array */ - public function get_options() { - if ( empty( $this->_opts ) ) { - $options = get_option( $this->_options_name, [] ); + public function get_options() + { + if (empty($this->_opts)) { + $options = get_option($this->_options_name, []); // Brand new install, no saved options so get all defaults. - if ( empty( $options ) || ! is_array( $options ) ) { + if (empty($options) || !is_array($options)) { $options = $this->defaults(); } // Check for constant overrides and replace. - if ( ! empty( $this->constant_opts ) ) { - $options = array_replace_recursive( $options, $this->constant_opts ); + if (!empty($this->constant_opts)) { + $options = array_replace_recursive($options, $this->constant_opts); } $this->_opts = $options; } @@ -137,10 +146,11 @@ public function get_options() { * * @link https://auth0.com/docs/cms/wordpress/extending#wp_auth0_get_option */ - public function get( $key, $default = null ) { + public function get($key, $default = null) + { $options = $this->get_options(); - $value = isset( $options[ $key ] ) ? $options[ $key ] : $default; - return apply_filters( 'wp_auth0_get_option', $value, $key ); + $value = isset($options[$key]) ? $options[$key] : $default; + return apply_filters('wp_auth0_get_option', $value, $key); } /** @@ -153,19 +163,20 @@ public function get( $key, $default = null ) { * * @return bool */ - public function set( $key, $value, $should_update = true ) { + public function set($key, $value, $should_update = true) + { // Cannot set a setting that is being overridden by a constant. - if ( $this->has_constant_val( $key ) ) { + if ($this->has_constant_val($key)) { return false; } $options = $this->get_options(); - $options[ $key ] = $value; + $options[$key] = $value; $this->_opts = $options; // No database update so process completed successfully. - if ( ! $should_update ) { + if (!$should_update) { return true; } @@ -177,15 +188,16 @@ public function set( $key, $value, $should_update = true ) { * * @param string $key - Option key name to remove. */ - public function remove( $key ) { + public function remove($key) + { // Cannot remove a setting that is being overridden by a constant. - if ( $this->has_constant_val( $key ) ) { + if ($this->has_constant_val($key)) { return; } $options = $this->get_options(); - unset( $options[ $key ] ); + unset($options[$key]); $this->_opts = $options; } @@ -194,19 +206,21 @@ public function remove( $key ) { * * @return bool */ - public function update_all() { + public function update_all() + { $options = $this->get_options(); - foreach ( $this->get_all_constant_keys() as $key ) { - unset( $options[ $key ] ); + foreach ($this->get_all_constant_keys() as $key) { + unset($options[$key]); } - return update_option( $this->_options_name, $options ); + return update_option($this->_options_name, $options); } /** * Save the options array for the first time. */ - public function save() { + public function save() + { $this->get_options(); $this->update_all(); } @@ -216,14 +230,16 @@ public function save() { * * @return bool */ - public function delete() { - return delete_option( $this->_options_name ); + public function delete() + { + return delete_option($this->_options_name); } /** * Reset options to defaults. */ - public function reset() { + public function reset() + { $this->_opts = null; $this->delete(); $this->save(); @@ -236,18 +252,21 @@ public function reset() { * * @return array */ - public function get_defaults( $keys_only = false ) { + public function get_defaults($keys_only = false) + { $default_opts = $this->defaults(); - return $keys_only ? array_keys( $default_opts ) : $default_opts; + return $keys_only ? array_keys($default_opts) : $default_opts; } - public function is_wp_registration_enabled() { - return is_multisite() ? users_can_register_signup_filter() : get_site_option( 'users_can_register' ); + public function is_wp_registration_enabled() + { + return is_multisite() ? users_can_register_signup_filter() : get_site_option('users_can_register'); } - public function get_default( $key ) { + public function get_default($key) + { $defaults = $this->defaults(); - return $defaults[ $key ]; + return $defaults[$key]; } /** @@ -255,20 +274,21 @@ public function get_default( $key ) { * * @return array */ - public function get_web_origins() { - $home_url_parsed = wp_parse_url( home_url() ); - $home_url_origin = ! empty( $home_url_parsed['path'] ) - ? str_replace( $home_url_parsed['path'], '', home_url() ) + public function get_web_origins() + { + $home_url_parsed = wp_parse_url(home_url()); + $home_url_origin = !empty($home_url_parsed['path']) + ? str_replace($home_url_parsed['path'], '', home_url()) : home_url(); - $site_url_parsed = wp_parse_url( site_url() ); - $site_url_origin = ! empty( $site_url_parsed['path'] ) - ? str_replace( $site_url_parsed['path'], '', site_url() ) + $site_url_parsed = wp_parse_url(site_url()); + $site_url_origin = !empty($site_url_parsed['path']) + ? str_replace($site_url_parsed['path'], '', site_url()) : site_url(); return $home_url_origin === $site_url_origin - ? [ $home_url_origin ] - : [ $home_url_origin, $site_url_origin ]; + ? [$home_url_origin] + : [$home_url_origin, $site_url_origin]; } /** @@ -278,12 +298,13 @@ public function get_web_origins() { * * @return string */ - public function get_wp_auth0_url( $protocol = null ) { - if ( is_null( $protocol ) && $this->get( 'force_https_callback' ) ) { + public function get_wp_auth0_url($protocol = null) + { + if (is_null($protocol) && $this->get('force_https_callback')) { $protocol = 'https'; } - $site_url = site_url( 'index.php', $protocol ); - return add_query_arg( 'auth0', 1, $site_url ); + $site_url = site_url('index.php', $protocol); + return add_query_arg('auth0', 1, $site_url); } /** @@ -291,9 +312,10 @@ public function get_wp_auth0_url( $protocol = null ) { * * @return string */ - public function get_lock_url() { - $cdn_url = $this->get( 'cdn_url' ); - return ( $cdn_url && $this->get( 'custom_cdn_url' ) ) ? $cdn_url : WPA0_LOCK_CDN_URL; + public function get_lock_url() + { + $cdn_url = $this->get('cdn_url'); + return ($cdn_url && $this->get('custom_cdn_url')) ? $cdn_url : WPA0_LOCK_CDN_URL; } /** @@ -301,10 +323,11 @@ public function get_lock_url() { * * @return string */ - public function get_auth_domain() { - $domain = $this->get( 'custom_domain' ); - if ( empty( $domain ) ) { - $domain = $this->get( 'domain' ); + public function get_auth_domain() + { + $domain = $this->get('custom_domain'); + if (empty($domain)) { + $domain = $this->get('domain'); } return $domain; } @@ -314,8 +337,9 @@ public function get_auth_domain() { * * @return string */ - public function get_auth_organization() { - return $this->get( 'organization', '' ); + public function get_auth_organization() + { + return $this->get('organization', ''); } /** @@ -323,10 +347,11 @@ public function get_auth_organization() { * * @return array */ - public function get_lock_connections() { - $connections = $this->get( 'lock_connections' ); - $connections = empty( $connections ) ? [] : explode( ',', $connections ); - return array_map( 'trim', $connections ); + public function get_lock_connections() + { + $connections = $this->get('lock_connections'); + $connections = empty($connections) ? [] : explode(',', $connections); + return array_map('trim', $connections); } /** @@ -334,14 +359,15 @@ public function get_lock_connections() { * * @param string $connection - connection name to add */ - public function add_lock_connection( $connection ) { + public function add_lock_connection($connection) + { $connections = $this->get_lock_connections(); // Add if it doesn't exist already - if ( ! array_key_exists( $connection, $connections ) ) { + if (!array_key_exists($connection, $connections)) { $connections[] = $connection; - $connections = implode( ',', $connections ); - $this->set( 'lock_connections', $connections ); + $connections = implode(',', $connections); + $this->set('lock_connections', $connections); } } @@ -355,17 +381,18 @@ public function add_lock_connection( $connection ) { * * @since 3.8.0 */ - public function strategy_skips_verified_email( $strategy ) { - $skip_strategies = trim( $this->get( 'skip_strategies' ) ); + public function strategy_skips_verified_email($strategy) + { + $skip_strategies = trim($this->get('skip_strategies')); // No strategies to skip. - if ( empty( $skip_strategies ) ) { + if (empty($skip_strategies)) { return false; } - $skip_strategies = explode( ',', $skip_strategies ); - $skip_strategies = array_map( 'trim', $skip_strategies ); - return in_array( $strategy, $skip_strategies ); + $skip_strategies = explode(',', $skip_strategies); + $skip_strategies = array_map('trim', $skip_strategies); + return in_array($strategy, $skip_strategies); } /** @@ -373,7 +400,8 @@ public function strategy_skips_verified_email( $strategy ) { * * @return array */ - protected function defaults() { + protected function defaults() + { return [ // System diff --git a/lib/WP_Auth0_Popup_Widget.php b/lib/WP_Auth0_Popup_Widget.php index 451fa4b80..ffa83d7fc 100644 --- a/lib/WP_Auth0_Popup_Widget.php +++ b/lib/WP_Auth0_Popup_Widget.php @@ -1,21 +1,25 @@ a0_options = $a0_options; - $this->ip_check = $ip_check instanceof WP_Auth0_Ip_Check ? $ip_check : new WP_Auth0_Ip_Check( $a0_options ); + $this->ip_check = $ip_check instanceof WP_Auth0_Ip_Check ? $ip_check : new WP_Auth0_Ip_Check($a0_options); } /** * Add rewrite tags and rules. */ - public function setup_rewrites() { - add_rewrite_tag( '%auth0%', '([^&]+)' ); - add_rewrite_tag( '%auth0fallback%', '([^&]+)' ); - add_rewrite_tag( '%code%', '([^&]+)' ); - add_rewrite_tag( '%state%', '([^&]+)' ); - add_rewrite_tag( '%auth0_error%', '([^&]+)' ); - add_rewrite_tag( '%a0_action%', '([^&]+)' ); - - add_rewrite_rule( '^\.well-known/oauth2-client-configuration', 'index.php?a0_action=oauth2-config', 'top' ); + public function setup_rewrites() + { + add_rewrite_tag('%auth0%', '([^&]+)'); + add_rewrite_tag('%auth0fallback%', '([^&]+)'); + add_rewrite_tag('%code%', '([^&]+)'); + add_rewrite_tag('%state%', '([^&]+)'); + add_rewrite_tag('%auth0_error%', '([^&]+)'); + add_rewrite_tag('%a0_action%', '([^&]+)'); + + add_rewrite_rule('^\.well-known/oauth2-client-configuration', 'index.php?a0_action=oauth2-config', 'top'); } /** @@ -60,32 +64,33 @@ public function setup_rewrites() { * * @return bool|string */ - public function custom_requests( $wp, $return = false ) { + public function custom_requests($wp, $return = false) + { $page = null; - if ( isset( $wp->query_vars['auth0fallback'] ) ) { + if (isset($wp->query_vars['auth0fallback'])) { $page = 'coo-fallback'; } - if ( isset( $wp->query_vars['a0_action'] ) ) { + if (isset($wp->query_vars['a0_action'])) { $page = $wp->query_vars['a0_action']; } - if ( null === $page && isset( $wp->query_vars['pagename'] ) ) { + if (null === $page && isset($wp->query_vars['pagename'])) { $page = $wp->query_vars['pagename']; } - if ( empty( $page ) ) { + if (empty($page)) { return false; } $json_header = true; - switch ( $page ) { + switch ($page) { case 'migration-ws-login': - $output = wp_json_encode( $this->migration_ws_login() ); + $output = wp_json_encode($this->migration_ws_login()); break; case 'migration-ws-get-user': - $output = wp_json_encode( $this->migration_ws_get_user() ); + $output = wp_json_encode($this->migration_ws_get_user()); break; case 'coo-fallback': $json_header = false; @@ -95,16 +100,16 @@ public function custom_requests( $wp, $return = false ) { return false; } - if ( $return ) { + if ($return) { return $output; } - if ( $json_header ) { - add_filter( 'wp_headers', [ $this, 'add_json_header' ] ); + if ($json_header) { + add_filter('wp_headers', [$this, 'add_json_header']); $wp->send_headers(); } - echo $output; + echo esc_js($output); exit; } @@ -115,48 +120,51 @@ public function custom_requests( $wp, $return = false ) { * * @return mixed */ - public function add_json_header( array $headers ) { - $headers['Content-Type'] = 'application/json; charset=' . get_bloginfo( 'charset' ); + public function add_json_header(array $headers) + { + $headers['Content-Type'] = 'application/json; charset=' . get_bloginfo('charset'); return $headers; } - protected function coo_fallback() { - $protocol = $this->a0_options->get( 'force_https_callback', false ) ? 'https' : null; + protected function coo_fallback() + { + $protocol = $this->a0_options->get('force_https_callback', false) ? 'https' : null; return sprintf( '', - esc_url( apply_filters( 'auth0_coo_auth0js_url', WPA0_AUTH0_JS_CDN_URL ) ), - esc_attr( $this->a0_options->get( 'client_id' ) ), - esc_attr( $this->a0_options->get_auth_domain() ), - esc_url( $this->a0_options->get_wp_auth0_url( $protocol ) ) + esc_url(apply_filters('auth0_coo_auth0js_url', WPA0_AUTH0_JS_CDN_URL)), + esc_attr($this->a0_options->get('client_id')), + esc_attr($this->a0_options->get_auth_domain()), + esc_url($this->a0_options->get_wp_auth0_url($protocol)) ); } - protected function getAuthorizationHeader() { + protected function getAuthorizationHeader() + { // Nonce is not needed here as this is an API endpoint. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $authorization = false; - if ( isset( $_POST['access_token'] ) ) { + if (isset($_POST['access_token'])) { // No need to sanitize, value is returned and checked. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $authorization = wp_unslash( $_POST['access_token'] ); - } elseif ( function_exists( 'getallheaders' ) ) { + $authorization = wp_unslash($_POST['access_token']); + } elseif (function_exists('getallheaders')) { $headers = getallheaders(); - if ( isset( $headers['Authorization'] ) ) { + if (isset($headers['Authorization'])) { $authorization = $headers['Authorization']; - } elseif ( isset( $headers['authorization'] ) ) { + } elseif (isset($headers['authorization'])) { $authorization = $headers['authorization']; } - } elseif ( isset( $_SERVER['Authorization'] ) ) { + } elseif (isset($_SERVER['Authorization'])) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $authorization = wp_unslash( $_SERVER['Authorization'] ); - } elseif ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { + $authorization = wp_unslash($_SERVER['Authorization']); + } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $authorization = wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ); + $authorization = wp_unslash($_SERVER['HTTP_AUTHORIZATION']); } return $authorization; @@ -171,31 +179,31 @@ protected function getAuthorizationHeader() { * * @see lib/scripts-js/db-login.js */ - protected function migration_ws_login() { + protected function migration_ws_login() + { // Nonce is not needed here as this is an API endpoint. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $code = $this->check_endpoint_access_error(); - if ( $code ) { - return $this->error_return_array( $code ); + if ($code) { + return $this->error_return_array($code); } try { - $this->check_endpoint_request( true ); + $this->check_endpoint_request(true); // Input is sanitized by core wp_authenticate function. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - $user = wp_authenticate( $_POST['username'], $_POST['password'] ); + $user = wp_authenticate($_POST['username'], $_POST['password']); - if ( is_wp_error( $user ) ) { - throw new Exception( __( 'Invalid credentials', 'wp-auth0' ), 401 ); + if (is_wp_error($user)) { + throw new Exception(esc_html__('Invalid credentials', 'wp-auth0'), 401); } - unset( $user->data->user_pass ); - return apply_filters( 'auth0_migration_ws_authenticated', $user ); - - } catch ( Exception $e ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $e ); + unset($user->data->user_pass); + return apply_filters('auth0_migration_ws_authenticated', $user); + } catch (Exception $e) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $e); return [ 'status' => $e->getCode() ?: 400, 'error' => $e->getMessage(), @@ -213,13 +221,14 @@ protected function migration_ws_login() { * * @see lib/scripts-js/db-get-user.js */ - protected function migration_ws_get_user() { + protected function migration_ws_get_user() + { // Nonce is not needed here as this is an API endpoint. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $code = $this->check_endpoint_access_error(); - if ( $code ) { - return $this->error_return_array( $code ); + if ($code) { + return $this->error_return_array($code); } try { @@ -227,25 +236,24 @@ protected function migration_ws_get_user() { // Input is sanitized by core get_user_by function. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - $user = get_user_by( 'email', $_POST['username'] ); + $user = get_user_by('email', $_POST['username']); - if ( ! $user ) { - throw new Exception( __( 'User not found', 'wp-auth0' ), 401 ); + if (!$user) { + throw new Exception(esc_html__('User not found', 'wp-auth0'), 401); } - $updated_email = WP_Auth0_UsersRepo::get_meta( $user->ID, WP_Auth0_Profile_Change_Email::UPDATED_EMAIL ); - if ( $updated_email === $user->data->user_email ) { + $updated_email = WP_Auth0_UsersRepo::get_meta($user->ID, WP_Auth0_Profile_Change_Email::UPDATED_EMAIL); + if ($updated_email === $user->data->user_email) { return [ 'status' => 200, 'error' => 'Email update in process', ]; } - unset( $user->data->user_pass ); - return apply_filters( 'auth0_migration_ws_authenticated', $user ); - - } catch ( Exception $e ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, $e ); + unset($user->data->user_pass); + return apply_filters('auth0_migration_ws_authenticated', $user); + } catch (Exception $e) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, $e); return [ 'status' => $e->getCode() ?: 400, 'error' => $e->getMessage(), @@ -260,17 +268,18 @@ protected function migration_ws_get_user() { * * @return int */ - private function check_endpoint_access_error() { + private function check_endpoint_access_error() + { // Migration web service is not turned on. - if ( ! $this->a0_options->get( 'migration_ws' ) ) { + if (!$this->a0_options->get('migration_ws')) { return 403; } // IP filtering is on and incoming IP address does not match filter. - if ( $this->a0_options->get( 'migration_ips_filter' ) ) { - $allowed_ips = $this->a0_options->get( 'migration_ips' ); - if ( ! $this->ip_check->connection_is_valid( $allowed_ips ) ) { + if ($this->a0_options->get('migration_ips_filter')) { + $allowed_ips = $this->a0_options->get('migration_ips'); + if (!$this->ip_check->connection_is_valid($allowed_ips)) { return 401; } } @@ -285,27 +294,28 @@ private function check_endpoint_access_error() { * * @throws Exception */ - private function check_endpoint_request( $require_password = false ) { + private function check_endpoint_request($require_password = false) + { // Nonce is not needed here as this is an API endpoint. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification $authorization = $this->getAuthorizationHeader(); - $authorization = trim( str_replace( 'Bearer ', '', $authorization ) ); + $authorization = trim(str_replace('Bearer ', '', $authorization)); - if ( empty( $authorization ) ) { - throw new Exception( __( 'Unauthorized: missing authorization header', 'wp-auth0' ), 401 ); + if (empty($authorization)) { + throw new Exception(esc_html__('Unauthorized: missing authorization header', 'wp-auth0'), 401); } - if ( $authorization !== $this->a0_options->get( 'migration_token' ) ) { - throw new Exception( __( 'Invalid token', 'wp-auth0' ), 401 ); + if ($authorization !== $this->a0_options->get('migration_token')) { + throw new Exception(esc_html__('Invalid token', 'wp-auth0'), 401); } - if ( empty( $_POST['username'] ) ) { - throw new Exception( __( 'Username is required', 'wp-auth0' ) ); + if (empty($_POST['username'])) { + throw new Exception(esc_html__('Username is required', 'wp-auth0')); } - if ( $require_password && empty( $_POST['password'] ) ) { - throw new Exception( __( 'Password is required', 'wp-auth0' ) ); + if ($require_password && empty($_POST['password'])) { + throw new Exception(esc_html__('Password is required', 'wp-auth0')); } // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification @@ -318,19 +328,20 @@ private function check_endpoint_request( $require_password = false ) { * * @return array */ - private function error_return_array( $code ) { + private function error_return_array($code) + { - switch ( $code ) { + switch ($code) { case 401: return [ 'status' => 401, - 'error' => __( 'Unauthorized', 'wp-auth0' ), + 'error' => esc_html__('Unauthorized', 'wp-auth0'), ]; default: return [ 'status' => 403, - 'error' => __( 'Forbidden', 'wp-auth0' ), + 'error' => esc_html__('Forbidden', 'wp-auth0'), ]; } } diff --git a/lib/WP_Auth0_Serializer.php b/lib/WP_Auth0_Serializer.php index f227b84a4..40bf81bbc 100644 --- a/lib/WP_Auth0_Serializer.php +++ b/lib/WP_Auth0_Serializer.php @@ -1,20 +1,22 @@ email ) ) { + if (isset($userinfo->email)) { $email = $userinfo->email; } - if ( empty( $email ) ) { + if (empty($email)) { $email = 'change_this_email@' . uniqid() . '.com'; } - $valid_user = apply_filters( 'wpa0_should_create_user', true, $userinfo ); - if ( ! $valid_user ) { + $valid_user = apply_filters('wpa0_should_create_user', true, $userinfo); + if (!$valid_user) { return -2; } @@ -28,47 +30,47 @@ public static function create_user( $userinfo ) { $firstname = ''; $lastname = ''; - if ( isset( $userinfo->name ) ) { + if (isset($userinfo->name)) { // Split the name into first- and lastname - $names = explode( ' ', $userinfo->name ); + $names = explode(' ', $userinfo->name); - if ( count( $names ) == 1 ) { + if (count($names) == 1) { $firstname = $userinfo->name; - } elseif ( count( $names ) == 2 ) { + } elseif (count($names) == 2) { $firstname = $names[0]; $lastname = $names[1]; } else { - $lastname = array_pop( $names ); - $firstname = implode( ' ', $names ); + $lastname = array_pop($names); + $firstname = implode(' ', $names); } } $username = ''; - if ( isset( $userinfo->username ) ) { + if (isset($userinfo->username)) { $username = $userinfo->username; - } elseif ( isset( $userinfo->nickname ) ) { + } elseif (isset($userinfo->nickname)) { $username = $userinfo->nickname; } - if ( empty( $username ) ) { + if (empty($username)) { $username = $email; } - while ( username_exists( $username ) ) { - $username = $username . rand( 0, 9 ); + while (username_exists($username)) { + $username = $username . rand(0, 9); } $description = ''; - if ( empty( $description ) ) { - if ( isset( $userinfo->headline ) ) { + if (empty($description)) { + if (isset($userinfo->headline)) { $description = $userinfo->headline; } - if ( isset( $userinfo->description ) ) { + if (isset($userinfo->description)) { $description = $userinfo->description; } - if ( isset( $userinfo->bio ) ) { + if (isset($userinfo->bio)) { $description = $userinfo->bio; } - if ( isset( $userinfo->about ) ) { + if (isset($userinfo->about)) { $description = $userinfo->about; } } @@ -83,16 +85,16 @@ public static function create_user( $userinfo ) { 'description' => $description, ]; - $user_data = apply_filters( 'auth0_create_user_data', $user_data, $userinfo ); + $user_data = apply_filters('auth0_create_user_data', $user_data, $userinfo); // Update the user - $user_id = wp_insert_user( $user_data ); + $user_id = wp_insert_user($user_data); - if ( ! is_numeric( $user_id ) ) { + if (!is_numeric($user_id)) { return $user_id; } - do_action( 'wpa0_user_created', $user_id, $email, $password, $firstname, $lastname ); + do_action('wpa0_user_created', $user_id, $email, $password, $firstname, $lastname); // Return the user ID return $user_id; @@ -105,11 +107,12 @@ public static function create_user( $userinfo ) { * * @return string */ - public static function get_strategy( $auth0_id ) { - if ( false === strpos( $auth0_id, '|' ) ) { + public static function get_strategy($auth0_id) + { + if (false === strpos($auth0_id, '|')) { return ''; } - $auth0_id_parts = explode( '|', $auth0_id ); + $auth0_id_parts = explode('|', $auth0_id); return $auth0_id_parts[0]; } } diff --git a/lib/WP_Auth0_UsersRepo.php b/lib/WP_Auth0_UsersRepo.php index fecb7483f..84daa987b 100644 --- a/lib/WP_Auth0_UsersRepo.php +++ b/lib/WP_Auth0_UsersRepo.php @@ -1,4 +1,5 @@ a0_options = $a0_options; } @@ -40,18 +43,19 @@ public function __construct( WP_Auth0_Options $a0_options ) { * @throws WP_Auth0_EmailNotVerifiedException - When a users's email is not verified but the site requires it. * @throws WP_Auth0_RegistrationNotEnabledException - When registration is not turned on for this site. */ - public function create( $userinfo, $token ) { + public function create($userinfo, $token) + { $auth0_sub = $userinfo->sub; - list($strategy) = explode( '|', $auth0_sub ); + list($strategy) = explode('|', $auth0_sub); $wp_user = null; $user_id = null; // Check legacy identities profile object for a DB connection. $is_db_connection = 'auth0' === $strategy; - if ( ! $is_db_connection && ! empty( $userinfo->identities ) ) { - foreach ( $userinfo->identities as $identity ) { - if ( 'auth0' === $identity->provider ) { + if (!$is_db_connection && !empty($userinfo->identities)) { + foreach ($userinfo->identities as $identity) { + if ('auth0' === $identity->provider) { $is_db_connection = true; break; } @@ -59,39 +63,39 @@ public function create( $userinfo, $token ) { } // Email is considered verified if flagged as such, if we ignore the requirement, or if the strategy is skipped. - $email_verified = ! empty( $userinfo->email_verified ) - || $this->a0_options->strategy_skips_verified_email( $strategy ); + $email_verified = !empty($userinfo->email_verified) + || $this->a0_options->strategy_skips_verified_email($strategy); // WP user to join with incoming Auth0 user. - if ( ! empty( $userinfo->email ) ) { - $wp_user = get_user_by( 'email', $userinfo->email ); + if (!empty($userinfo->email)) { + $wp_user = get_user_by('email', $userinfo->email); } - if ( is_object( $wp_user ) && $wp_user instanceof WP_User ) { + if (is_object($wp_user) && $wp_user instanceof WP_User) { // WP user exists, check if we can join. $user_id = $wp_user->ID; // Cannot join a DB connection user without a verified email. - if ( $is_db_connection && ! $email_verified ) { - throw new WP_Auth0_EmailNotVerifiedException( $userinfo, $token ); + if ($is_db_connection && !$email_verified) { + throw new WP_Auth0_EmailNotVerifiedException(esc_html($userinfo), esc_html($token)); } // If the user has a different Auth0 ID, we cannot join it. - $current_auth0_id = self::get_meta( $user_id, 'auth0_id' ); - if ( ! empty( $current_auth0_id ) && $auth0_sub !== $current_auth0_id ) { - throw new WP_Auth0_CouldNotCreateUserException( __( 'There is a user with the same email.', 'wp-auth0' ) ); + $current_auth0_id = self::get_meta($user_id, 'auth0_id'); + if (!empty($current_auth0_id) && $auth0_sub !== $current_auth0_id) { + throw new WP_Auth0_CouldNotCreateUserException(esc_html__('There is a user with the same email.', 'wp-auth0')); } - } elseif ( $this->a0_options->is_wp_registration_enabled() || $this->a0_options->get( 'auto_provisioning' ) ) { + } elseif ($this->a0_options->is_wp_registration_enabled() || $this->a0_options->get('auto_provisioning')) { // WP user does not exist and registration is allowed. - $user_id = WP_Auth0_Users::create_user( $userinfo ); + $user_id = WP_Auth0_Users::create_user($userinfo); // Check if user was created. - if ( is_wp_error( $user_id ) ) { - throw new WP_Auth0_CouldNotCreateUserException( $user_id->get_error_message() ); - } elseif ( -2 === $user_id ) { + if (is_wp_error($user_id)) { + throw new WP_Auth0_CouldNotCreateUserException(esc_html($user_id->get_error_message())); + } elseif (-2 === $user_id) { // Registration rejected by wpa0_should_create_user filter in WP_Auth0_Users::create_user(). - throw new WP_Auth0_CouldNotCreateUserException( __( 'Registration rejected.', 'wp-auth0' ) ); - } elseif ( $user_id < 0 ) { + throw new WP_Auth0_CouldNotCreateUserException(esc_html__('Registration rejected.', 'wp-auth0')); + } elseif ($user_id < 0) { // Registration failed for another reason. throw new WP_Auth0_CouldNotCreateUserException(); } @@ -100,7 +104,7 @@ public function create( $userinfo, $token ) { throw new WP_Auth0_RegistrationNotEnabledException(); } - $this->update_auth0_object( $user_id, $userinfo ); + $this->update_auth0_object($user_id, $userinfo); return $user_id; } @@ -111,11 +115,12 @@ public function create( $userinfo, $token ) { * * @return null|WP_User */ - public function find_auth0_user( $id ) { + public function find_auth0_user($id) + { global $wpdb; - if ( empty( $id ) ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__, __( 'Empty user id', 'wp-auth0' ) ); + if (empty($id)) { + WP_Auth0_ErrorLog::insert_error(__METHOD__, esc_html__('Empty user id', 'wp-auth0')); return null; } @@ -127,8 +132,8 @@ public function find_auth0_user( $id ) { * * @param string $id The Auth0 ID. */ - $check = apply_filters( 'find_auth0_user', null, $id ); - if ( $check instanceof WP_User ) { + $check = apply_filters('find_auth0_user', null, $id); + if ($check instanceof WP_User) { return $check; } @@ -142,14 +147,14 @@ public function find_auth0_user( $id ) { 'blog_id' => 0, ]; - $users = get_users( $query ); + $users = get_users($query); - if ( $users === [] ) { - WP_Auth0_ErrorLog::insert_error( __METHOD__ . ' => get_users() ', __( 'User not found', 'wp-auth0' ) ); + if ($users === []) { + WP_Auth0_ErrorLog::insert_error(__METHOD__ . ' => get_users() ', esc_html__('User not found', 'wp-auth0')); return null; } - return ! empty( $users[0] ) ? $users[0] : null; + return !empty($users[0]) ? $users[0] : null; } /** @@ -158,15 +163,16 @@ public function find_auth0_user( $id ) { * @param int $user_id - WordPress user ID. * @param stdClass $userinfo - User profile object from Auth0. */ - public function update_auth0_object( $user_id, $userinfo ) { - $auth0_user_id = isset( $userinfo->user_id ) ? $userinfo->user_id : $userinfo->sub; - self::update_meta( $user_id, 'auth0_id', $auth0_user_id ); + public function update_auth0_object($user_id, $userinfo) + { + $auth0_user_id = isset($userinfo->user_id) ? $userinfo->user_id : $userinfo->sub; + self::update_meta($user_id, 'auth0_id', $auth0_user_id); - $userinfo_encoded = WP_Auth0_Serializer::serialize( $userinfo ); - $userinfo_encoded = wp_slash( $userinfo_encoded ); - self::update_meta( $user_id, 'auth0_obj', $userinfo_encoded ); + $userinfo_encoded = WP_Auth0_Serializer::serialize($userinfo); + $userinfo_encoded = wp_slash($userinfo_encoded); + self::update_meta($user_id, 'auth0_obj', $userinfo_encoded); - self::update_meta( $user_id, 'last_update', date( 'c' ) ); + self::update_meta($user_id, 'last_update', date('c')); } /** @@ -179,7 +185,8 @@ public function update_auth0_object( $user_id, $userinfo ) { * * @since 3.8.0 */ - public static function get_meta( $user_id, $key ) { + public static function get_meta($user_id, $key) + { /** * Short circuits the return value of the Auth0 user meta field. @@ -189,13 +196,13 @@ public static function get_meta( $user_id, $key ) { * @param integer $user_id The user ID. * @param string $key The meta key. */ - $check = apply_filters( 'auth0_get_meta', null, $user_id, $key ); - if ( $check !== null ) { + $check = apply_filters('auth0_get_meta', null, $user_id, $key); + if ($check !== null) { return $check; } global $wpdb; - return get_user_meta( $user_id, $wpdb->prefix . $key, true ); + return get_user_meta($user_id, $wpdb->prefix . $key, true); } /** @@ -209,7 +216,8 @@ public static function get_meta( $user_id, $key ) { * * @since 3.11.0 */ - public static function update_meta( $user_id, $key, $value ) { + public static function update_meta($user_id, $key, $value) + { /** * Short circuits updating a user's Auth0 meta values. @@ -221,13 +229,13 @@ public static function update_meta( $user_id, $key, $value ) { * @param string $key The meta key. * @param mixed $value The meta value. */ - $check = apply_filters( 'auth0_update_meta', null, $user_id, $key, $value ); - if ( $check !== null ) { + $check = apply_filters('auth0_update_meta', null, $user_id, $key, $value); + if ($check !== null) { return (bool) $check; } global $wpdb; - return update_user_meta( $user_id, $wpdb->prefix . $key, $value ); + return update_user_meta($user_id, $wpdb->prefix . $key, $value); } /** @@ -240,7 +248,8 @@ public static function update_meta( $user_id, $key, $value ) { * * @since 3.11.0 */ - public static function delete_meta( $user_id, $key ) { + public static function delete_meta($user_id, $key) + { /** * Short circuits deleting a user's Auth0 meta values. @@ -251,11 +260,11 @@ public static function delete_meta( $user_id, $key ) { * @param integer $user_id The user ID. * @param string $key The meta key. */ - $check = apply_filters( 'auth0_delete_meta', null, $user_id, $key ); - if ( $check !== null ) { + $check = apply_filters('auth0_delete_meta', null, $user_id, $key); + if ($check !== null) { return (bool) $check; } global $wpdb; - return delete_user_meta( $user_id, $wpdb->prefix . $key ); + return delete_user_meta($user_id, $wpdb->prefix . $key); } } diff --git a/lib/WP_Auth0_WooCommerceOverrides.php b/lib/WP_Auth0_WooCommerceOverrides.php index 064298ac4..1ad2f5c04 100644 --- a/lib/WP_Auth0_WooCommerceOverrides.php +++ b/lib/WP_Auth0_WooCommerceOverrides.php @@ -1,4 +1,5 @@ options = $options; } @@ -33,16 +36,17 @@ public function __construct( WP_Auth0_Options $options ) { * * @param string $redirect_page - Page slug to redirect to after logging in. */ - private function render_login_form( $redirect_page ) { + private function render_login_form($redirect_page) + { wp_auth0_login_enqueue_scripts(); - if ( $this->options->get( 'auto_login', false ) ) { + if ($this->options->get('auto_login', false)) { // Redirecting to WordPress login page. - $redirect_url = get_permalink( wc_get_page_id( $redirect_page ) ); - $login_url = wp_login_url( $redirect_url ); + $redirect_url = get_permalink(wc_get_page_id($redirect_page)); + $login_url = wp_login_url($redirect_url); - printf( "%s", $login_url, __( 'Login', 'wp-auth0' ) ); + echo wp_kses(sprintf("%s", $login_url, esc_html__('Login', 'wp-auth0')), ['a' => ['class' => true, 'href' => true]]); } else { - echo wp_auth0_render_lock_form( '' ); + echo wp_kses_post(wp_auth0_render_lock_form('')); } } @@ -53,16 +57,17 @@ private function render_login_form( $redirect_page ) { * * @return mixed */ - public function override_woocommerce_checkout_login_form( $html ) { + public function override_woocommerce_checkout_login_form($html) + { - if ( ! wp_auth0_is_ready() ) { + if (!wp_auth0_is_ready()) { return $html; } - $this->render_login_form( 'checkout' ); + $this->render_login_form('checkout'); - if ( wp_auth0_can_show_wp_login_form() ) { - echo ''; + if (wp_auth0_can_show_wp_login_form()) { + echo wp_kses('', ['style' => []]); } } @@ -73,12 +78,13 @@ public function override_woocommerce_checkout_login_form( $html ) { * * @return mixed */ - public function override_woocommerce_login_form( $html ) { + public function override_woocommerce_login_form($html) + { - if ( ! wp_auth0_is_ready() ) { + if (!wp_auth0_is_ready()) { return $html; } - $this->render_login_form( 'myaccount' ); + $this->render_login_form('myaccount'); } } diff --git a/lib/admin/WP_Auth0_Admin.php b/lib/admin/WP_Auth0_Admin.php index fe8e0941b..cc4d07c48 100755 --- a/lib/admin/WP_Auth0_Admin.php +++ b/lib/admin/WP_Auth0_Admin.php @@ -1,8 +1,9 @@ a0_options = $a0_options; $this->router = $router; $this->sections = [ - 'basic' => new WP_Auth0_Admin_Basic( $this->a0_options ), - 'features' => new WP_Auth0_Admin_Features( $this->a0_options ), - 'appearance' => new WP_Auth0_Admin_Appearance( $this->a0_options ), - 'advanced' => new WP_Auth0_Admin_Advanced( $this->a0_options, $this->router ), + 'basic' => new WP_Auth0_Admin_Basic($this->a0_options), + 'features' => new WP_Auth0_Admin_Features($this->a0_options), + 'appearance' => new WP_Auth0_Admin_Appearance($this->a0_options), + 'advanced' => new WP_Auth0_Admin_Advanced($this->a0_options, $this->router), ]; } /** * Enqueue scripts for all Auth0 wp-admin pages */ - public function admin_enqueue() { + public function admin_enqueue() + { // Nonce is not needed here as this is not processing form data. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // Register admin styles - wp_register_style( 'wpa0_admin_initial_setup', WPA0_PLUGIN_CSS_URL . 'initial-setup.css', false, WPA0_VERSION ); + wp_register_style('wpa0_admin_initial_setup', WPA0_PLUGIN_CSS_URL . 'initial-setup.css', false, WPA0_VERSION); // Register admin scripts - wp_register_script( 'wpa0_async', WPA0_PLUGIN_LIB_URL . 'async.min.js', false, WPA0_VERSION ); - wp_register_script( 'wpa0_admin', WPA0_PLUGIN_JS_URL . 'admin.js', [ 'jquery' ], WPA0_VERSION ); + wp_register_script('wpa0_async', WPA0_PLUGIN_LIB_URL . 'async.min.js', false, WPA0_VERSION, true); + wp_register_script('wpa0_admin', WPA0_PLUGIN_JS_URL . 'admin.js', ['jquery'], WPA0_VERSION, true); wp_localize_script( 'wpa0_admin', 'wpa0', [ - 'media_title' => __( 'Choose your icon', 'wp-auth0' ), - 'media_button' => __( 'Choose icon', 'wp-auth0' ), - 'ajax_working' => __( 'Working ...', 'wp-auth0' ), - 'ajax_done' => __( 'Done!', 'wp-auth0' ), - 'refresh_prompt' => __( 'Save or refresh this page to see changes.', 'wp-auth0' ), - 'clear_cache_nonce' => wp_create_nonce( 'auth0_delete_cache_transient' ), - 'rotate_token_nonce' => wp_create_nonce( WP_Auth0_Admin_Advanced::ROTATE_TOKEN_NONCE_ACTION ), - 'form_confirm_submit_msg' => __( 'Are you sure?', 'wp-auth0' ), - 'ajax_url' => admin_url( 'admin-ajax.php' ), + 'media_title' => esc_html__('Choose your icon', 'wp-auth0'), + 'media_button' => esc_html__('Choose icon', 'wp-auth0'), + 'ajax_working' => esc_html__('Working ...', 'wp-auth0'), + 'ajax_done' => esc_html__('Done!', 'wp-auth0'), + 'refresh_prompt' => esc_html__('Save or refresh this page to see changes.', 'wp-auth0'), + 'clear_cache_nonce' => wp_create_nonce('auth0_delete_cache_transient'), + 'rotate_token_nonce' => wp_create_nonce(WP_Auth0_Admin_Advanced::ROTATE_TOKEN_NONCE_ACTION), + 'form_confirm_submit_msg' => esc_html__('Are you sure?', 'wp-auth0'), + 'ajax_url' => admin_url('admin-ajax.php'), ] ); // Only checking the value, not processing. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized - $wpa0_curr_page = ! empty( $_REQUEST['page'] ) ? wp_unslash( $_REQUEST['page'] ) : ''; - $wpa0_pages = [ 'wpa0', 'wpa0-errors', 'wpa0-import-settings', 'wpa0-setup' ]; - if ( ! in_array( $wpa0_curr_page, $wpa0_pages ) ) { + $wpa0_curr_page = !empty($_REQUEST['page']) ? wp_unslash($_REQUEST['page']) : ''; + $wpa0_pages = ['wpa0', 'wpa0-errors', 'wpa0-import-settings', 'wpa0-setup']; + if (!in_array($wpa0_curr_page, $wpa0_pages)) { return false; } - wp_enqueue_script( 'wpa0_admin' ); - wp_enqueue_script( 'wpa0_async' ); + wp_enqueue_script('wpa0_admin'); + wp_enqueue_script('wpa0_async'); - if ( 'wpa0' === $wpa0_curr_page ) { + if ('wpa0' === $wpa0_curr_page) { wp_enqueue_media(); - wp_enqueue_style( 'media' ); + wp_enqueue_style('media'); } - wp_enqueue_style( 'wpa0_admin_initial_setup' ); + wp_enqueue_style('wpa0_admin_initial_setup'); return true; // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification } - public function init_admin() { + public function init_admin() + { - foreach ( $this->sections as $section ) { + foreach ($this->sections as $section) { $section->init(); } @@ -83,7 +87,7 @@ public function init_admin() { $this->a0_options->get_options_name() . '_basic', $this->a0_options->get_options_name(), [ - 'sanitize_callback' => [ $this, 'input_validator' ], + 'sanitize_callback' => [$this, 'input_validator'], ] ); } @@ -96,49 +100,51 @@ public function init_admin() { * * @return mixed */ - public function input_validator( array $input ) { + public function input_validator(array $input) + { $constant_keys = $this->a0_options->get_all_constant_keys(); // Look for and set constant overrides so validation is still possible. - foreach ( $constant_keys as $key ) { - $input[ $key ] = $this->a0_options->get_constant_val( $key ); + foreach ($constant_keys as $key) { + $input[$key] = $this->a0_options->get_constant_val($key); } - $option_keys = $this->a0_options->get_defaults( true ); + $option_keys = $this->a0_options->get_defaults(true); // Look for custom settings fields. $custom_opts = []; - foreach ( self::OPT_SECTIONS as $section ) { - $custom_opts = array_merge( $custom_opts, apply_filters( 'auth0_settings_fields', [], $section ) ); + foreach (self::OPT_SECTIONS as $section) { + $custom_opts = array_merge($custom_opts, apply_filters('auth0_settings_fields', [], $section)); } // Merge in any custom setting option keys. - foreach ( $custom_opts as $custom_opt ) { - if ( $custom_opt && $custom_opt['opt'] ) { + foreach ($custom_opts as $custom_opt) { + if ($custom_opt && $custom_opt['opt']) { $option_keys[] = $custom_opt['opt']; } } // Remove unknown keys. - foreach ( $input as $key => $val ) { - if ( ! in_array( $key, $option_keys ) ) { - unset( $input[ $key ] ); + foreach ($input as $key => $val) { + if (!in_array($key, $option_keys)) { + unset($input[$key]); } } - foreach ( $this->sections as $name => $section ) { - $input = $section->input_validator( $input ); + foreach ($this->sections as $name => $section) { + $input = $section->input_validator($input); } // Remove constant overrides so they are not saved to the database. - foreach ( $constant_keys as $key ) { - unset( $input[ $key ] ); + foreach ($constant_keys as $key) { + unset($input[$key]); } return $input; } - public function render_settings_page() { + public function render_settings_page() + { include WPA0_PLUGIN_DIR . 'templates/settings.php'; } } diff --git a/lib/admin/WP_Auth0_Admin_Advanced.php b/lib/admin/WP_Auth0_Admin_Advanced.php index b37d6d570..8a8e9213b 100644 --- a/lib/admin/WP_Auth0_Admin_Advanced.php +++ b/lib/admin/WP_Auth0_Admin_Advanced.php @@ -1,4 +1,5 @@ Auth0 > Settings > Advanced tab. */ -class WP_Auth0_Admin_Advanced extends WP_Auth0_Admin_Generic { +class WP_Auth0_Admin_Advanced extends WP_Auth0_Admin_Generic +{ /** * AJAX nonce action for the rotate token endpoint. @@ -33,8 +35,9 @@ class WP_Auth0_Admin_Advanced extends WP_Auth0_Admin_Generic { * @param WP_Auth0_Options $options - WP_Auth0_Options instance. * @param WP_Auth0_Routes $router - WP_Auth0_Routes instance. */ - public function __construct( WP_Auth0_Options $options, WP_Auth0_Routes $router ) { - parent::__construct( $options ); + public function __construct(WP_Auth0_Options $options, WP_Auth0_Routes $router) + { + parent::__construct($options); $this->router = $router; $this->actions_middlewares[] = 'migration_ws_validation'; $this->actions_middlewares[] = 'migration_ips_validation'; @@ -46,52 +49,53 @@ public function __construct( WP_Auth0_Options $options, WP_Auth0_Routes $router * @see \WP_Auth0_Admin::init_admin * @see \WP_Auth0_Admin_Generic::init_option_section */ - public function init() { + public function init() + { $options = [ [ - 'name' => __( 'Require Verified Email', 'wp-auth0' ), + 'name' => esc_html__('Require Verified Email', 'wp-auth0'), 'opt' => 'requires_verified_email', 'id' => 'wpa0_verified_email', 'function' => 'render_verified_email', ], [ - 'name' => __( 'Skip Strategies', 'wp-auth0' ), + 'name' => esc_html__('Skip Strategies', 'wp-auth0'), 'opt' => 'skip_strategies', 'id' => 'wpa0_skip_strategies', 'function' => 'render_skip_strategies', ], [ - 'name' => __( 'Remember User Session', 'wp-auth0' ), + 'name' => esc_html__('Remember User Session', 'wp-auth0'), 'opt' => 'remember_users_session', 'id' => 'wpa0_remember_users_session', 'function' => 'render_remember_users_session', ], [ - 'name' => __( 'Login Redirection URL', 'wp-auth0' ), + 'name' => esc_html__('Login Redirection URL', 'wp-auth0'), 'opt' => 'default_login_redirection', 'id' => 'wpa0_default_login_redirection', 'function' => 'render_default_login_redirection', ], [ - 'name' => __( 'Force HTTPS Callback', 'wp-auth0' ), + 'name' => esc_html__('Force HTTPS Callback', 'wp-auth0'), 'opt' => 'force_https_callback', 'id' => 'wpa0_force_https_callback', 'function' => 'render_force_https_callback', ], [ - 'name' => __( 'Auto Provisioning', 'wp-auth0' ), + 'name' => esc_html__('Auto Provisioning', 'wp-auth0'), 'opt' => 'auto_provisioning', 'id' => 'wpa0_auto_provisioning', 'function' => 'render_auto_provisioning', ], [ - 'name' => __( 'User Migration Endpoints', 'wp-auth0' ), + 'name' => esc_html__('User Migration Endpoints', 'wp-auth0'), 'opt' => 'migration_ws', 'id' => 'wpa0_migration_ws', 'function' => 'render_migration_ws', ], [ - 'name' => __( 'Migration IPs Whitelist', 'wp-auth0' ), + 'name' => esc_html__('Migration IPs Whitelist', 'wp-auth0'), 'opt' => 'migration_ips_filter', 'id' => 'wpa0_migration_ws_ips_filter', 'function' => 'render_migration_ws_ips_filter', @@ -103,26 +107,26 @@ public function init() { 'function' => 'render_migration_ws_ips', ], [ - 'name' => __( 'Valid Proxy IP', 'wp-auth0' ), + 'name' => esc_html__('Valid Proxy IP', 'wp-auth0'), 'opt' => 'valid_proxy_ip', 'id' => 'wpa0_valid_proxy_ip', 'function' => 'render_valid_proxy_ip', ], [ - 'name' => __( 'Cookie Domain', 'wp-auth0' ), + 'name' => esc_html__('Cookie Domain', 'wp-auth0'), 'opt' => 'cookie_domain', 'id' => 'wpa0_cookie_domain', 'function' => 'render_cookie_domain', ], [ - 'name' => __( 'Disable Auth0 logging in Wordpress', 'wp-auth0' ), + 'name' => esc_html__('Disable Auth0 logging in Wordpress', 'wp-auth0'), 'opt' => 'disable_logging', 'id' => 'wpa0_disable_logging', 'function' => 'render_disable_logging', ], ]; - $this->init_option_section( '', 'advanced', $options ); + $this->init_option_section('', 'advanced', $options); } /** @@ -134,12 +138,13 @@ public function init() { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_verified_email( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'], 'wpa0_skip_strategies' ); + public function render_verified_email($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name'], 'wpa0_skip_strategies'); $this->render_field_description( - __( 'Require new users to both provide and verify their email before logging in. ', 'wp-auth0' ) . - __( 'An email address is verified manually by an email from Auth0 or automatically by the provider. ', 'wp-auth0' ) . - __( 'This will disallow logins from social connections that do not provide email (like Twitter)', 'wp-auth0' ) + esc_html__('Require new users to both provide and verify their email before logging in. ', 'wp-auth0') . + esc_html__('An email address is verified manually by an email from Auth0 or automatically by the provider. ', 'wp-auth0') . + esc_html__('This will disallow logins from social connections that do not provide email (like Twitter)', 'wp-auth0') ); } @@ -154,13 +159,14 @@ public function render_verified_email( $args = [] ) { * * @since 3.8.0 */ - public function render_skip_strategies( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', 'e.g. "twitter,ldap"' ); + public function render_skip_strategies($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', 'e.g. "twitter,ldap"'); $this->render_field_description( - __( 'Enter one or more strategies, separated by commas, to skip email verification. ', 'wp-auth0' ) . - __( 'You can find the strategy under the "Connection Name" field in the Auth0 dashboard. ', 'wp-auth0' ) . - __( 'Leave this field blank to require email for all strategies. ', 'wp-auth0' ) . - __( 'This could introduce a security risk and should be used sparingly, if at all', 'wp-auth0' ) + esc_html__('Enter one or more strategies, separated by commas, to skip email verification. ', 'wp-auth0') . + esc_html__('You can find the strategy under the "Connection Name" field in the Auth0 dashboard. ', 'wp-auth0') . + esc_html__('Leave this field blank to require email for all strategies. ', 'wp-auth0') . + esc_html__('This could introduce a security risk and should be used sparingly, if at all', 'wp-auth0') ); } @@ -173,11 +179,12 @@ public function render_skip_strategies( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_remember_users_session( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_remember_users_session($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'A user session by default is kept for two days. ', 'wp-auth0' ) . - __( 'Enabling this setting will extend that and make the session be kept for 14 days', 'wp-auth0' ) + esc_html__('A user session by default is kept for two days. ', 'wp-auth0') . + esc_html__('Enabling this setting will extend that and make the session be kept for 14 days', 'wp-auth0') ); } @@ -190,11 +197,12 @@ public function render_remember_users_session( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_default_login_redirection( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); + public function render_default_login_redirection($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'URL where successfully logged-in users are redirected when using the wp-login.php page. ', 'wp-auth0' ) . - __( 'This can be overridden with the redirect_to URL parameter', 'wp-auth0' ) + esc_html__('URL where successfully logged-in users are redirected when using the wp-login.php page. ', 'wp-auth0') . + wp_kses(__('This can be overridden with the redirect_to URL parameter', 'wp-auth0'), ['code' => []]) ); } @@ -207,11 +215,12 @@ public function render_default_login_redirection( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_force_https_callback( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_force_https_callback($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Forces the plugin to use HTTPS for the callback URL when a site supports both; ', 'wp-auth0' ) . - __( 'if disabled, the protocol from the WordPress home URL will be used', 'wp-auth0' ) + esc_html__('Forces the plugin to use HTTPS for the callback URL when a site supports both; ', 'wp-auth0') . + esc_html__('if disabled, the protocol from the WordPress home URL will be used', 'wp-auth0') ); } @@ -224,11 +233,12 @@ public function render_force_https_callback( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_auto_provisioning( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_auto_provisioning($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Create new users in the WordPress database when signups are off. ', 'wp-auth0' ) . - __( 'Signups will not be allowed but successful Auth0 logins will add the user in WordPress', 'wp-auth0' ) + esc_html__('Create new users in the WordPress database when signups are off. ', 'wp-auth0') . + esc_html__('Signups will not be allowed but successful Auth0 logins will add the user in WordPress', 'wp-auth0') ); } @@ -241,11 +251,12 @@ public function render_auto_provisioning( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_disable_logging( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_disable_logging($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Disables Auth0 logging within WordPress. ', 'wp-auth0' ) . - __( 'If enabled, Auth0 logging will be disabled in WordPress. Other Auth0 logs are unaffected by this switch', 'wp-auth0' ) + esc_html__('Disables Auth0 logging within WordPress. ', 'wp-auth0') . + esc_html__('If enabled, Auth0 logging will be disabled in WordPress. Other Auth0 logs are unaffected by this switch', 'wp-auth0') ); } @@ -258,10 +269,11 @@ public function render_disable_logging( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_cookie_domain( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); + public function render_cookie_domain($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Overrides the default domain assignment for cookie storage. Use with caution.', 'wp-auth0' ) + esc_html__('Overrides the default domain assignment for cookie storage. Use with caution.', 'wp-auth0') ); } @@ -274,45 +286,46 @@ public function render_cookie_domain( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_migration_ws( $args = [] ) { - $value = $this->options->get( $args['opt_name'] ); - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_migration_ws($args = []) + { + $value = $this->options->get($args['opt_name']); + $this->render_switch($args['label_for'], $args['opt_name']); - if ( $value ) { + if ($value) { $this->render_field_description( - __( 'User migration endpoints activated. ', 'wp-auth0' ) . - __( 'See below for the token to use. ', 'wp-auth0' ) . - __( 'The custom database scripts need to be configured manually as described ', 'wp-auth0' ) . - $this->get_docs_link( 'cms/wordpress/user-migration' ) + esc_html__('User migration endpoints activated. ', 'wp-auth0') . + esc_html__('See below for the token to use. ', 'wp-auth0') . + esc_html__('The custom database scripts need to be configured manually as described ', 'wp-auth0') . + $this->get_docs_link('cms/wordpress/user-migration') ); - $this->render_field_description( 'Migration token:' ); - if ( $this->options->has_constant_val( 'migration_token' ) ) { - $this->render_const_notice( 'migration_token' ); + $this->render_field_description('Migration token:'); + if ($this->options->has_constant_val('migration_token')) { + $this->render_const_notice('migration_token'); } - $migration_token = $this->options->get( 'migration_token' ); + $migration_token = $this->options->get('migration_token'); printf( '%s
', - $migration_token ? sanitize_text_field( $migration_token ) : __( 'No migration token', 'wp-auth0' ) + esc_html($migration_token ? sanitize_text_field($migration_token) : esc_html__('No migration token', 'wp-auth0')) ); - if ( ! $this->options->has_constant_val( 'migration_token' ) ) { - printf( + if (!$this->options->has_constant_val('migration_token')) { + echo wp_kses(sprintf( '', - esc_attr( self::ROTATE_TOKEN_NONCE_ACTION ), + esc_attr(self::ROTATE_TOKEN_NONCE_ACTION), esc_attr( - __( 'This will change your migration token immediately. ', 'wp-auth0' ) . - __( 'The new token must be changed in the custom scripts for your database Connection. ', 'wp-auth0' ) . - __( 'Continue?', 'wp-auth0' ) + esc_html__('This will change your migration token immediately. ', 'wp-auth0') . + esc_html__('The new token must be changed in the custom scripts for your database Connection. ', 'wp-auth0') . + esc_html__('Continue?', 'wp-auth0') ), - __( 'Generate New Migration Token', 'wp-auth0' ) - ); + esc_html__('Generate New Migration Token', 'wp-auth0') + ), ['button' => ['id' => true, 'class' => true, 'data-confirm-msg' => true]]); } } else { $this->render_field_description( - __( 'User migration endpoints deactivated. ', 'wp-auth0' ) . - __( 'Custom database connections can be deactivated in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'connections/database' ) + esc_html__('User migration endpoints deactivated. ', 'wp-auth0') . + esc_html__('Custom database connections can be deactivated in the ', 'wp-auth0') . + $this->get_dashboard_link('connections/database') ); } } @@ -326,8 +339,9 @@ public function render_migration_ws( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_migration_ws_ips_filter( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'], 'wpa0_migration_ws_ips' ); + public function render_migration_ws_ips_filter($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name'], 'wpa0_migration_ws_ips'); } /** @@ -339,14 +353,15 @@ public function render_migration_ws_ips_filter( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_migration_ws_ips( $args = [] ) { - $ip_check = new WP_Auth0_Ip_Check( WP_Auth0_Options::Instance() ); - $this->render_textarea_field( $args['label_for'], $args['opt_name'] ); + public function render_migration_ws_ips($args = []) + { + $ip_check = new WP_Auth0_Ip_Check(WP_Auth0_Options::Instance()); + $this->render_textarea_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Only requests from these IPs will be allowed to access the migration endpoints. ', 'wp-auth0' ) . - __( 'Separate multiple IPs with commas. ', 'wp-auth0' ) . - __( 'The following Auth0 IPs are automatically whitelisted: ', 'wp-auth0' ) . - '

' . $ip_check->get_ips_by_domain( null, ' ' ) . '' + esc_html__('Only requests from these IPs will be allowed to access the migration endpoints. ', 'wp-auth0') . + esc_html__('Separate multiple IPs with commas. ', 'wp-auth0') . + esc_html__('The following Auth0 IPs are automatically whitelisted: ', 'wp-auth0') . + '

' . $ip_check->get_ips_by_domain(null, ' ') . '' ); } @@ -359,10 +374,11 @@ public function render_migration_ws_ips( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_valid_proxy_ip( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); + public function render_valid_proxy_ip($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Whitelist for proxy and load balancer IPs to enable logins and migration webservices', 'wp-auth0' ) + esc_html__('Whitelist for proxy and load balancer IPs to enable logins and migration webservices', 'wp-auth0') ); } @@ -373,20 +389,21 @@ public function render_valid_proxy_ip( $args = [] ) { * * @return array */ - public function basic_validation( array $input ) { - $input['requires_verified_email'] = $this->sanitize_switch_val( $input['requires_verified_email'] ?? null ); - $input['skip_strategies'] = $this->sanitize_text_val( $input['skip_strategies'] ?? null ); - $input['remember_users_session'] = $this->sanitize_switch_val( $input['remember_users_session'] ?? null ); - $input['default_login_redirection'] = $this->validate_login_redirect( $input['default_login_redirection'] ?? null ); - $input['force_https_callback'] = $this->sanitize_switch_val( $input['force_https_callback'] ?? null ); - $input['auto_provisioning'] = $this->sanitize_switch_val( $input['auto_provisioning'] ?? null ); + public function basic_validation(array $input) + { + $input['requires_verified_email'] = $this->sanitize_switch_val($input['requires_verified_email'] ?? null); + $input['skip_strategies'] = $this->sanitize_text_val($input['skip_strategies'] ?? null); + $input['remember_users_session'] = $this->sanitize_switch_val($input['remember_users_session'] ?? null); + $input['default_login_redirection'] = $this->validate_login_redirect($input['default_login_redirection'] ?? null); + $input['force_https_callback'] = $this->sanitize_switch_val($input['force_https_callback'] ?? null); + $input['auto_provisioning'] = $this->sanitize_switch_val($input['auto_provisioning'] ?? null); // `migration_ws` is sanitized in $this->migration_ws_validation() below. // `migration_token` is sanitized in $this->migration_ws_validation() below. - $input['migration_ips_filter'] = $this->sanitize_switch_val( $input['migration_ips_filter'] ?? null ); + $input['migration_ips_filter'] = $this->sanitize_switch_val($input['migration_ips_filter'] ?? null); // `migration_ips` is sanitized in $this->migration_ips_validation() below. - $input['valid_proxy_ip'] = ( isset( $input['valid_proxy_ip'] ) ? $input['valid_proxy_ip'] : null ); - $input['cookie_domain'] = $this->sanitize_text_val( $input['cookie_domain'] ?? null ); - $input['disable_logging'] = $this->sanitize_switch_val( $input['disable_logging'] ?? null ); + $input['valid_proxy_ip'] = (isset($input['valid_proxy_ip']) ? $input['valid_proxy_ip'] : null); + $input['cookie_domain'] = $this->sanitize_text_val($input['cookie_domain'] ?? null); + $input['disable_logging'] = $this->sanitize_switch_val($input['disable_logging'] ?? null); return $input; } @@ -398,15 +415,16 @@ public function basic_validation( array $input ) { * * @return array */ - public function migration_ws_validation( array $input ) { - $input['migration_ws'] = $this->sanitize_switch_val( $input['migration_ws'] ?? null ); - $input['migration_token'] = $this->options->get( 'migration_token' ); + public function migration_ws_validation(array $input) + { + $input['migration_ws'] = $this->sanitize_switch_val($input['migration_ws'] ?? null); + $input['migration_token'] = $this->options->get('migration_token'); - if ( empty( $input['migration_token'] ) ) { + if (empty($input['migration_token'])) { $input['migration_token'] = wp_auth0_generate_token(); } - if ( $input['migration_ws'] ) { + if ($input['migration_ws']) { $this->router->setup_rewrites(); flush_rewrite_rules(); } @@ -422,25 +440,26 @@ public function migration_ws_validation( array $input ) { * * @return array */ - public function migration_ips_validation( array $input ) { + public function migration_ips_validation(array $input) + { - if ( empty( $input['migration_ips'] ) ) { + if (empty($input['migration_ips'])) { $input['migration_ips'] = ''; return $input; } - $ip_addresses = explode( ',', $this->sanitize_text_val( $input['migration_ips'] ) ); - $ip_addresses = array_map( 'trim', $ip_addresses ); - $ip_addresses = array_filter( $ip_addresses ); - $ip_addresses = array_unique( $ip_addresses ); + $ip_addresses = explode(',', $this->sanitize_text_val($input['migration_ips'])); + $ip_addresses = array_map('trim', $ip_addresses); + $ip_addresses = array_filter($ip_addresses); + $ip_addresses = array_unique($ip_addresses); - if ( ! empty( $input['domain'] ) ) { + if (!empty($input['domain'])) { $ip_check = new WP_Auth0_Ip_Check(); - $whitelist_ips = $ip_check->get_ips_by_domain( $input['domain'], null ); - $ip_addresses = array_diff( $ip_addresses, $whitelist_ips ); + $whitelist_ips = $ip_check->get_ips_by_domain($input['domain'], null); + $ip_addresses = array_diff($ip_addresses, $whitelist_ips); } - $input['migration_ips'] = implode( ', ', $ip_addresses ); + $input['migration_ips'] = implode(', ', $ip_addresses); return $input; } @@ -452,35 +471,36 @@ public function migration_ips_validation( array $input ) { * * @return string */ - public function validate_login_redirect( $new_url, $existing_url = null ) { - $new_redirect_url = esc_url_raw( strtolower( $new_url ) ); - $old_redirect_url = $existing_url ?? $this->options->get( 'default_login_redirection' ); + public function validate_login_redirect($new_url, $existing_url = null) + { + $new_redirect_url = esc_url_raw(strtolower($new_url)); + $old_redirect_url = $existing_url ?? $this->options->get('default_login_redirection'); // No change so no validation needed. - if ( $new_redirect_url === strtolower( $old_redirect_url ) ) { + if ($new_redirect_url === strtolower($old_redirect_url)) { return $new_url; } $home_url = home_url(); // Set the default redirection URL to be the homepage. - if ( empty( $new_redirect_url ) ) { + if (empty($new_redirect_url)) { return $home_url; } // Allow subdomains within the same domain. - $home_domain = $this->get_domain( $home_url ); - $redirect_domain = $this->get_domain( $new_redirect_url ); - if ( $home_domain === $redirect_domain ) { + $home_domain = $this->get_domain($home_url); + $redirect_domain = $this->get_domain($new_redirect_url); + if ($home_domain === $redirect_domain) { return $new_url; } // If we get here, the redirect URL is a page outside of the WordPress install. - $error = __( 'Advanced > "Login Redirection URL" cannot point to another site.', 'wp-auth0' ); - $this->add_validation_error( $error ); + $error = esc_html__('Advanced > "Login Redirection URL" cannot point to another site.', 'wp-auth0'); + $this->add_validation_error($error); // Either revert to the previous (validated) value or set as the homepage. - return ! empty( $old_redirect_url ) ? $old_redirect_url : $home_url; + return !empty($old_redirect_url) ? $old_redirect_url : $home_url; } /** @@ -490,11 +510,12 @@ public function validate_login_redirect( $new_url, $existing_url = null ) { * * @return mixed|string */ - private function get_domain( $url ) { - $host_pieces = explode( '.', wp_parse_url( $url, PHP_URL_HOST ) ); - $domain = array_pop( $host_pieces ); - if ( count( $host_pieces ) ) { - $domain = array_pop( $host_pieces ) . '.' . $domain; + private function get_domain($url) + { + $host_pieces = explode('.', wp_parse_url($url, PHP_URL_HOST)); + $domain = array_pop($host_pieces); + if (count($host_pieces)) { + $domain = array_pop($host_pieces) . '.' . $domain; } return $domain; } diff --git a/lib/admin/WP_Auth0_Admin_Appearance.php b/lib/admin/WP_Auth0_Admin_Appearance.php index 6261f0c8b..a0f2d7b98 100644 --- a/lib/admin/WP_Auth0_Admin_Appearance.php +++ b/lib/admin/WP_Auth0_Admin_Appearance.php @@ -1,4 +1,5 @@ __( 'Passwordless Login', 'wp-auth0' ), + 'name' => esc_html__('Passwordless Login', 'wp-auth0'), 'opt' => 'passwordless_enabled', 'id' => 'wpa0_passwordless_enabled', 'function' => 'render_passwordless_enabled', ], [ - 'name' => __( 'Icon URL', 'wp-auth0' ), + 'name' => esc_html__('Icon URL', 'wp-auth0'), 'opt' => 'icon_url', 'id' => 'wpa0_icon_url', 'function' => 'render_icon_url', ], [ - 'name' => __( 'Form Title', 'wp-auth0' ), + 'name' => esc_html__('Form Title', 'wp-auth0'), 'opt' => 'form_title', 'id' => 'wpa0_form_title', 'function' => 'render_form_title', ], [ - 'name' => __( 'Enable Gravatar Integration', 'wp-auth0' ), + 'name' => esc_html__('Enable Gravatar Integration', 'wp-auth0'), 'opt' => 'gravatar', 'id' => 'wpa0_gravatar', 'function' => 'render_gravatar', ], [ - 'name' => __( 'Login Name Style', 'wp-auth0' ), + 'name' => esc_html__('Login Name Style', 'wp-auth0'), 'opt' => 'username_style', 'id' => 'wpa0_username_style', 'function' => 'render_username_style', ], [ - 'name' => __( 'Primary Color', 'wp-auth0' ), + 'name' => esc_html__('Primary Color', 'wp-auth0'), 'opt' => 'primary_color', 'id' => 'wpa0_primary_color', 'function' => 'render_primary_color', ], [ - 'name' => __( 'Extra Settings', 'wp-auth0' ), + 'name' => esc_html__('Extra Settings', 'wp-auth0'), 'opt' => 'extra_conf', 'id' => 'wpa0_extra_conf', 'function' => 'render_extra_conf', ], [ - 'name' => __( 'Use Custom Lock JS URL', 'wp-auth0' ), + 'name' => esc_html__('Use Custom Lock JS URL', 'wp-auth0'), 'opt' => 'custom_cdn_url', 'id' => 'wpa0_custom_cdn_url', 'function' => 'render_custom_cdn_url', ], [ - 'name' => __( 'Custom Lock JS URL', 'wp-auth0' ), + 'name' => esc_html__('Custom Lock JS URL', 'wp-auth0'), 'opt' => 'cdn_url', 'id' => 'wpa0_cdn_url', 'function' => 'render_cdn_url', ], [ - 'name' => __( 'Connections to Show', 'wp-auth0' ), + 'name' => esc_html__('Connections to Show', 'wp-auth0'), 'opt' => 'lock_connections', 'id' => 'wpa0_connections', 'function' => 'render_connections', ], ]; - $this->init_option_section( '', 'appearance', $options ); + $this->init_option_section('', 'appearance', $options); } /** @@ -94,14 +97,15 @@ public function init() { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_custom_cdn_url( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'], 'wpa0_cdn_url' ); - $this->render_field_description( __( 'Use a custom Lock CDN URL instead of the default. ', 'wp-auth0' ) ); + public function render_custom_cdn_url($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name'], 'wpa0_cdn_url'); + $this->render_field_description(esc_html__('Use a custom Lock CDN URL instead of the default. ', 'wp-auth0')); - if ( ! $this->options->get( $args['opt_name'] ) ) { + if (!$this->options->get($args['opt_name'])) { $this->render_field_description( - __( 'Currently using:', 'wp-auth0' ) . - ' ' . WPA0_LOCK_CDN_URL . '' + esc_html__('Currently using:', 'wp-auth0') . + ' ' . WPA0_LOCK_CDN_URL . '' ); } } @@ -115,10 +119,11 @@ public function render_custom_cdn_url( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_cdn_url( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text' ); + public function render_cdn_url($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name'], 'text'); $this->render_field_description( - __( 'This should point to the latest Lock JS available in the CDN and rarely needs to change', 'wp-auth0' ) + esc_html__('This should point to the latest Lock JS available in the CDN and rarely needs to change', 'wp-auth0') ); } @@ -131,14 +136,15 @@ public function render_cdn_url( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_passwordless_enabled( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_passwordless_enabled($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Turn on Passwordless login (email or SMS) in the Auth0 form. ', 'wp-auth0' ) . - __( 'Passwordless connections are managed in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'connections/passwordless' ) . - __( ' and at least one must be active and enabled on this Application for this to work. ', 'wp-auth0' ) . - __( 'Username/password login is not enabled when Passwordless is on', 'wp-auth0' ) + esc_html__('Turn on Passwordless login (email or SMS) in the Auth0 form. ', 'wp-auth0') . + esc_html__('Passwordless connections are managed in the ', 'wp-auth0') . + $this->get_dashboard_link('connections/passwordless') . + esc_html__(' and at least one must be active and enabled on this Application for this to work. ', 'wp-auth0') . + esc_html__('Username/password login is not enabled when Passwordless is on', 'wp-auth0') ); } @@ -151,19 +157,20 @@ public function render_passwordless_enabled( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_connections( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', 'eg: "sms, google-oauth2, github"' ); + public function render_connections($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', 'eg: "sms, google-oauth2, github"'); $this->render_field_description( - __( 'Specify which Social, Database, or Passwordless connections to display in the Auth0 form. ', 'wp-auth0' ) . - __( 'If this is empty, all enabled connections for this Application will be shown. ', 'wp-auth0' ) . - __( 'Separate multiple connection names with a comma. ', 'wp-auth0' ) . - sprintf( - // translators: HTML link to the Auth0 dashboard. - __( 'Connections listed here must already be active in your %s', 'wp-auth0' ), - $this->get_dashboard_link( 'connections/social' ) - ) . - __( ' and enabled for this Application. ', 'wp-auth0' ) . - __( 'Click on a Connection and use the "Name" value in this field', 'wp-auth0' ) + esc_html__('Specify which Social, Database, or Passwordless connections to display in the Auth0 form. ', 'wp-auth0') . + esc_html__('If this is empty, all enabled connections for this Application will be shown. ', 'wp-auth0') . + esc_html__('Separate multiple connection names with a comma. ', 'wp-auth0') . + sprintf( + // translators: HTML link to the Auth0 dashboard. + esc_html__('Connections listed here must already be active in your %s', 'wp-auth0'), + $this->get_dashboard_link('connections/social') + ) . + esc_html__(' and enabled for this Application. ', 'wp-auth0') . + esc_html__('Click on a Connection and use the "Name" value in this field', 'wp-auth0') ); } @@ -176,12 +183,13 @@ public function render_connections( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_icon_url( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); - printf( ' %s', __( 'Choose Icon', 'wp-auth0' ) ); + public function render_icon_url($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); + echo wp_kses(sprintf(' %s', esc_html__('Choose Icon', 'wp-auth0')), ['a' => ['id' => true, 'class' => true]]); $this->render_field_description( - __( 'Icon above the title on the Auth0 login form. ', 'wp-auth0' ) . - __( 'This image works best as a PNG with a transparent background less than 120px tall', 'wp-auth0' ) + esc_html__('Icon above the title on the Auth0 login form. ', 'wp-auth0') . + esc_html__('This image works best as a PNG with a transparent background less than 120px tall', 'wp-auth0') ); } @@ -194,9 +202,10 @@ public function render_icon_url( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_form_title( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); - $this->render_field_description( __( 'Title used on the Auth0 login form', 'wp-auth0' ) ); + public function render_form_title($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); + $this->render_field_description(esc_html__('Title used on the Auth0 login form', 'wp-auth0')); } /** @@ -208,10 +217,11 @@ public function render_form_title( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_gravatar( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_gravatar($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Automatically display an avatar (from Gravatar) on the Auth0 login form', 'wp-auth0' ) + esc_html__('Automatically display an avatar (from Gravatar) on the Auth0 login form', 'wp-auth0') ); } @@ -224,7 +234,8 @@ public function render_gravatar( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_username_style( $args = [] ) { + public function render_username_style($args = []) + { $this->render_radio_buttons( [ [ @@ -236,11 +247,11 @@ public function render_username_style( $args = [] ) { ], $args['label_for'], $args['opt_name'], - $this->options->get( $args['opt_name'], '' ) + $this->options->get($args['opt_name'], '') ); $this->render_field_description( - __( 'To allow the user to use either email or username to login, leave this as "Auto." ', 'wp-auth0' ) . - __( 'Only database connections that require a username will allow username logins', 'wp-auth0' ) + esc_html__('To allow the user to use either email or username to login, leave this as "Auto." ', 'wp-auth0') . + esc_html__('Only database connections that require a username will allow username logins', 'wp-auth0') ); } @@ -253,14 +264,15 @@ public function render_username_style( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_primary_color( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'] ); + public function render_primary_color($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Primary color for the Auth0 login form in hex format. ', 'wp-auth0' ) . - $this->get_docs_link( - 'libraries/lock/v11/configuration#primarycolor-string-', - __( 'More information on this settings', 'wp-auth0' ) - ) + esc_html__('Primary color for the Auth0 login form in hex format. ', 'wp-auth0') . + $this->get_docs_link( + 'libraries/lock/v11/configuration#primarycolor-string-', + esc_html__('More information on this settings', 'wp-auth0') + ) ); } @@ -273,11 +285,12 @@ public function render_primary_color( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_extra_conf( $args = [] ) { - $this->render_textarea_field( $args['label_for'], $args['opt_name'] ); + public function render_extra_conf($args = []) + { + $this->render_textarea_field($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Valid JSON for Lock options configuration; will override all options set elsewhere. ', 'wp-auth0' ) . - $this->get_docs_link( 'libraries/lock/customization', 'See options and examples' ) + esc_html__('Valid JSON for Lock options configuration; will override all options set elsewhere. ', 'wp-auth0') . + $this->get_docs_link('libraries/lock/customization', 'See options and examples') ); } @@ -288,36 +301,37 @@ public function render_extra_conf( $args = [] ) { * * @return array */ - public function basic_validation( array $input ) { - $input['passwordless_enabled'] = $this->sanitize_switch_val( $input['passwordless_enabled'] ?? null ); + public function basic_validation(array $input) + { + $input['passwordless_enabled'] = $this->sanitize_switch_val($input['passwordless_enabled'] ?? null); - $input['icon_url'] = esc_url_raw( $this->sanitize_text_val( $input['icon_url'] ?? null ) ); - if ( ! empty( $input['icon_url'] ) && ! filter_var( $input['icon_url'], FILTER_VALIDATE_URL ) ) { - $input['icon_url'] = $this->options->get( 'icon_url' ); - self::add_validation_error( __( 'The Icon URL used is not valid.', 'wp-auth0' ) ); + $input['icon_url'] = esc_url_raw($this->sanitize_text_val($input['icon_url'] ?? null)); + if (!empty($input['icon_url']) && !filter_var($input['icon_url'], FILTER_VALIDATE_URL)) { + $input['icon_url'] = $this->options->get('icon_url'); + self::add_validation_error(esc_html__('The Icon URL used is not valid.', 'wp-auth0')); } - $input['form_title'] = $this->sanitize_text_val( $input['form_title'] ?? null ); - $input['gravatar'] = $this->sanitize_switch_val( $input['gravatar'] ?? null ); - $input['username_style'] = $this->sanitize_text_val( $input['username_style'] ?? null ); - $input['primary_color'] = $this->sanitize_text_val( $input['primary_color'] ?? null ); + $input['form_title'] = $this->sanitize_text_val($input['form_title'] ?? null); + $input['gravatar'] = $this->sanitize_switch_val($input['gravatar'] ?? null); + $input['username_style'] = $this->sanitize_text_val($input['username_style'] ?? null); + $input['primary_color'] = $this->sanitize_text_val($input['primary_color'] ?? null); - $input['extra_conf'] = $this->sanitize_text_val( $input['extra_conf'] ?? null ); - if ( ! empty( $input['extra_conf'] ) && ! json_decode( $input['extra_conf'] ) ) { - $input['extra_conf'] = $this->options->get( 'extra_conf', '' ); - $error = __( 'The Extra Settings parameter should be a valid JSON object.', 'wp-auth0' ); - self::add_validation_error( $error ); + $input['extra_conf'] = $this->sanitize_text_val($input['extra_conf'] ?? null); + if (!empty($input['extra_conf']) && !json_decode($input['extra_conf'])) { + $input['extra_conf'] = $this->options->get('extra_conf', ''); + $error = esc_html__('The Extra Settings parameter should be a valid JSON object.', 'wp-auth0'); + self::add_validation_error($error); } - $input['custom_cdn_url'] = $this->sanitize_switch_val( $input['custom_cdn_url'] ?? null ); + $input['custom_cdn_url'] = $this->sanitize_switch_val($input['custom_cdn_url'] ?? null); - $input['cdn_url'] = esc_url_raw( $this->sanitize_text_val( $input['cdn_url'] ?? null ) ); - if ( $input['custom_cdn_url'] && ! filter_var( $input['cdn_url'], FILTER_VALIDATE_URL ) ) { - $input['cdn_url'] = $this->options->get( 'cdn_url', WPA0_LOCK_CDN_URL ); - self::add_validation_error( __( 'The Custom Lock JS URL used is not valid.', 'wp-auth0' ) ); + $input['cdn_url'] = esc_url_raw($this->sanitize_text_val($input['cdn_url'] ?? null)); + if ($input['custom_cdn_url'] && !filter_var($input['cdn_url'], FILTER_VALIDATE_URL)) { + $input['cdn_url'] = $this->options->get('cdn_url', WPA0_LOCK_CDN_URL); + self::add_validation_error(esc_html__('The Custom Lock JS URL used is not valid.', 'wp-auth0')); } - $input['lock_connections'] = $this->sanitize_text_val( $input['lock_connections'] ?? null ); + $input['lock_connections'] = $this->sanitize_text_val($input['lock_connections'] ?? null); return $input; } diff --git a/lib/admin/WP_Auth0_Admin_Basic.php b/lib/admin/WP_Auth0_Admin_Basic.php index f4d0aafec..0489a4b65 100755 --- a/lib/admin/WP_Auth0_Admin_Basic.php +++ b/lib/admin/WP_Auth0_Admin_Basic.php @@ -1,4 +1,5 @@ __( 'Domain', 'wp-auth0' ), + 'name' => esc_html__('Domain', 'wp-auth0'), 'opt' => 'domain', 'id' => 'wpa0_domain', 'function' => 'render_domain', ], [ - 'name' => __( 'Custom Domain', 'wp-auth0' ), + 'name' => esc_html__('Custom Domain', 'wp-auth0'), 'opt' => 'custom_domain', 'id' => 'wpa0_custom_domain', 'function' => 'render_custom_domain', ], [ - 'name' => __( 'Client ID', 'wp-auth0' ), + 'name' => esc_html__('Client ID', 'wp-auth0'), 'opt' => 'client_id', 'id' => 'wpa0_client_id', 'function' => 'render_client_id', ], [ - 'name' => __( 'Client Secret', 'wp-auth0' ), + 'name' => esc_html__('Client Secret', 'wp-auth0'), 'opt' => 'client_secret', 'id' => 'wpa0_client_secret', 'function' => 'render_client_secret', ], [ - 'name' => __( 'Organization', 'wp-auth0' ), + 'name' => esc_html__('Organization', 'wp-auth0'), 'opt' => 'organization', 'id' => 'wpa0_organization', 'function' => 'render_organization', ], [ - 'name' => __( 'JWT Signature Algorithm', 'wp-auth0' ), + 'name' => esc_html__('JWT Signature Algorithm', 'wp-auth0'), 'opt' => 'client_signing_algorithm', 'id' => 'wpa0_client_signing_algorithm', 'function' => 'render_client_signing_algorithm', ], [ - 'name' => __( 'JWKS Cache Time (in minutes)', 'wp-auth0' ), + 'name' => esc_html__('JWKS Cache Time (in minutes)', 'wp-auth0'), 'opt' => 'cache_expiration', 'id' => 'wpa0_cache_expiration', 'function' => 'render_cache_expiration', ], [ - 'name' => __( 'Original Login Form on wp-login.php', 'wp-auth0' ), + 'name' => esc_html__('Original Login Form on wp-login.php', 'wp-auth0'), 'opt' => 'wordpress_login_enabled', 'id' => 'wpa0_login_enabled', 'function' => 'render_allow_wordpress_login', ], [ - 'name' => __( 'Allow Signups', 'wp-auth0' ), + 'name' => esc_html__('Allow Signups', 'wp-auth0'), 'id' => 'wpa0_allow_signup', 'function' => 'render_allow_signup', ], ]; - $this->init_option_section( '', 'basic', $options ); + $this->init_option_section('', 'basic', $options); } /** @@ -90,13 +93,14 @@ public function init() { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_domain( $args = [] ) { + public function render_domain($args = []) + { - $style = $this->options->get( $args['opt_name'] ) ? '' : self::ERROR_FIELD_STYLE; - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', 'your-tenant.auth0.com', $style ); + $style = $this->options->get($args['opt_name']) ? '' : self::ERROR_FIELD_STYLE; + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', 'your-tenant.auth0.com', $style); $this->render_field_description( - __( 'Auth0 Domain, found in your Application settings in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'applications' ) + esc_html__('Auth0 Domain, found in your Application settings in the ', 'wp-auth0') . + $this->get_dashboard_link('applications') ); } @@ -111,12 +115,13 @@ public function render_domain( $args = [] ) { * * @since 3.7.0 */ - public function render_custom_domain( $args = [] ) { + public function render_custom_domain($args = []) + { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', 'login.yourdomain.com' ); + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', 'login.yourdomain.com'); $this->render_field_description( - __( 'Custom login domain. ', 'wp-auth0' ) . - $this->get_docs_link( 'custom-domains', __( 'More information here', 'wp-auth0' ) ) + esc_html__('Custom login domain. ', 'wp-auth0') . + $this->get_docs_link('custom-domains', esc_html__('More information here', 'wp-auth0')) ); } @@ -129,13 +134,14 @@ public function render_custom_domain( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_client_id( $args = [] ) { + public function render_client_id($args = []) + { - $style = $this->options->get( $args['opt_name'] ) ? '' : self::ERROR_FIELD_STYLE; - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', '', $style ); + $style = $this->options->get($args['opt_name']) ? '' : self::ERROR_FIELD_STYLE; + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', '', $style); $this->render_field_description( - __( 'Client ID, found in your Application settings in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'applications' ) + esc_html__('Client ID, found in your Application settings in the ', 'wp-auth0') . + $this->get_dashboard_link('applications') ); } @@ -148,13 +154,14 @@ public function render_client_id( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_client_secret( $args = [] ) { + public function render_client_secret($args = []) + { - $style = $this->options->get( $args['opt_name'] ) ? '' : self::ERROR_FIELD_STYLE; - $this->render_text_field( $args['label_for'], $args['opt_name'], 'password', '', $style ); + $style = $this->options->get($args['opt_name']) ? '' : self::ERROR_FIELD_STYLE; + $this->render_text_field($args['label_for'], $args['opt_name'], 'password', '', $style); $this->render_field_description( - __( 'Client Secret, found in your Application settings in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'applications' ) + esc_html__('Client Secret, found in your Application settings in the ', 'wp-auth0') . + $this->get_dashboard_link('applications') ); } @@ -167,12 +174,13 @@ public function render_client_secret( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_organization( $args = [] ) { + public function render_organization($args = []) + { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'text', '' ); + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', ''); $this->render_field_description( - __( 'Optional. Organization Id, found in your Organizations settings in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'applications' ) + esc_html__('Optional. Organization Id, found in your Organizations settings in the ', 'wp-auth0') . + $this->get_dashboard_link('applications') ); } @@ -185,9 +193,10 @@ public function render_organization( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_client_signing_algorithm( $args = [] ) { + public function render_client_signing_algorithm($args = []) + { - $curr_value = $this->options->get( $args['opt_name'] ) ?: WP_Auth0_Api_Client::DEFAULT_CLIENT_ALG; + $curr_value = $this->options->get($args['opt_name']) ?: WP_Auth0_Api_Client::DEFAULT_CLIENT_ALG; $this->render_radio_buttons( self::ALLOWED_ID_TOKEN_ALGS, $args['label_for'], @@ -195,9 +204,9 @@ public function render_client_signing_algorithm( $args = [] ) { $curr_value ); $this->render_field_description( - __( 'This value can be found the Application settings in the ', 'wp-auth0' ) . - $this->get_dashboard_link( 'applications' ) . - __( ' under Show Advanced Settings > OAuth > "JsonWebToken Signature Algorithm"', 'wp-auth0' ) + esc_html__('This value can be found the Application settings in the ', 'wp-auth0') . + $this->get_dashboard_link('applications') . + esc_html__(' under Show Advanced Settings > OAuth > "JsonWebToken Signature Algorithm"', 'wp-auth0') ); } @@ -210,22 +219,23 @@ public function render_client_signing_algorithm( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_cache_expiration( $args = [] ) { + public function render_cache_expiration($args = []) + { - $this->render_text_field( $args['label_for'], $args['opt_name'], 'number' ); - printf( + $this->render_text_field($args['label_for'], $args['opt_name'], 'number'); + echo wp_kses(sprintf( ' ', - __( 'Delete Cache', 'wp-auth0' ) - ); - $this->render_field_description( __( 'JWKS cache expiration in minutes (use 0 for no caching)', 'wp-auth0' ) ); - $domain = $this->options->get( 'domain' ); - if ( $domain ) { + esc_html__('Delete Cache', 'wp-auth0') + ), ['button' => ['id' => true, 'class' => true]]); + $this->render_field_description(esc_html__('JWKS cache expiration in minutes (use 0 for no caching)', 'wp-auth0')); + $domain = $this->options->get('domain'); + if ($domain) { $this->render_field_description( - sprintf( + wp_kses(sprintf( '%s', $domain, - __( 'View your JWKS here', 'wp-auth0' ) - ) + esc_html__('View your JWKS here', 'wp-auth0') + ), ['a' => ['href' => true, 'target' => true]]) ); } } @@ -239,48 +249,54 @@ public function render_cache_expiration( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_allow_wordpress_login( $args = [] ) { + public function render_allow_wordpress_login($args = []) + { - $isset_desc = sprintf( + $isset_desc = wp_kses(sprintf( '%s?wle', wp_login_url(), wp_login_url() - ); - $code_desc = '' . __( 'Save settings to generate URL.', 'wp-auth0' ) . ''; - $wle_code = $this->options->get( 'wle_code' ); - if ( $wle_code ) { - $code_desc = str_replace( '?wle', '?wle=' . $wle_code, $isset_desc ); + ), ['code' => ['class' => true], 'a' => ['href' => true, 'target' => true]]); + + $code_desc = wp_kses('' . esc_html__('Save settings to generate URL.', 'wp-auth0') . '', ['code' => ['class' => true]]); + $wle_code = $this->options->get('wle_code'); + + if ($wle_code) { + $code_desc = str_replace('?wle', '?wle=' . $wle_code, $isset_desc); } + $buttons = [ [ - 'label' => __( 'Never', 'wp-auth0' ), + 'label' => esc_html__('Never', 'wp-auth0'), 'value' => 'no', ], [ - 'label' => __( 'Via a link under the Auth0 form', 'wp-auth0' ), + 'label' => esc_html__('Via a link under the Auth0 form', 'wp-auth0'), 'value' => 'link', - 'desc' => __( 'URL is the same as below', 'wp-auth0' ), + 'desc' => esc_html__('URL is the same as below', 'wp-auth0'), ], [ - 'label' => __( 'When "wle" query parameter is present', 'wp-auth0' ), + 'label' => esc_html__('When "wle" query parameter is present', 'wp-auth0'), 'value' => 'isset', 'desc' => $isset_desc, ], [ - 'label' => __( 'When "wle" query parameter contains specific code', 'wp-auth0' ), + 'label' => esc_html__('When "wle" query parameter contains specific code', 'wp-auth0'), 'value' => 'code', 'desc' => $code_desc, ], ]; - printf( + + echo wp_kses(sprintf( '
%s.

', - __( 'Logins and signups using the original form will NOT be pushed to Auth0', 'wp-auth0' ) - ); + esc_html__('Logins and signups using the original form will NOT be pushed to Auth0', 'wp-auth0') + ), ['div' => ['class' => true], 'span' => ['class' => true], 'br' => []]); + $this->render_radio_buttons( $buttons, $args['label_for'], $args['opt_name'], - $this->options->get( $args['opt_name'] ), + $this->options->get($args['opt_name']), true ); } @@ -292,21 +308,22 @@ public function render_allow_wordpress_login( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_allow_signup() { + public function render_allow_signup() + { - if ( is_multisite() ) { - $settings_text = __( + if (is_multisite()) { + $settings_text = esc_html__( '"Allow new registrations" in the Network Admin > Settings > Network Settings', 'wp-auth0' ); } else { - $settings_text = __( '"Anyone can register" in the WordPress General Settings', 'wp-auth0' ); + $settings_text = esc_html__('"Anyone can register" in the WordPress General Settings', 'wp-auth0'); } $allow_signup = $this->options->is_wp_registration_enabled(); $this->render_field_description( - __( 'Signups are currently ', 'wp-auth0' ) . '' . - ( $allow_signup ? __( 'enabled', 'wp-auth0' ) : __( 'disabled', 'wp-auth0' ) ) . - '' . __( ' by this setting ', 'wp-auth0' ) . $settings_text + esc_html__('Signups are currently ', 'wp-auth0') . '' . + ($allow_signup ? esc_html__('enabled', 'wp-auth0') : esc_html__('disabled', 'wp-auth0')) . + '' . esc_html__(' by this setting ', 'wp-auth0') . $settings_text ); } @@ -317,48 +334,49 @@ public function render_allow_signup() { * * @return array */ - public function basic_validation( array $input ) { + public function basic_validation(array $input) + { - if ( wp_cache_get( 'doing_db_update', WPA0_CACHE_GROUP ) ) { + if (wp_cache_get('doing_db_update', WPA0_CACHE_GROUP)) { return $input; } - $input['domain'] = $this->sanitize_text_val( $input['domain'] ?? null ); - if ( empty( $input['domain'] ) ) { - $this->add_validation_error( __( 'You need to specify a domain', 'wp-auth0' ) ); + $input['domain'] = $this->sanitize_text_val($input['domain'] ?? null); + if (empty($input['domain'])) { + $this->add_validation_error(esc_html__('You need to specify a domain', 'wp-auth0')); } - $input['custom_domain'] = $this->sanitize_text_val( $input['custom_domain'] ?? null ); + $input['custom_domain'] = $this->sanitize_text_val($input['custom_domain'] ?? null); - $input['client_id'] = $this->sanitize_text_val( $input['client_id'] ?? null ); - if ( empty( $input['client_id'] ) ) { - $this->add_validation_error( __( 'You need to specify a Client ID', 'wp-auth0' ) ); + $input['client_id'] = $this->sanitize_text_val($input['client_id'] ?? null); + if (empty($input['client_id'])) { + $this->add_validation_error(esc_html__('You need to specify a Client ID', 'wp-auth0')); } - $input['client_secret'] = $this->sanitize_text_val( $input['client_secret'] ?? null ); - if ( __( '[REDACTED]', 'wp-auth0' ) === $input['client_secret'] ) { + $input['client_secret'] = $this->sanitize_text_val($input['client_secret'] ?? null); + if (esc_html__('[REDACTED]', 'wp-auth0') === $input['client_secret']) { // The field is loaded with "[REDACTED]" so if that value is saved, we keep the existing secret. - $input['client_secret'] = $this->options->get( 'client_secret' ); + $input['client_secret'] = $this->options->get('client_secret'); } - if ( empty( $input['client_secret'] ) ) { - $this->add_validation_error( __( 'You need to specify a Client Secret', 'wp-auth0' ) ); + if (empty($input['client_secret'])) { + $this->add_validation_error(esc_html__('You need to specify a Client Secret', 'wp-auth0')); } - $input['organization'] = $this->sanitize_text_val( $input['organization'] ?? null ); + $input['organization'] = $this->sanitize_text_val($input['organization'] ?? null); $id_token_alg = $input['client_signing_algorithm'] ?? null; - if ( ! in_array( $id_token_alg, self::ALLOWED_ID_TOKEN_ALGS ) ) { - $input['client_signing_algorithm'] = $this->options->get_default( 'client_signing_algorithm' ); + if (!in_array($id_token_alg, self::ALLOWED_ID_TOKEN_ALGS)) { + $input['client_signing_algorithm'] = $this->options->get_default('client_signing_algorithm'); } - $input['cache_expiration'] = absint( $input['cache_expiration'] ?? 0 ); + $input['cache_expiration'] = absint($input['cache_expiration'] ?? 0); $wle = $input['wordpress_login_enabled'] ?? null; - if ( ! in_array( $wle, [ 'link', 'isset', 'code', 'no' ] ) ) { - $input['wordpress_login_enabled'] = $this->options->get_default( 'wordpress_login_enabled' ); + if (!in_array($wle, ['link', 'isset', 'code', 'no'])) { + $input['wordpress_login_enabled'] = $this->options->get_default('wordpress_login_enabled'); } - $input['wle_code'] = $this->options->get( 'wle_code' ) ?: wp_auth0_generate_token( 24 ); + $input['wle_code'] = $this->options->get('wle_code') ?: wp_auth0_generate_token(24); return $input; } diff --git a/lib/admin/WP_Auth0_Admin_Features.php b/lib/admin/WP_Auth0_Admin_Features.php index 464a4ea6e..e84145de8 100644 --- a/lib/admin/WP_Auth0_Admin_Features.php +++ b/lib/admin/WP_Auth0_Admin_Features.php @@ -1,4 +1,5 @@ __( 'Universal Login Page', 'wp-auth0' ), + 'name' => esc_html__('Universal Login Page', 'wp-auth0'), 'opt' => 'auto_login', 'id' => 'wpa0_auto_login', 'function' => 'render_auto_login', ], [ - 'name' => __( 'Auto Login Parameters', 'wp-auth0' ), + 'name' => esc_html__('Auto Login Parameters', 'wp-auth0'), 'opt' => 'auto_login_params', 'id' => 'wpa0_auto_login_params', 'function' => 'render_auto_login_params', ], [ - 'name' => __( 'Auto Login Method', 'wp-auth0' ), + 'name' => esc_html__('Auto Login Method', 'wp-auth0'), 'opt' => 'auto_login_method', 'id' => 'wpa0_auto_login_method', 'function' => 'render_auto_login_method', ], [ - 'name' => __( 'Auth0 Logout', 'wp-auth0' ), + 'name' => esc_html__('Auth0 Logout', 'wp-auth0'), 'opt' => 'singlelogout', 'id' => 'wpa0_singlelogout', 'function' => 'render_singlelogout', ], [ - 'name' => __( 'Override WordPress Avatars', 'wp-auth0' ), + 'name' => esc_html__('Override WordPress Avatars', 'wp-auth0'), 'opt' => 'override_wp_avatars', 'id' => 'wpa0_override_wp_avatars', 'function' => 'render_override_wp_avatars', ], ]; - $this->init_option_section( '', 'features', $options ); + $this->init_option_section('', 'features', $options); } /** @@ -65,10 +68,11 @@ public function init() { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_singlelogout( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_singlelogout($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Turning this on will log users out of Auth0 when they log out of WordPress.', 'wp-auth0' ) + esc_html__('Turning this on will log users out of Auth0 when they log out of WordPress.', 'wp-auth0') ); } @@ -81,13 +85,14 @@ public function render_singlelogout( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_auto_login( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'], 'wpa0_auto_login_options' ); + public function render_auto_login($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name'], 'wpa0_auto_login_options'); $this->render_field_description( - __( 'Use the Universal Login Page (ULP) for authentication and SSO. ', 'wp-auth0' ) . - __( 'When turned on, wp-login.php will redirect to the hosted login page. ', 'wp-auth0' ) . - __( 'When turned off, wp-login.php will show an embedded login form. ', 'wp-auth0' ) . - $this->get_docs_link( 'guides/login/universal-vs-embedded', __( 'More on ULP vs embedded here', 'wp-auth0' ) ) + esc_html__('Use the Universal Login Page (ULP) for authentication and SSO. ', 'wp-auth0') . + wp_kses(__('When turned on, wp-login.php will redirect to the hosted login page. ', 'wp-auth0'), ['code' => []]) . + wp_kses(__('When turned off, wp-login.php will show an embedded login form. ', 'wp-auth0'), ['code' => []]) . + $this->get_docs_link('guides/login/universal-vs-embedded', esc_html__('More on ULP vs embedded here', 'wp-auth0')) ); } @@ -100,12 +105,13 @@ public function render_auto_login( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_auto_login_params( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'], '', '', '', 'wpa0_auto_login_options' ); + public function render_auto_login_params($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', '', '', 'wpa0_auto_login_options'); $this->render_field_description( - __( 'Optional. Here you can specify additional parameters to pass to the the Universal Login Page (ULP) during authentication. ', 'wp-auth0' ) . - __( 'For example, you can specify screen_hint=signup or prompt=login parameters here. ', 'wp-auth0' ) . - $this->get_docs_link( 'docs/login/universal-login/new-experience', __( 'Learn more about available ULP parameters here', 'wp-auth0' ) ) + esc_html__('Optional. Here you can specify additional parameters to pass to the the Universal Login Page (ULP) during authentication. ', 'wp-auth0') . + wp_kses(__('For example, you can specify screen_hint=signup or prompt=login parameters here. ', 'wp-auth0'), ['code' => []]) . + $this->get_docs_link('docs/login/universal-login/new-experience', esc_html__('Learn more about available ULP parameters here', 'wp-auth0')) ); } @@ -118,16 +124,17 @@ public function render_auto_login_params( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_auto_login_method( $args = [] ) { - $this->render_text_field( $args['label_for'], $args['opt_name'], '', '', '', 'wpa0_auto_login_options' ); + public function render_auto_login_method($args = []) + { + $this->render_text_field($args['label_for'], $args['opt_name'], 'text', '', '', 'wpa0_auto_login_options'); $this->render_field_description( - __( 'Enter a name here to automatically use a single, specific connection to login . ', 'wp-auth0' ) . - sprintf( - // translators: Placeholder is an HTML link to the Auth0 dashboard. - __( 'Find the method name to use under Connections > [Connection Type] in your %s. ', 'wp-auth0' ), - $this->get_dashboard_link() - ) . - __( 'Click the expand icon and use the value in the "Name" field (like "google-oauth2")', 'wp-auth0' ) + esc_html__('Enter a name here to automatically use a single, specific connection to login . ', 'wp-auth0') . + wp_kses(sprintf( + // translators: Placeholder is an HTML link to the Auth0 dashboard. + esc_html__('Find the method name to use under Connections > [Connection Type] in your %s. ', 'wp-auth0'), + $this->get_dashboard_link() + ), ['a' => ['href' => true, 'target' => true]]) . + esc_html__('Click the expand icon and use the value in the "Name" field (like "google-oauth2")', 'wp-auth0') ); } @@ -140,10 +147,11 @@ public function render_auto_login_method( $args = [] ) { * @see WP_Auth0_Admin_Generic::init_option_section() * @see add_settings_field() */ - public function render_override_wp_avatars( $args = [] ) { - $this->render_switch( $args['label_for'], $args['opt_name'] ); + public function render_override_wp_avatars($args = []) + { + $this->render_switch($args['label_for'], $args['opt_name']); $this->render_field_description( - __( 'Overrides the WordPress avatar with the Auth0 profile avatar', 'wp-auth0' ) + esc_html__('Overrides the WordPress avatar with the Auth0 profile avatar', 'wp-auth0') ); } @@ -154,12 +162,13 @@ public function render_override_wp_avatars( $args = [] ) { * * @return array */ - public function basic_validation( array $input ) { - $input['auto_login'] = $this->sanitize_switch_val( $input['auto_login'] ?? null ); - $input['auto_login_params'] = $this->sanitize_query_parameters( $input['auto_login_params'] ?? null ); - $input['auto_login_method'] = $this->sanitize_text_val( $input['auto_login_method'] ?? null ); - $input['singlelogout'] = $this->sanitize_switch_val( $input['singlelogout'] ?? null ); - $input['override_wp_avatars'] = $this->sanitize_switch_val( $input['override_wp_avatars'] ?? null ); + public function basic_validation(array $input) + { + $input['auto_login'] = $this->sanitize_switch_val($input['auto_login'] ?? null); + $input['auto_login_params'] = $this->sanitize_query_parameters($input['auto_login_params'] ?? null); + $input['auto_login_method'] = $this->sanitize_text_val($input['auto_login_method'] ?? null); + $input['singlelogout'] = $this->sanitize_switch_val($input['singlelogout'] ?? null); + $input['override_wp_avatars'] = $this->sanitize_switch_val($input['override_wp_avatars'] ?? null); return $input; } } diff --git a/lib/admin/WP_Auth0_Admin_Generic.php b/lib/admin/WP_Auth0_Admin_Generic.php index 589367d89..de01e0e8b 100644 --- a/lib/admin/WP_Auth0_Admin_Generic.php +++ b/lib/admin/WP_Auth0_Admin_Generic.php @@ -1,6 +1,7 @@ options = $options; $this->_option_name = $options->get_options_name(); } @@ -34,8 +36,9 @@ public function __construct( WP_Auth0_Options $options ) { * @param string $id - settings screen id * @param array $options - array of settings fields */ - protected function init_option_section( $section_name, $id, $options ) { - $options_name = $this->_option_name . '_' . strtolower( $id ); + protected function init_option_section($section_name, $id, $options) + { + $options_name = $this->_option_name . '_' . strtolower($id); $section_id = "wp_auth0_{$id}_settings_section"; add_settings_section( @@ -45,12 +48,12 @@ protected function init_option_section( $section_name, $id, $options ) { $options_name ); - $options = apply_filters( 'auth0_settings_fields', $options, $id ); + $options = apply_filters('auth0_settings_fields', $options, $id); - foreach ( $options as $setting ) { - $callback = function_exists( $setting['function'] ) + foreach ($options as $setting) { + $callback = function_exists($setting['function']) ? $setting['function'] - : [ $this, $setting['function'] ]; + : [$this, $setting['function']]; add_settings_field( $setting['id'], @@ -60,16 +63,17 @@ protected function init_option_section( $section_name, $id, $options ) { $section_id, [ 'label_for' => $setting['id'], - 'opt_name' => isset( $setting['opt'] ) ? $setting['opt'] : null, + 'opt_name' => isset($setting['opt']) ? $setting['opt'] : null, ] ); } } - public function input_validator( $input ) { + public function input_validator($input) + { - foreach ( $this->actions_middlewares as $action ) { - $input = $this->$action( $input ); + foreach ($this->actions_middlewares as $action) { + $input = $this->$action($input); } return $input; @@ -81,7 +85,8 @@ public function input_validator( $input ) { * @param string $error - Translated error message. * @param string $type - Notice type, "error" by default or "updated". */ - protected function add_validation_error( $error, $type = 'error' ) { + protected function add_validation_error($error, $type = 'error') + { add_settings_error( $this->_option_name, $this->_option_name, @@ -97,22 +102,25 @@ protected function add_validation_error( $error, $type = 'error' ) { * @param string $input_name - input name attribute * @param string $expand_id - id of a field that should be hidden until this switch is active */ - protected function render_switch( $id, $input_name, $expand_id = '' ) { - $value = $this->options->get( $input_name ); - if ( $field_is_const = $this->options->has_constant_val( $input_name ) ) { - $this->render_const_notice( $input_name ); + protected function render_switch($id, $input_name, $expand_id = '') + { + $value = $this->options->get($input_name); + + if ($field_is_const = $this->options->has_constant_val($input_name)) { + $this->render_const_notice($input_name); } - printf( + + echo wp_kses(sprintf( '
', - esc_attr( $this->_option_name ), - esc_attr( $input_name ), - esc_attr( $id ), - ! empty( $expand_id ) ? esc_attr( $expand_id ) : '', - checked( empty( $value ), false, false ), + esc_attr($this->_option_name), + esc_attr($input_name), + esc_attr($id), + !empty($expand_id) ? esc_attr($expand_id) : '', + checked(empty($value), false, false), $field_is_const ? 'disabled' : '', - esc_attr( $id ) - ); + esc_attr($id) + ), ['div' => ['class' => true], 'input' => ['type' => true, 'name' => true, 'id' => true, 'data-expand' => true, 'value' => true, 'checked' => true, 'disabled' => true], 'label' => ['for' => true]]); } /** @@ -125,29 +133,30 @@ protected function render_switch( $id, $input_name, $expand_id = '' ) { * @param string $style - inline CSS * @param string $grouping - A string representing a one or more items in a grouping of related settings that will have their visibility toggled by a switch state. */ - protected function render_text_field( $id, $input_name, $type = 'text', $placeholder = '', $style = '', $grouping = '' ) { - $value = $this->options->get( $input_name ); + protected function render_text_field($id, $input_name, $type = 'text', $placeholder = '', $style = '', $grouping = '') + { + $value = $this->options->get($input_name); // Secure fields are not output by default; validation keeps last value if a new one is not entered - if ( 'password' === $type ) { - $value = empty( $value ) ? '' : __( '[REDACTED]', 'wp-auth0' ); + if ('password' === $type) { + $value = empty($value) ? '' : esc_html__('[REDACTED]', 'wp-auth0'); $type = 'text'; } - if ( $field_is_const = $this->options->has_constant_val( $input_name ) ) { - $this->render_const_notice( $input_name ); + if ($field_is_const = $this->options->has_constant_val($input_name)) { + $this->render_const_notice($input_name); } - printf( - '', - esc_attr( $grouping ), - esc_attr( $type ), - esc_attr( $this->_option_name ), - esc_attr( $input_name ), - esc_attr( $id ), - esc_attr( $value ), - $placeholder ? esc_attr( $placeholder ) : '', - $style ? esc_attr( $style ) : '', + echo wp_kses(sprintf( + '', + esc_attr($grouping), + esc_attr($type), + esc_attr($this->_option_name), + esc_attr($input_name), + esc_attr($id), + esc_attr($value), + $placeholder ? esc_attr($placeholder) : '', + $style ? esc_attr($style) : '', $field_is_const ? 'disabled' : '' - ); + ), ['input' => ['data-group' => true, 'type' => true, 'name' => true, 'id' => true, 'value' => true, 'placeholder' => true, 'style' => true, 'disabled' => true]]); } /** @@ -156,20 +165,21 @@ protected function render_text_field( $id, $input_name, $type = 'text', $placeho * @param string $id - input id attribute * @param string $input_name - input name attribute */ - protected function render_textarea_field( $id, $input_name ) { - $value = $this->options->get( $input_name ); - if ( $field_is_const = $this->options->has_constant_val( $input_name ) ) { - $this->render_const_notice( $input_name ); + protected function render_textarea_field($id, $input_name) + { + $value = $this->options->get($input_name); + if ($field_is_const = $this->options->has_constant_val($input_name)) { + $this->render_const_notice($input_name); } - printf( + echo wp_kses(sprintf( '', - esc_attr( $this->_option_name ), - esc_attr( $input_name ), - esc_attr( $id ), + esc_attr($this->_option_name), + esc_attr($input_name), + esc_attr($id), $this->_textarea_rows, $field_is_const ? 'disabled' : '', - esc_textarea( $value ) - ); + esc_textarea($value) + ), ['textarea' => ['name' => true, 'id' => true, 'rows' => true, 'class' => true, 'disabled' => true]]); } /** @@ -181,28 +191,31 @@ protected function render_textarea_field( $id, $input_name ) { * @param int|float|string $curr_value - Current option value. * @param bool $vert - True to use vertical orientation for buttons. */ - protected function render_radio_buttons( array $buttons, $id, $input_name, $curr_value, $vert = false ) { - if ( $field_is_const = $this->options->has_constant_val( $input_name ) ) { - $this->render_const_notice( $input_name ); + protected function render_radio_buttons(array $buttons, $id, $input_name, $curr_value, $vert = false) + { + if ($field_is_const = $this->options->has_constant_val($input_name)) { + $this->render_const_notice($input_name); } - foreach ( $buttons as $index => $button ) { + + foreach ($buttons as $index => $button) { $id_attr = $id . '_' . $index; - $label = is_array( $button ) ? $button['label'] : ucfirst( $button ); - $value = is_array( $button ) ? $button['value'] : $button; - $desc = isset( $button['desc'] ) ? '

' . $button['desc'] . '

' : ''; - printf( + $label = is_array($button) ? $button['label'] : ucfirst($button); + $value = is_array($button) ? $button['value'] : $button; + $desc = isset($button['desc']) ? '

' . $button['desc'] . '

' : ''; + + echo wp_kses(sprintf( '%s %s', $vert ? '
' : '', - esc_attr( $id_attr ), - esc_attr( $this->_option_name ), - esc_attr( $input_name ), - esc_attr( $id_attr ), - esc_attr( $value ), - checked( $value === $curr_value, true, false ), + esc_attr($id_attr), + esc_attr($this->_option_name), + esc_attr($input_name), + esc_attr($id_attr), + esc_attr($value), + checked($value === $curr_value, true, false), $field_is_const ? 'disabled' : '', - sanitize_text_field( $label ), + sanitize_text_field($label), $vert ? $desc . '
' : '' - ); + ), ['label' => ['for' => true], 'input' => ['type' => true, 'name' => true, 'id' => true, 'value' => true, 'checked' => true, 'disabled' => true], 'div' => ['class' => true], 'code' => ['class' => true], 'a' => ['href' => true, 'target' => true], 'span' => ['class' => true], 'br' => []]); } } @@ -211,9 +224,10 @@ protected function render_radio_buttons( array $buttons, $id, $input_name, $curr * * @param string $text - description text to display */ - protected function render_field_description( $text ) { - $period = ! in_array( $text[ strlen( $text ) - 1 ], [ '.', ':' ] ) ? '.' : ''; - printf( '
%s%s
', $text, $period ); + protected function render_field_description($text) + { + $period = !in_array($text[strlen($text) - 1], ['.', ':']) ? '.' : ''; + echo wp_kses(sprintf('
%s%s
', $text, $period), ['div' => ['class' => true], 'span' => ['class' => true], 'a' => ['href' => true, 'target' => true], 'code' => ['class' => true]]); } /** @@ -221,12 +235,13 @@ protected function render_field_description( $text ) { * * @param string $input_name - Input name for the field, used as option key. */ - protected function render_const_notice( $input_name ) { - printf( + protected function render_const_notice($input_name) + { + echo wp_kses(sprintf( '

%s %s

', - __( 'Value is set in the constant ', 'wp-auth0' ), - $this->options->get_constant_name( $input_name ) - ); + esc_html__('Value is set in the constant ', 'wp-auth0'), + $this->options->get_constant_name($input_name) + ), ['p' => ['class' => true], 'span' => ['class' => true]], ['code' => []]); } /** @@ -236,12 +251,13 @@ protected function render_const_notice( $input_name ) { * * @return string */ - protected function get_dashboard_link( $path = '' ) { - return sprintf( + protected function get_dashboard_link($path = '') + { + return wp_kses(sprintf( '%s', $path, - __( 'Auth0 dashboard', 'wp-auth0' ) - ); + esc_html__('Auth0 dashboard', 'wp-auth0') + ), ['a' => ['href' => true, 'target' => true]]); } /** @@ -252,10 +268,11 @@ protected function get_dashboard_link( $path = '' ) { * * @return string */ - protected function get_docs_link( $path, $text = '' ) { - $path = '/' === $path[0] ? substr( $path, 1 ) : $path; - $text = empty( $text ) ? __( 'here', 'wp-auth0' ) : sanitize_text_field( $text ); - return sprintf( '%s', $path, $text ); + protected function get_docs_link($path, $text = '') + { + $path = '/' === $path[0] ? substr($path, 1) : $path; + $text = empty($text) ? esc_html__('here', 'wp-auth0') : sanitize_text_field($text); + return wp_kses(sprintf('%s', $path, $text), ['a' => ['href' => true, 'target' => true]]); } /** @@ -265,33 +282,36 @@ protected function get_docs_link( $path, $text = '' ) { * * @return bool */ - protected function sanitize_switch_val( $val ) { - return in_array( $val, [ 1, '1', true ], true ) ? true : false; + protected function sanitize_switch_val($val) + { + return in_array($val, [1, '1', true], true) ? true : false; } - protected function sanitize_text_val( $val ) { - return sanitize_text_field( trim( strval( $val ) ) ); + protected function sanitize_text_val($val) + { + return sanitize_text_field(trim(strval($val))); } - protected function sanitize_query_parameters( $val ) { - $val = trim( strval( $val ) ); + protected function sanitize_query_parameters($val) + { + $val = trim(strval($val)); - if ( strlen( $val ) === 0 ) { + if (strlen($val) === 0) { return ''; } - parse_str( $val, $parsed ); + parse_str($val, $parsed); $sanitized = []; - foreach ( $parsed as $key => $value ) { - $sanitized[ $this->sanitize_text_val( $key ) ] = $this->sanitize_text_val( $value ); + foreach ($parsed as $key => $value) { + $sanitized[$this->sanitize_text_val($key)] = $this->sanitize_text_val($value); } return http_build_query( array_filter( $sanitized, - function( $var ) { - return ( $var !== null && $var !== false && trim( $var ) !== '' ); + function ($var) { + return ($var !== null && $var !== false && trim($var) !== ''); } ) ); diff --git a/lib/api/WP_Auth0_Api_Abstract.php b/lib/api/WP_Auth0_Api_Abstract.php index 15460b2df..87e4b4ed8 100644 --- a/lib/api/WP_Auth0_Api_Abstract.php +++ b/lib/api/WP_Auth0_Api_Abstract.php @@ -1,4 +1,5 @@ options = $options; // Required settings in the plugin. - $this->domain = $domain ?: $this->options->get( 'domain' ); - $this->client_id = $this->options->get( 'client_id' ); - $this->client_secret = $this->options->get( 'client_secret' ); - $this->organization = $this->options->get( 'organization' ); + $this->domain = $domain ?: $this->options->get('domain'); + $this->client_id = $this->options->get('client_id'); + $this->client_secret = $this->options->get('client_secret'); + $this->organization = $this->options->get('organization'); // Headers sent with every request. $this->headers = static::get_info_headers(); @@ -127,16 +130,17 @@ public function __construct( WP_Auth0_Options $options, $domain = null ) { * * @return array */ - public static function get_info_headers() { + public static function get_info_headers() + { $header_value = [ 'name' => 'wp-auth0', 'version' => WPA0_VERSION, 'env' => [ 'php' => phpversion(), - 'wp' => get_bloginfo( 'version' ), + 'wp' => get_bloginfo('version'), ], ]; - return [ 'Auth0-Client' => base64_encode( wp_json_encode( $header_value ) ) ]; + return ['Auth0-Client' => base64_encode(wp_json_encode($header_value))]; } /** @@ -153,7 +157,7 @@ abstract function call(); * * @return mixed */ - abstract protected function handle_response( $method ); + abstract protected function handle_response($method); /** * Set the remote path to call. @@ -162,8 +166,9 @@ abstract protected function handle_response( $method ); * * @return $this */ - protected function set_path( $path ) { - $this->remote_path = $this->clean_path( $path ); + protected function set_path($path) + { + $this->remote_path = $this->clean_path($path); return $this; } @@ -174,9 +179,10 @@ protected function set_path( $path ) { * * @return bool */ - protected function set_bearer( $scope ) { + protected function set_bearer($scope) + { - if ( ! $this->api_client_creds instanceof WP_Auth0_Api_Client_Credentials ) { + if (!$this->api_client_creds instanceof WP_Auth0_Api_Client_Credentials) { return false; } @@ -184,18 +190,18 @@ protected function set_bearer( $scope ) { $api_token = $cc_api::get_stored_token(); // No stored API token so need to get a new one. - if ( ! $api_token ) { + if (!$api_token) { $api_token = $this->api_client_creds->call(); } // No token to use, error recorded in previous steps. - if ( ! $api_token ) { + if (!$api_token) { return false; } - if ( $cc_api::check_stored_scope( $scope ) ) { + if ($cc_api::check_stored_scope($scope)) { // Scope exists, add to the header and cache. - $this->add_header( 'Authorization', 'Bearer ' . $api_token ); + $this->add_header('Authorization', 'Bearer ' . $api_token); return true; } @@ -205,7 +211,7 @@ protected function set_bearer( $scope ) { new WP_Error( 'insufficient_scope', // translators: The $scope var here is a machine term and should not be translated. - sprintf( __( 'API token does not include the scope %s.', 'wp-auth0' ), $scope ) + sprintf(esc_html__('API token does not include the scope %s.', 'wp-auth0'), $scope) ) ); @@ -219,7 +225,8 @@ protected function set_bearer( $scope ) { * * @return $this */ - protected function send_audience() { + protected function send_audience() + { $this->body['audience'] = 'https://' . $this->domain . '/api/v2/'; return $this; } @@ -229,7 +236,8 @@ protected function send_audience() { * * @return $this */ - protected function send_client_id() { + protected function send_client_id() + { $this->body['client_id'] = $this->client_id; return $this; } @@ -239,7 +247,8 @@ protected function send_client_id() { * * @return $this */ - protected function send_client_secret() { + protected function send_client_secret() + { $this->body['client_secret'] = $this->client_secret; return $this; } @@ -249,7 +258,8 @@ protected function send_client_secret() { * * @return $this */ - protected function send_organization() { + protected function send_organization() + { $this->body['organization'] = $this->organization; return $this; } @@ -262,8 +272,9 @@ protected function send_organization() { * * @return $this */ - protected function add_header( $header, $value ) { - $this->headers[ $header ] = $value; + protected function add_header($header, $value) + { + $this->headers[$header] = $value; return $this; } @@ -275,8 +286,9 @@ protected function add_header( $header, $value ) { * * @return $this */ - protected function add_body( $key, $value ) { - $this->body[ $key ] = $value; + protected function add_body($key, $value) + { + $this->body[$key] = $value; return $this; } @@ -285,7 +297,8 @@ protected function add_body( $key, $value ) { * * @return string */ - protected function build_url() { + protected function build_url() + { return 'https://' . $this->domain . '/' . $this->remote_path; } @@ -294,8 +307,9 @@ protected function build_url() { * * @return $this */ - protected function get() { - return $this->request( 'GET' ); + protected function get() + { + return $this->request('GET'); } /** @@ -303,8 +317,9 @@ protected function get() { * * @return $this */ - protected function post() { - return $this->add_header( 'Content-Type', 'application/json' )->request( 'POST' ); + protected function post() + { + return $this->add_header('Content-Type', 'application/json')->request('POST'); } /** @@ -312,8 +327,9 @@ protected function post() { * * @return $this */ - protected function delete() { - return $this->request( 'DELETE' ); + protected function delete() + { + return $this->request('DELETE'); } /** @@ -321,8 +337,9 @@ protected function delete() { * * @return $this */ - protected function patch() { - return $this->add_header( 'Content-Type', 'application/json' )->request( 'PATCH' ); + protected function patch() + { + return $this->add_header('Content-Type', 'application/json')->request('PATCH'); } /** @@ -333,9 +350,10 @@ protected function patch() { * * @return bool - True if there was a WP_Error, false if not. */ - protected function handle_wp_error( $method ) { - if ( $this->response instanceof WP_Error ) { - WP_Auth0_ErrorLog::insert_error( $method, $this->response ); + protected function handle_wp_error($method) + { + if ($this->response instanceof WP_Error) { + WP_Auth0_ErrorLog::insert_error($method, $this->response); return true; } return false; @@ -350,36 +368,37 @@ protected function handle_wp_error( $method ) { * * @return bool - True if there was an error, false if not. */ - protected function handle_failed_response( $method, $success_code = 200 ) { + protected function handle_failed_response($method, $success_code = 200) + { - if ( $this->response_code === $success_code ) { + if ($this->response_code === $success_code) { return false; } - $response_body = json_decode( $this->response_body, true ); - $message = __( 'Error returned', 'wp-auth0' ); + $response_body = json_decode($this->response_body, true); + $message = esc_html__('Error returned', 'wp-auth0'); - if ( isset( $response_body['statusCode'] ) ) { + if (isset($response_body['statusCode'])) { - if ( isset( $response_body['message'] ) ) { - $message .= ' - ' . sanitize_text_field( $response_body['message'] ); + if (isset($response_body['message'])) { + $message .= ' - ' . sanitize_text_field($response_body['message']); } - if ( isset( $response_body['errorCode'] ) ) { - $message .= ' [' . sanitize_text_field( $response_body['errorCode'] ) . ']'; + if (isset($response_body['errorCode'])) { + $message .= ' [' . sanitize_text_field($response_body['errorCode']) . ']'; } - WP_Auth0_ErrorLog::insert_error( $method, new WP_Error( $response_body['statusCode'], $message ) ); + WP_Auth0_ErrorLog::insert_error($method, new WP_Error($response_body['statusCode'], $message)); return true; } - if ( isset( $response_body['error'] ) ) { - if ( isset( $response_body['error_description'] ) ) { - $message .= ' - ' . sanitize_text_field( $response_body['error_description'] ); + if (isset($response_body['error'])) { + if (isset($response_body['error_description'])) { + $message .= ' - ' . sanitize_text_field($response_body['error_description']); } - WP_Auth0_ErrorLog::insert_error( $method, new WP_Error( $response_body['error'], $message ) ); + WP_Auth0_ErrorLog::insert_error($method, new WP_Error($response_body['error'], $message)); return true; } - WP_Auth0_ErrorLog::insert_error( $method, $this->response_body ); + WP_Auth0_ErrorLog::insert_error($method, $this->response_body); return true; } @@ -392,17 +411,18 @@ protected function handle_failed_response( $method, $success_code = 200 ) { * * @codeCoverageIgnore - Tested by individual HTTP methods in TestApiAbstract::testHttpRequests() */ - private function request( $method ) { + private function request($method) + { $remote_url = $this->build_url(); $http_args = [ 'headers' => $this->headers, 'method' => $method, - 'body' => ! empty( $this->body ) ? json_encode( $this->body ) : null, + 'body' => !empty($this->body) ? json_encode($this->body) : null, ]; - $this->response = wp_remote_request( $remote_url, $http_args ); - $this->response_code = (int) wp_remote_retrieve_response_code( $this->response ); - $this->response_body = wp_remote_retrieve_body( $this->response ); + $this->response = wp_remote_request($remote_url, $http_args); + $this->response_code = (int) wp_remote_retrieve_response_code($this->response); + $this->response_body = wp_remote_retrieve_body($this->response); return $this; } @@ -416,9 +436,10 @@ private function request( $method ) { * * @codeCoverageIgnore */ - private function clean_path( $path ) { - if ( ! empty( $path[0] ) && '/' === $path[0] ) { - $path = substr( $path, 1 ); + private function clean_path($path) + { + if (!empty($path[0]) && '/' === $path[0]) { + $path = substr($path, 1); } return $path; } diff --git a/lib/api/WP_Auth0_Api_Change_Email.php b/lib/api/WP_Auth0_Api_Change_Email.php index a77c1e8f2..03de9af16 100644 --- a/lib/api/WP_Auth0_Api_Change_Email.php +++ b/lib/api/WP_Auth0_Api_Change_Email.php @@ -1,4 +1,5 @@ api_client_creds = $api_client_creds; } @@ -51,24 +53,25 @@ public function __construct( * * @return bool */ - public function call( $user_id = null, $email = null ) { + public function call($user_id = null, $email = null) + { - if ( empty( $user_id ) || empty( $email ) ) { + if (empty($user_id) || empty($email)) { return self::RETURN_ON_FAILURE; } - if ( ! $this->set_bearer( self::API_SCOPE ) ) { + if (!$this->set_bearer(self::API_SCOPE)) { return self::RETURN_ON_FAILURE; } return $this - ->set_path( 'api/v2/users/' . rawurlencode( $user_id ) ) - ->add_body( 'email', $email ) + ->set_path('api/v2/users/' . rawurlencode($user_id)) + ->add_body('email', $email) // Email is either changed by an admin or verified by WP. - ->add_body( 'email_verified', true ) - ->add_body( 'client_id', $this->options->get( 'client_id' ) ) + ->add_body('email_verified', true) + ->add_body('client_id', $this->options->get('client_id')) ->patch() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -78,13 +81,14 @@ public function call( $user_id = null, $email = null ) { * * @return bool */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } diff --git a/lib/api/WP_Auth0_Api_Change_Password.php b/lib/api/WP_Auth0_Api_Change_Password.php index 2e967e702..f3ab1a886 100644 --- a/lib/api/WP_Auth0_Api_Change_Password.php +++ b/lib/api/WP_Auth0_Api_Change_Password.php @@ -1,4 +1,5 @@ api_client_creds = $api_client_creds; } @@ -51,21 +53,22 @@ public function __construct( * * @return bool|string|null */ - public function call( $user_id = null, $password = null ) { + public function call($user_id = null, $password = null) + { - if ( empty( $user_id ) || empty( $password ) ) { + if (empty($user_id) || empty($password)) { return self::RETURN_ON_FAILURE; } - if ( ! $this->set_bearer( self::API_SCOPE ) ) { + if (!$this->set_bearer(self::API_SCOPE)) { return self::RETURN_ON_FAILURE; } return $this - ->set_path( 'api/v2/users/' . rawurlencode( $user_id ) ) - ->add_body( 'password', $password ) + ->set_path('api/v2/users/' . rawurlencode($user_id)) + ->add_body('password', $password) ->patch() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -75,16 +78,17 @@ public function call( $user_id = null, $password = null ) { * * @return bool|string */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { - $response_body = json_decode( $this->response_body ); - if ( isset( $response_body->message ) && false !== strpos( $response_body->message, 'PasswordStrengthError' ) ) { - return __( 'Password is too weak, please choose a different one.', 'wp-auth0' ); + if ($this->handle_failed_response($method)) { + $response_body = json_decode($this->response_body); + if (isset($response_body->message) && false !== strpos($response_body->message, 'PasswordStrengthError')) { + return esc_html__('Password is too weak, please choose a different one.', 'wp-auth0'); } return self::RETURN_ON_FAILURE; } diff --git a/lib/api/WP_Auth0_Api_Client_Credentials.php b/lib/api/WP_Auth0_Api_Client_Credentials.php index c638be116..eb8778e8a 100644 --- a/lib/api/WP_Auth0_Api_Client_Credentials.php +++ b/lib/api/WP_Auth0_Api_Client_Credentials.php @@ -1,4 +1,5 @@ set_path( 'oauth/token' ) + public function __construct(WP_Auth0_Options $options) + { + parent::__construct($options); + $this->set_path('oauth/token') ->send_client_id() ->send_client_secret() ->send_audience() - ->add_body( 'grant_type', 'client_credentials' ); + ->add_body('grant_type', 'client_credentials'); } /** @@ -46,8 +49,9 @@ public function __construct( WP_Auth0_Options $options ) { * * @return mixed|null */ - public function call() { - return $this->post()->handle_response( __METHOD__ ); + public function call() + { + return $this->post()->handle_response(__METHOD__); } /** @@ -57,31 +61,32 @@ public function call() { * * @return string|null */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } - $response_body = json_decode( $this->response_body, true ); + $response_body = json_decode($this->response_body, true); // If we have no access token, something went wrong upstream. - if ( ! isset( $response_body['access_token'] ) ) { - WP_Auth0_ErrorLog::insert_error( $method, __( 'No access_token returned.', 'wp-auth0' ) ); + if (!isset($response_body['access_token'])) { + WP_Auth0_ErrorLog::insert_error($method, esc_html__('No access_token returned.', 'wp-auth0')); return self::RETURN_ON_FAILURE; } // Set the transient to expire 1 minute before the token does. - $expires_in = ! isset( $response_body['expires_in'] ) ? HOUR_IN_SECONDS : absint( $response_body['expires_in'] ); + $expires_in = !isset($response_body['expires_in']) ? HOUR_IN_SECONDS : absint($response_body['expires_in']); $expires_in -= MINUTE_IN_SECONDS; // Store the token and scope to check when used. - set_transient( self::TOKEN_TRANSIENT_KEY, $response_body['access_token'], $expires_in ); - set_transient( self::SCOPE_TRANSIENT_KEY, $response_body['scope'], $expires_in ); + set_transient(self::TOKEN_TRANSIENT_KEY, $response_body['access_token'], $expires_in); + set_transient(self::SCOPE_TRANSIENT_KEY, $response_body['scope'], $expires_in); return $response_body['access_token']; } @@ -91,16 +96,18 @@ protected function handle_response( $method ) { * * @return string */ - public static function get_stored_token() { - return get_transient( self::TOKEN_TRANSIENT_KEY ); + public static function get_stored_token() + { + return get_transient(self::TOKEN_TRANSIENT_KEY); } /** * Delete the stored access token and scope from transients. */ - public static function delete_store() { - delete_transient( self::TOKEN_TRANSIENT_KEY ); - delete_transient( self::SCOPE_TRANSIENT_KEY ); + public static function delete_store() + { + delete_transient(self::TOKEN_TRANSIENT_KEY); + delete_transient(self::SCOPE_TRANSIENT_KEY); } /** @@ -110,9 +117,10 @@ public static function delete_store() { * * @return bool */ - public static function check_stored_scope( $scope ) { - $stored_scope = get_transient( self::SCOPE_TRANSIENT_KEY ); - $scopes = explode( ' ', $stored_scope ); - return in_array( $scope, $scopes ); + public static function check_stored_scope($scope) + { + $stored_scope = get_transient(self::SCOPE_TRANSIENT_KEY); + $scopes = explode(' ', $stored_scope); + return in_array($scope, $scopes); } } diff --git a/lib/api/WP_Auth0_Api_Exchange_Code.php b/lib/api/WP_Auth0_Api_Exchange_Code.php index 5c40d99a8..865ee3d85 100644 --- a/lib/api/WP_Auth0_Api_Exchange_Code.php +++ b/lib/api/WP_Auth0_Api_Exchange_Code.php @@ -1,4 +1,5 @@ options->get( 'client_id' ); - if ( empty( $client_id ) ) { + $client_id = $client_id ?: $this->options->get('client_id'); + if (empty($client_id)) { return self::RETURN_ON_FAILURE; } - $client_secret = $this->options->get( 'client_secret' ) ?: ''; + $client_secret = $this->options->get('client_secret') ?: ''; $redirect_uri = $redirect_uri ?: $this->options->get_wp_auth0_url(); return $this - ->set_path( 'oauth/token' ) - ->add_body( 'grant_type', 'authorization_code' ) - ->add_body( 'code', $code ) - ->add_body( 'redirect_uri', $redirect_uri ) - ->add_body( 'client_id', $client_id ) - ->add_body( 'client_secret', $client_secret ) + ->set_path('oauth/token') + ->add_body('grant_type', 'authorization_code') + ->add_body('code', $code) + ->add_body('redirect_uri', $redirect_uri) + ->add_body('client_id', $client_id) + ->add_body('client_secret', $client_secret) ->post() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -61,22 +64,23 @@ public function call( $code = null, $client_id = null, $redirect_uri = null ) { * * @return string|null */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( 401 == $this->response_code ) { + if (401 == $this->response_code) { WP_Auth0_ErrorLog::insert_error( __METHOD__ . ' L:' . __LINE__, - __( 'An /oauth/token call triggered a 401 response from Auth0. ', 'wp-auth0' ) . - __( 'Please check the Client Secret saved in the Auth0 plugin settings. ', 'wp-auth0' ) + esc_html__('An /oauth/token call triggered a 401 response from Auth0. ', 'wp-auth0') . + esc_html__('Please check the Client Secret saved in the Auth0 plugin settings. ', 'wp-auth0') ); return self::RETURN_ON_FAILURE; } - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } diff --git a/lib/api/WP_Auth0_Api_Get_Jwks.php b/lib/api/WP_Auth0_Api_Get_Jwks.php index f1d1b582c..ef966e091 100644 --- a/lib/api/WP_Auth0_Api_Get_Jwks.php +++ b/lib/api/WP_Auth0_Api_Get_Jwks.php @@ -1,4 +1,5 @@ set_path( '.well-known/jwks.json' ) + ->set_path('.well-known/jwks.json') ->get() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -37,16 +40,17 @@ public function call() { * * @return array */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } - return json_decode( $this->response_body, true ); + return json_decode($this->response_body, true); } } diff --git a/lib/api/WP_Auth0_Api_Get_User.php b/lib/api/WP_Auth0_Api_Get_User.php index 3bf88162c..f900ee0c4 100644 --- a/lib/api/WP_Auth0_Api_Get_User.php +++ b/lib/api/WP_Auth0_Api_Get_User.php @@ -1,4 +1,5 @@ api_client_creds = $api_client_creds; } @@ -44,20 +46,21 @@ public function __construct( * * @return null|string */ - public function call( $user_id = null ) { + public function call($user_id = null) + { - if ( empty( $user_id ) ) { + if (empty($user_id)) { return self::RETURN_ON_FAILURE; } - if ( ! $this->set_bearer( self::API_SCOPE ) ) { + if (!$this->set_bearer(self::API_SCOPE)) { return self::RETURN_ON_FAILURE; } return $this - ->set_path( 'api/v2/users/' . rawurlencode( $user_id ) ) + ->set_path('api/v2/users/' . rawurlencode($user_id)) ->get() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -67,13 +70,14 @@ public function call( $user_id = null ) { * * @return string|null */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } diff --git a/lib/api/WP_Auth0_Api_Jobs_Verification.php b/lib/api/WP_Auth0_Api_Jobs_Verification.php index 17f624408..f2390aade 100644 --- a/lib/api/WP_Auth0_Api_Jobs_Verification.php +++ b/lib/api/WP_Auth0_Api_Jobs_Verification.php @@ -1,4 +1,5 @@ api_client_creds = $api_client_creds; - $this->set_path( 'api/v2/jobs/verification-email' ) + $this->set_path('api/v2/jobs/verification-email') ->send_client_id(); } @@ -52,19 +54,20 @@ public function __construct( * * @return bool|mixed|null */ - public function call( $user_id = null ) { + public function call($user_id = null) + { - if ( empty( $user_id ) ) { + if (empty($user_id)) { return self::RETURN_ON_FAILURE; } - if ( ! $this->set_bearer( self::API_SCOPE ) ) { + if (!$this->set_bearer(self::API_SCOPE)) { return self::RETURN_ON_FAILURE; } - return $this->add_body( 'user_id', $user_id ) + return $this->add_body('user_id', $user_id) ->post() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -74,13 +77,14 @@ public function call( $user_id = null ) { * * @return mixed|null */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method, 201 ) ) { + if ($this->handle_failed_response($method, 201)) { return self::RETURN_ON_FAILURE; } diff --git a/lib/api/WP_Auth0_Api_Refresh_Access_Token.php b/lib/api/WP_Auth0_Api_Refresh_Access_Token.php index 69b7784fd..84ec9e8aa 100644 --- a/lib/api/WP_Auth0_Api_Refresh_Access_Token.php +++ b/lib/api/WP_Auth0_Api_Refresh_Access_Token.php @@ -1,4 +1,5 @@ options->get( 'client_id' ); - if ( empty( $client_id ) ) { + $client_id = $client_id ?: $this->options->get('client_id'); + if (empty($client_id)) { return self::RETURN_ON_FAILURE; } - $client_secret = $client_secret ?: $this->options->get( 'client_secret' ); - if ( empty( $client_secret ) ) { + $client_secret = $client_secret ?: $this->options->get('client_secret'); + if (empty($client_secret)) { return self::RETURN_ON_FAILURE; } return $this - ->set_path( 'oauth/token' ) - ->add_body( 'grant_type', 'refresh_token' ) - ->add_body( 'client_id', $client_id ) - ->add_body( 'client_secret', $client_secret ) - ->add_body( 'refresh_token', $refresh_token ) + ->set_path('oauth/token') + ->add_body('grant_type', 'refresh_token') + ->add_body('client_id', $client_id) + ->add_body('client_secret', $client_secret) + ->add_body('refresh_token', $refresh_token) ->post() - ->handle_response( __METHOD__ ); + ->handle_response(__METHOD__); } /** @@ -63,22 +66,23 @@ public function call( $client_id = null, $client_secret = null, $refresh_token = * * @return string|null */ - protected function handle_response( $method ) { + protected function handle_response($method) + { - if ( 401 == $this->response_code ) { + if (401 == $this->response_code) { WP_Auth0_ErrorLog::insert_error( __METHOD__ . ' L:' . __LINE__, - __( 'An /oauth/token call triggered a 401 response from Auth0. ', 'wp-auth0' ) . - __( 'Please check the Client ID and Client Secret saved in the Auth0 plugin settings. ', 'wp-auth0' ) + esc_html__('An /oauth/token call triggered a 401 response from Auth0. ', 'wp-auth0') . + esc_html__('Please check the Client ID and Client Secret saved in the Auth0 plugin settings. ', 'wp-auth0') ); return self::RETURN_ON_FAILURE; } - if ( $this->handle_wp_error( $method ) ) { + if ($this->handle_wp_error($method)) { return self::RETURN_ON_FAILURE; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return self::RETURN_ON_FAILURE; } diff --git a/lib/exceptions/WP_Auth0_BeforeLoginException.php b/lib/exceptions/WP_Auth0_BeforeLoginException.php index 0569b41ea..639021367 100644 --- a/lib/exceptions/WP_Auth0_BeforeLoginException.php +++ b/lib/exceptions/WP_Auth0_BeforeLoginException.php @@ -1,3 +1,5 @@ userinfo = $userinfo; $this->id_token = $id_token; } diff --git a/lib/exceptions/WP_Auth0_InvalidIdTokenException.php b/lib/exceptions/WP_Auth0_InvalidIdTokenException.php index 5fea511b9..7ba163500 100644 --- a/lib/exceptions/WP_Auth0_InvalidIdTokenException.php +++ b/lib/exceptions/WP_Auth0_InvalidIdTokenException.php @@ -5,4 +5,6 @@ * * @since 3.11.0 */ -class WP_Auth0_InvalidIdTokenException extends Exception {} +class WP_Auth0_InvalidIdTokenException extends Exception +{ +} diff --git a/lib/exceptions/WP_Auth0_LoginFlowValidationException.php b/lib/exceptions/WP_Auth0_LoginFlowValidationException.php index 1a0d6314d..cb4dad88d 100644 --- a/lib/exceptions/WP_Auth0_LoginFlowValidationException.php +++ b/lib/exceptions/WP_Auth0_LoginFlowValidationException.php @@ -1,3 +1,5 @@ api_change_email = $api_change_email; } @@ -44,65 +47,66 @@ public function __construct( WP_Auth0_Api_Change_Email $api_change_email ) { * * @return boolean */ - public function update_email( $wp_user_id, $old_user_data ) { + public function update_email($wp_user_id, $old_user_data) + { // Exit if this is not an Auth0 user. - $auth0_id = WP_Auth0_UsersRepo::get_meta( $wp_user_id, 'auth0_id' ); - if ( empty( $auth0_id ) ) { + $auth0_id = WP_Auth0_UsersRepo::get_meta($wp_user_id, 'auth0_id'); + if (empty($auth0_id)) { return false; } // Exit if this is not a database strategy user. - if ( 'auth0' !== WP_Auth0_Users::get_strategy( $auth0_id ) ) { + if ('auth0' !== WP_Auth0_Users::get_strategy($auth0_id)) { return false; } - $wp_user = get_user_by( 'id', $wp_user_id ); + $wp_user = get_user_by('id', $wp_user_id); $current_email = $wp_user->data->user_email; $old_email = $old_user_data->data->user_email; // No email address changes, exit. - if ( $old_email === $current_email ) { + if ($old_email === $current_email) { return false; } // Set a flag so the Get User call to other processes know the email is in the process of changing. - WP_Auth0_UsersRepo::update_meta( $wp_user_id, self::UPDATED_EMAIL, $current_email ); + WP_Auth0_UsersRepo::update_meta($wp_user_id, self::UPDATED_EMAIL, $current_email); // Attempt to update the email address at Auth0. // For custom database setups, this will trigger a Get User script call from Auth0. // See: WP_Auth0_Routes::migration_ws_get_user() - if ( $this->api_change_email->call( $auth0_id, $current_email ) ) { - WP_Auth0_UsersRepo::delete_meta( $wp_user_id, self::UPDATED_EMAIL ); + if ($this->api_change_email->call($auth0_id, $current_email)) { + WP_Auth0_UsersRepo::delete_meta($wp_user_id, self::UPDATED_EMAIL); return true; } // Past this point, email update with Auth0 has failed so we need to revert changes saved in WP. // Remove the pending email address change flags so it can be tried again. - delete_user_meta( $wp_user_id, '_new_email' ); - WP_Auth0_UsersRepo::delete_meta( $wp_user_id, self::UPDATED_EMAIL ); + delete_user_meta($wp_user_id, '_new_email'); + WP_Auth0_UsersRepo::delete_meta($wp_user_id, self::UPDATED_EMAIL); // Suppress the notification for email change. - add_filter( 'email_change_email', [ $this, 'suppress_email_change_notification' ], 100 ); + add_filter('email_change_email', [$this, 'suppress_email_change_notification'], 100); // Remove this method from profile_update, which is called by wp_update_user, to avoid an infinite loop. - remove_action( 'profile_update', 'wp_auth0_profile_change_email', 100 ); + remove_action('profile_update', 'wp_auth0_profile_change_email', 100); // Revert the email address to previous. $wp_user->data->user_email = $old_email; - wp_update_user( $wp_user ); + wp_update_user($wp_user); // Revert hooks from above. - add_action( 'profile_update', 'wp_auth0_profile_change_email', 100, 2 ); - remove_filter( 'email_change_email', [ $this, 'suppress_email_change_notification' ], 100 ); + add_action('profile_update', 'wp_auth0_profile_change_email', 100, 2); + remove_filter('email_change_email', [$this, 'suppress_email_change_notification'], 100); // Can't set a custom message here so redirect with an error for WP to pick up. - if ( in_array( $GLOBALS['pagenow'], [ 'user-edit.php', 'profile.php' ] ) ) { - $redirect_url = admin_url( $GLOBALS['pagenow'] ); - $redirect_url = add_query_arg( 'user_id', $wp_user_id, $redirect_url ); - $redirect_url = add_query_arg( 'error', 'new-email', $redirect_url ); - wp_safe_redirect( $redirect_url ); + if (in_array($GLOBALS['pagenow'], ['user-edit.php', 'profile.php'])) { + $redirect_url = admin_url($GLOBALS['pagenow']); + $redirect_url = add_query_arg('user_id', $wp_user_id, $redirect_url); + $redirect_url = add_query_arg('error', 'new-email', $redirect_url); + wp_safe_redirect($redirect_url); exit; } @@ -118,10 +122,11 @@ public function update_email( $wp_user_id, $old_user_data ) { * * @see wp_update_user() */ - public function suppress_email_change_notification( array $email ) { + public function suppress_email_change_notification(array $email) + { $email['to'] = null; $email['message'] = null; - $email['subject'] = __( 'Email suppressed - Auth0 email change failed.', 'wp-auth0' ); + $email['subject'] = esc_html__('Email suppressed - Auth0 email change failed.', 'wp-auth0'); return $email; } } diff --git a/lib/profile/WP_Auth0_Profile_Change_Password.php b/lib/profile/WP_Auth0_Profile_Change_Password.php index 9c961bbdf..085cf1571 100644 --- a/lib/profile/WP_Auth0_Profile_Change_Password.php +++ b/lib/profile/WP_Auth0_Profile_Change_Password.php @@ -1,4 +1,5 @@ api_change_password = $api_change_password; } @@ -38,62 +41,63 @@ public function __construct( WP_Auth0_Api_Change_Password $api_change_password ) * * @return boolean */ - public function validate_new_password( $errors, $user ) { + public function validate_new_password($errors, $user) + { // Nonce was verified during core process this is hooked to. // phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification // Exit if we're not changing the password. // The pass1 key is for core WP, password_1 is WooCommerce. - if ( empty( $_POST['pass1'] ) && empty( $_POST['password_1'] ) ) { + if (empty($_POST['pass1']) && empty($_POST['password_1'])) { return false; } // Do we have a user to edit? - $is_user_from_hook = is_object( $user ) && ! empty( $user->ID ); - if ( ! $is_user_from_hook && ! isset( $_POST['user_id'] ) ) { + $is_user_from_hook = is_object($user) && !empty($user->ID); + if (!$is_user_from_hook && !isset($_POST['user_id'])) { return false; } - $wp_user_id = absint( $is_user_from_hook ? $user->ID : $_POST['user_id'] ); + $wp_user_id = absint($is_user_from_hook ? $user->ID : $_POST['user_id']); // Does the current user have permission to edit this user? - if ( ! current_user_can( 'edit_users' ) && $wp_user_id !== get_current_user_id() ) { + if (!current_user_can('edit_users') && $wp_user_id !== get_current_user_id()) { return false; } // Is the user being edited an Auth0 user? - $auth0_id = WP_Auth0_UsersRepo::get_meta( $wp_user_id, 'auth0_id' ); - if ( empty( $auth0_id ) ) { + $auth0_id = WP_Auth0_UsersRepo::get_meta($wp_user_id, 'auth0_id'); + if (empty($auth0_id)) { return false; } // Is the user being edited a DB strategy user? - $strategy = WP_Auth0_Users::get_strategy( $auth0_id ); - if ( 'auth0' !== $strategy ) { + $strategy = WP_Auth0_Users::get_strategy($auth0_id); + if ('auth0' !== $strategy) { return false; } - $field_name = ! empty( $_POST['pass1'] ) ? 'pass1' : 'password_1'; + $field_name = !empty($_POST['pass1']) ? 'pass1' : 'password_1'; // Validated above and only sent to the change password API endpoint. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - $new_password = wp_unslash( $_POST[ $field_name ] ); + $new_password = wp_unslash($_POST[$field_name]); - $result = $this->api_change_password->call( $auth0_id, $new_password ); + $result = $this->api_change_password->call($auth0_id, $new_password); // Password change was successful, nothing else to do. - if ( true === $result ) { + if (true === $result) { return true; } // Password change was unsuccessful so don't change WP user account. - unset( $_POST['pass1'] ); - unset( $_POST['pass1-text'] ); - unset( $_POST['pass2'] ); + unset($_POST['pass1']); + unset($_POST['pass1-text']); + unset($_POST['pass2']); // Add an error message to appear at the top of the page. - $error_msg = is_string( $result ) ? $result : __( 'Password could not be updated.', 'wp-auth0' ); - $errors->add( 'auth0_password', $error_msg, [ 'form-field' => $field_name ] ); + $error_msg = is_string($result) ? $result : esc_html__('Password could not be updated.', 'wp-auth0'); + $errors->add('auth0_password', $error_msg, ['form-field' => $field_name]); return false; // phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification diff --git a/lib/profile/WP_Auth0_Profile_Delete_Data.php b/lib/profile/WP_Auth0_Profile_Delete_Data.php index 9bf7404b2..86c5214fb 100644 --- a/lib/profile/WP_Auth0_Profile_Delete_Data.php +++ b/lib/profile/WP_Auth0_Profile_Delete_Data.php @@ -1,4 +1,5 @@ +?>
- + - +

- - + +
- __( 'Empty user_id', 'wp-auth0' ) ] ); + if (empty($_POST['user_id'])) { + wp_send_json_error(['error' => esc_html__('Empty user_id', 'wp-auth0')]); } - $user_id = absint( $_POST['user_id'] ); + $user_id = absint($_POST['user_id']); - if ( ! current_user_can( 'edit_users' ) ) { - wp_send_json_error( [ 'error' => __( 'Forbidden', 'wp-auth0' ) ] ); + if (!current_user_can('edit_users')) { + wp_send_json_error(['error' => esc_html__('Forbidden', 'wp-auth0')]); } - wp_auth0_delete_auth0_object( $user_id ); + wp_auth0_delete_auth0_object($user_id); wp_send_json_success(); } } diff --git a/lib/scripts-js/db-get-user.js b/lib/scripts-js/db-get-user.js index fdd8d9d93..61a7c7360 100644 --- a/lib/scripts-js/db-get-user.js +++ b/lib/scripts-js/db-get-user.js @@ -10,20 +10,18 @@ * @param {string} email - User email address, provided on login. * @param {function} callback - Function to call when the script has completed. */ -function getByEmail (email, callback) { - - var request = require('request'); +function getByEmail(email, callback) { + var request = require("request"); request.post( - configuration.endpointUrl + 'migration-ws-get-user', + configuration.endpointUrl + "migration-ws-get-user", { form: { username: email, - access_token: configuration.migrationToken - } + access_token: configuration.migrationToken, + }, }, - function(error, response, body) { - + function (error, response, body) { // Error encountered during HTTP request, exit. if (error) { return callback(error); @@ -32,19 +30,20 @@ function getByEmail (email, callback) { var wpUser = JSON.parse(body); // Error returned from WordPress or no data, exit. - if (wpUser.error || ! wpUser.data) { + if (wpUser.error || !wpUser.data) { return callback(null); } // Use WordPress profile data to populate Auth0 account. var profile = { - user_id: configuration.userNamespace + '|' + wpUser.data.ID, + user_id: configuration.userNamespace + "|" + wpUser.data.ID, username: wpUser.data.user_login, email: wpUser.data.user_email, name: wpUser.data.display_name, - email_verified: true + email_verified: true, }; callback(null, profile); - }); + } + ); } diff --git a/lib/scripts-js/db-login.js b/lib/scripts-js/db-login.js index 4269b038e..b7a47c048 100644 --- a/lib/scripts-js/db-login.js +++ b/lib/scripts-js/db-login.js @@ -11,21 +11,19 @@ * @param {string} password - User password, provided on login. * @param {function} callback - Function to call when the script has completed. */ -function login (email, password, callback) { - - var request = require('request'); +function login(email, password, callback) { + var request = require("request"); request.post( - configuration.endpointUrl + 'migration-ws-login', + configuration.endpointUrl + "migration-ws-login", { form: { - username: email, - password: password, - access_token: configuration.migrationToken - } + username: email, + password: password, + access_token: configuration.migrationToken, + }, }, - function(error, response, body) { - + function (error, response, body) { // Error encountered during HTTP request, exit. if (error) { return callback(error); @@ -34,19 +32,20 @@ function login (email, password, callback) { var wpUser = JSON.parse(body); // Error returned from WordPress or no data, exit. - if (wpUser.error || ! wpUser.data) { + if (wpUser.error || !wpUser.data) { return callback(null); } // Use WordPress profile data to populate Auth0 account. var profile = { - user_id: configuration.userNamespace + '|' + wpUser.data.ID, + user_id: configuration.userNamespace + "|" + wpUser.data.ID, username: wpUser.data.user_login, email: wpUser.data.user_email, name: wpUser.data.display_name, - email_verified: true + email_verified: true, }; callback(null, profile); - }); + } + ); } diff --git a/lib/token-verifier/WP_Auth0_AsymmetricVerifier.php b/lib/token-verifier/WP_Auth0_AsymmetricVerifier.php index c686defeb..4ca8896e8 100644 --- a/lib/token-verifier/WP_Auth0_AsymmetricVerifier.php +++ b/lib/token-verifier/WP_Auth0_AsymmetricVerifier.php @@ -1,4 +1,5 @@ jwks = $jwks; - parent::__construct( 'RS256' ); + parent::__construct('RS256'); } /** @@ -44,15 +47,16 @@ public function __construct( WP_Auth0_JwksFetcher $jwks ) { * * @throws WP_Auth0_InvalidIdTokenException If ID token kid was not found in the JWKS. */ - protected function checkSignature( Token $token ) : bool { - $token_kid = $token->getHeader( 'kid', false ); - $signing_key = $this->jwks->getKey( $token_kid ); - if ( ! $signing_key ) { - throw new WP_Auth0_InvalidIdTokenException( + protected function checkSignature(Token $token): bool + { + $token_kid = $token->getHeader('kid', false); + $signing_key = $this->jwks->getKey($token_kid); + if (!$signing_key) { + throw new WP_Auth0_InvalidIdTokenException(esc_html( 'Could not find a public key for Key ID (kid) "' . $token_kid . '"' - ); + )); } - return $token->verify( new RsSigner(), new Key( $signing_key ) ); + return $token->verify(new RsSigner(), new Key($signing_key)); } } diff --git a/lib/token-verifier/WP_Auth0_IdTokenVerifier.php b/lib/token-verifier/WP_Auth0_IdTokenVerifier.php index 798c8d693..d844eca28 100644 --- a/lib/token-verifier/WP_Auth0_IdTokenVerifier.php +++ b/lib/token-verifier/WP_Auth0_IdTokenVerifier.php @@ -1,4 +1,5 @@ issuer = $issuer; $this->audience = $audience; $this->verifier = $verifier; @@ -62,7 +65,8 @@ public function __construct( string $issuer, string $audience, WP_Auth0_Signatur * * @return void */ - public function setLeeway( int $newLeeway ) { + public function setLeeway(int $newLeeway) + { $this->leeway = $newLeeway; } @@ -84,16 +88,17 @@ public function setLeeway( int $newLeeway ) { * - Token algorithm is not supported * - Any claim-based test fails */ - public function verify( string $token, array $options = [] ) : array { - if ( empty( $token ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'ID token is required but missing' ); + public function verify(string $token, array $options = []): array + { + if (empty($token)) { + throw new WP_Auth0_InvalidIdTokenException('ID token is required but missing'); } - $verifiedToken = $this->verifier->verifyAndDecode( $token ); + $verifiedToken = $this->verifier->verifyAndDecode($token); $claims = []; - foreach ( $verifiedToken->getClaims() as $claim => $value ) { - $claims[ $claim ] = $value->getValue(); + foreach ($verifiedToken->getClaims() as $claim => $value) { + $claims[$claim] = $value->getValue(); } /* @@ -101,17 +106,17 @@ public function verify( string $token, array $options = [] ) : array { */ $tokenIss = $claims['iss'] ?? false; - if ( ! $tokenIss || ! is_string( $tokenIss ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Issuer (iss) claim must be a string present in the ID token' ); + if (!$tokenIss || !is_string($tokenIss)) { + throw new WP_Auth0_InvalidIdTokenException('Issuer (iss) claim must be a string present in the ID token'); } - if ( $tokenIss !== $this->issuer ) { + if ($tokenIss !== $this->issuer) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Issuer (iss) claim mismatch in the ID token; expected "%s", found "%s"', $this->issuer, $tokenIss - ) + )) ); } @@ -120,8 +125,8 @@ public function verify( string $token, array $options = [] ) : array { */ $tokenSub = $claims['sub'] ?? false; - if ( ! $tokenSub || ! is_string( $tokenSub ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Subject (sub) claim must be a string present in the ID token' ); + if (!$tokenSub || !is_string($tokenSub)) { + throw new WP_Auth0_InvalidIdTokenException('Subject (sub) claim must be a string present in the ID token'); } /* @@ -129,27 +134,27 @@ public function verify( string $token, array $options = [] ) : array { */ $tokenAud = $claims['aud'] ?? false; - if ( ! $tokenAud || ( ! is_string( $tokenAud ) && ! is_array( $tokenAud ) ) ) { + if (!$tokenAud || (!is_string($tokenAud) && !is_array($tokenAud))) { throw new WP_Auth0_InvalidIdTokenException( 'Audience (aud) claim must be a string or array of strings present in the ID token' ); } - if ( is_array( $tokenAud ) && ! in_array( $this->audience, $tokenAud ) ) { + if (is_array($tokenAud) && !in_array($this->audience, $tokenAud)) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Audience (aud) claim mismatch in the ID token; expected "%s" was not one of "%s"', $this->audience, - implode( ', ', $tokenAud ) - ) + implode(', ', $tokenAud) + )) ); - } elseif ( is_string( $tokenAud ) && $tokenAud !== $this->audience ) { + } elseif (is_string($tokenAud) && $tokenAud !== $this->audience) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Audience (aud) claim mismatch in the ID token; expected "%s", found "%s"', $this->audience, $tokenAud - ) + )) ); } @@ -161,43 +166,43 @@ public function verify( string $token, array $options = [] ) : array { $leeway = $options['leeway'] ?? $this->leeway; $tokenExp = $claims['exp'] ?? false; - if ( ! $tokenExp || ! is_int( $tokenExp ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Expiration Time (exp) claim must be a number present in the ID token' ); + if (!$tokenExp || !is_int($tokenExp)) { + throw new WP_Auth0_InvalidIdTokenException('Expiration Time (exp) claim must be a number present in the ID token'); } $expireTime = $tokenExp + $leeway; - if ( $now > $expireTime ) { + if ($now > $expireTime) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Expiration Time (exp) claim error in the ID token; current time (%d) is after expiration time (%d)', $now, $expireTime - ) + )) ); } $tokenIat = $claims['iat'] ?? false; - if ( ! $tokenIat || ! is_int( $tokenIat ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Issued At (iat) claim must be a number present in the ID token' ); + if (!$tokenIat || !is_int($tokenIat)) { + throw new WP_Auth0_InvalidIdTokenException('Issued At (iat) claim must be a number present in the ID token'); } /* * Nonce check */ - if ( ! empty( $options['nonce'] ) ) { + if (!empty($options['nonce'])) { $tokenNonce = $claims['nonce'] ?? false; - if ( ! $tokenNonce || ! is_string( $tokenNonce ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Nonce (nonce) claim must be a string present in the ID token' ); + if (!$tokenNonce || !is_string($tokenNonce)) { + throw new WP_Auth0_InvalidIdTokenException('Nonce (nonce) claim must be a string present in the ID token'); } - if ( $tokenNonce !== $options['nonce'] ) { + if ($tokenNonce !== $options['nonce']) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Nonce (nonce) claim mismatch in the ID token; expected "%s", found "%s"', $options['nonce'], $tokenNonce - ) + )) ); } } @@ -206,21 +211,21 @@ public function verify( string $token, array $options = [] ) : array { * Authorized party check */ - if ( is_array( $tokenAud ) && count( $tokenAud ) > 1 ) { + if (is_array($tokenAud) && count($tokenAud) > 1) { $tokenAzp = $claims['azp'] ?? false; - if ( ! $tokenAzp || ! is_string( $tokenAzp ) ) { + if (!$tokenAzp || !is_string($tokenAzp)) { throw new WP_Auth0_InvalidIdTokenException( 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values' ); } - if ( $tokenAzp !== $this->audience ) { + if ($tokenAzp !== $this->audience) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Authorized Party (azp) claim mismatch in the ID token; expected "%s", found "%s"', $this->audience, $tokenAzp - ) + )) ); } } @@ -231,18 +236,18 @@ public function verify( string $token, array $options = [] ) : array { $expectedOrganization = $options['org_id'] ?? null; - if ( null !== $expectedOrganization && '' !== $expectedOrganization ) { - if ( ! isset( $claims['org_id'] ) || ! is_string( $claims['org_id'] ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Organization Id (org_id) claim must be a string present in the ID token' ); + if (null !== $expectedOrganization && '' !== $expectedOrganization) { + if (!isset($claims['org_id']) || !is_string($claims['org_id'])) { + throw new WP_Auth0_InvalidIdTokenException('Organization Id (org_id) claim must be a string present in the ID token'); } - if ( $claims['org_id'] !== $expectedOrganization ) { + if ($claims['org_id'] !== $expectedOrganization) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Organization Id (org_id) claim value mismatch in the ID token; expected "%s", found "%s"', $expectedOrganization, $claims['org_id'] - ) + )) ); } } @@ -251,9 +256,9 @@ public function verify( string $token, array $options = [] ) : array { * Authentication time check */ - if ( ! empty( $options['max_age'] ) ) { + if (!empty($options['max_age'])) { $tokenAuthTime = $claims['auth_time'] ?? false; - if ( ! $tokenAuthTime || ! is_int( $tokenAuthTime ) ) { + if (!$tokenAuthTime || !is_int($tokenAuthTime)) { throw new WP_Auth0_InvalidIdTokenException( 'Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified' ); @@ -261,13 +266,13 @@ public function verify( string $token, array $options = [] ) : array { $authValidUntil = $tokenAuthTime + $options['max_age'] + $leeway; - if ( $now > $authValidUntil ) { + if ($now > $authValidUntil) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (%d) is after last auth at %d', $now, $authValidUntil - ) + )) ); } } diff --git a/lib/token-verifier/WP_Auth0_JwksFetcher.php b/lib/token-verifier/WP_Auth0_JwksFetcher.php index 3dbf9b6b1..f32382606 100644 --- a/lib/token-verifier/WP_Auth0_JwksFetcher.php +++ b/lib/token-verifier/WP_Auth0_JwksFetcher.php @@ -5,7 +5,8 @@ * * @codeCoverageIgnore - Classes are adapted from the PHP SDK and tested there. */ -class WP_Auth0_JwksFetcher { +class WP_Auth0_JwksFetcher +{ /** * @var WP_Auth0_Options @@ -15,8 +16,9 @@ class WP_Auth0_JwksFetcher { /** * WP_Auth0_JwksFetcher constructor. */ - public function __construct() { - $this->options = WP_Auth0_Options::Instance(); + public function __construct() + { + $this->options = WP_Auth0_Options::Instance(); } /** @@ -26,9 +28,10 @@ public function __construct() { * * @return string */ - protected function convertCertToPem( string $cert ) : string { + protected function convertCertToPem(string $cert): string + { $output = '-----BEGIN CERTIFICATE-----' . PHP_EOL; - $output .= chunk_split( $cert, 64, PHP_EOL ); + $output .= chunk_split($cert, 64, PHP_EOL); $output .= '-----END CERTIFICATE-----' . PHP_EOL; return $output; } @@ -40,14 +43,15 @@ protected function convertCertToPem( string $cert ) : string { * * @return string */ - public function getKey( string $kid ) { + public function getKey(string $kid) + { $keys = $this->getKeys(); - if ( ! empty( $keys ) && empty( $keys[ $kid ] ) ) { - $keys = $this->getKeys( false ); + if (!empty($keys) && empty($keys[$kid])) { + $keys = $this->getKeys(false); } - return $keys[ $kid ] ?? null; + return $keys[$kid] ?? null; } /** @@ -57,30 +61,31 @@ public function getKey( string $kid ) { * * @return array */ - public function getKeys( $use_cache = true ) : array { - $keys = $use_cache ? get_transient( WPA0_JWKS_CACHE_TRANSIENT_NAME ) : []; - if ( is_array( $keys ) && ! empty( $keys ) ) { + public function getKeys($use_cache = true): array + { + $keys = $use_cache ? get_transient(WPA0_JWKS_CACHE_TRANSIENT_NAME) : []; + if (is_array($keys) && !empty($keys)) { return $keys; } $jwks = $this->requestJwks(); - if ( empty( $jwks ) || empty( $jwks['keys'] ) ) { + if (empty($jwks) || empty($jwks['keys'])) { return []; } $keys = []; - foreach ( $jwks['keys'] as $key ) { - if ( empty( $key['kid'] ) || empty( $key['x5c'] ) || empty( $key['x5c'][0] ) ) { + foreach ($jwks['keys'] as $key) { + if (empty($key['kid']) || empty($key['x5c']) || empty($key['x5c'][0])) { continue; } - $keys[ $key['kid'] ] = $this->convertCertToPem( $key['x5c'][0] ); + $keys[$key['kid']] = $this->convertCertToPem($key['x5c'][0]); } - $cache_expiration = $this->options->get( 'cache_expiration' ); - if ( $keys && $cache_expiration ) { - set_transient( WPA0_JWKS_CACHE_TRANSIENT_NAME, $keys, $cache_expiration * MINUTE_IN_SECONDS ); + $cache_expiration = $this->options->get('cache_expiration'); + if ($keys && $cache_expiration) { + set_transient(WPA0_JWKS_CACHE_TRANSIENT_NAME, $keys, $cache_expiration * MINUTE_IN_SECONDS); } return $keys; @@ -91,7 +96,8 @@ public function getKeys( $use_cache = true ) : array { * * @return array */ - protected function requestJwks() : array { - return ( new WP_Auth0_Api_Get_Jwks( $this->options, $this->options->get_auth_domain() ) )->call(); + protected function requestJwks(): array + { + return (new WP_Auth0_Api_Get_Jwks($this->options, $this->options->get_auth_domain()))->call(); } } diff --git a/lib/token-verifier/WP_Auth0_SignatureVerifier.php b/lib/token-verifier/WP_Auth0_SignatureVerifier.php index 1522c9de5..1351cccfb 100644 --- a/lib/token-verifier/WP_Auth0_SignatureVerifier.php +++ b/lib/token-verifier/WP_Auth0_SignatureVerifier.php @@ -1,4 +1,5 @@ alg = $alg; $this->parser = new Parser(); } @@ -62,26 +65,27 @@ public function __construct( string $alg ) { * @throws WP_Auth0_InvalidIdTokenException If token algorithm does not match the validator. * @throws WP_Auth0_InvalidIdTokenException If token algorithm signature cannot be validated. */ - final public function verifyAndDecode( string $token ) : Token { + final public function verifyAndDecode(string $token): Token + { try { - $parsedToken = $this->parser->parse( $token ); - } catch ( InvalidArgumentException $e ) { - throw new WP_Auth0_InvalidIdTokenException( 'ID token could not be decoded' ); + $parsedToken = $this->parser->parse($token); + } catch (InvalidArgumentException $e) { + throw new WP_Auth0_InvalidIdTokenException('ID token could not be decoded'); } - $tokenAlg = $parsedToken->getHeader( 'alg', false ); - if ( $tokenAlg !== $this->alg ) { + $tokenAlg = $parsedToken->getHeader('alg', false); + if ($tokenAlg !== $this->alg) { throw new WP_Auth0_InvalidIdTokenException( - sprintf( + esc_html(sprintf( 'Signature algorithm of "%s" is not supported. Expected the ID token to be signed with "%s".', $tokenAlg, $this->alg - ) + )) ); } - if ( ! $this->checkSignature( $parsedToken ) ) { - throw new WP_Auth0_InvalidIdTokenException( 'Invalid ID token signature' ); + if (!$this->checkSignature($parsedToken)) { + throw new WP_Auth0_InvalidIdTokenException('Invalid ID token signature'); } return $parsedToken; diff --git a/lib/token-verifier/WP_Auth0_SymmetricVerifier.php b/lib/token-verifier/WP_Auth0_SymmetricVerifier.php index cfc3497aa..ab7ad3a30 100644 --- a/lib/token-verifier/WP_Auth0_SymmetricVerifier.php +++ b/lib/token-verifier/WP_Auth0_SymmetricVerifier.php @@ -1,4 +1,5 @@ clientSecret = $clientSecret; - parent::__construct( 'HS256' ); + parent::__construct('HS256'); } /** @@ -42,8 +45,9 @@ public function __construct( string $clientSecret ) { * * @return boolean */ - protected function checkSignature( Token $token ) : bool { - return $token->verify( new HsSigner(), $this->clientSecret ); + protected function checkSignature(Token $token): bool + { + return $token->verify(new HsSigner(), $this->clientSecret); } /** @@ -51,7 +55,8 @@ protected function checkSignature( Token $token ) : bool { * * @return string */ - protected function getAlgorithm() : string { + protected function getAlgorithm(): string + { return 'HS256'; } } diff --git a/templates/a0-error-log.php b/templates/a0-error-log.php index de55f3435..08b0e5618 100644 --- a/templates/a0-error-log.php +++ b/templates/a0-error-log.php @@ -1,4 +1,5 @@
-

- +

+
-
- + +
- + - - - - - - - + + + + + + + - - - - - - + - - - - - + - - + + + + + + + + + + +
diff --git a/templates/a0-widget-setup-form.php b/templates/a0-widget-setup-form.php index 5d28a17ac..4d288fb60 100644 --- a/templates/a0-widget-setup-form.php +++ b/templates/a0-widget-setup-form.php @@ -1,99 +1,81 @@

- - + +

showAsModal() ) : - $modal_trigger_name = isset( $instance['modal_trigger_name'] ) ? $instance['modal_trigger_name'] : ''; - ?> +if ($this->showAsModal()) : + $modal_trigger_name = isset($instance['modal_trigger_name']) ? $instance['modal_trigger_name'] : ''; +?>

- - + +

- - + +

- - + +

- +
-

- /> - -   - /> - -   - /> - -
+
+ /> + +   + /> + +   + /> + +

- - - -
. + + + +
.

- - + +
- +
- %s', - __( 'List of all modifiable options', 'wp-auth0' ) - ); - ?> - + %s', + esc_html__('List of all modifiable options', 'wp-auth0') + ), ['a' => ['href' => [], 'target' => []]]); + ?> +
- +

- - + +
- - - + + +

diff --git a/templates/auth0-login-form.php b/templates/auth0-login-form.php index 88feb3694..d5c8f0fd6 100644 --- a/templates/auth0-login-form.php +++ b/templates/auth0-login-form.php @@ -1,20 +1,20 @@ get( 'wordpress_login_enabled' ); +$wle = $auth0_options->get('wordpress_login_enabled'); ?> - diff --git a/tests/Unit/EmailVerificationTest.php b/tests/Unit/EmailVerificationTest.php index 85e7a2314..073061db1 100644 --- a/tests/Unit/EmailVerificationTest.php +++ b/tests/Unit/EmailVerificationTest.php @@ -1,4 +1,5 @@ getUserinfo( 'not-auth0' ); + $userinfo = $this->getUserinfo('not-auth0'); // 1. Check that only the default message appears if this is not an Auth0 strategy. ob_start(); - WP_Auth0_Email_Verification::render_die( $userinfo ); - $this->assertEquals( '

This site requires a verified email address.

', ob_get_clean() ); + WP_Auth0_Email_Verification::render_die($userinfo); + $this->assertEquals('

This site requires a verified email address.

', ob_get_clean()); // Set the userinfo as an Auth0 strategy. - $userinfo = $this->getUserinfo( 'auth0' ); + $userinfo = $this->getUserinfo('auth0'); ob_start(); - WP_Auth0_Email_Verification::render_die( $userinfo ); + WP_Auth0_Email_Verification::render_die($userinfo); $html = ob_get_clean(); // 2. Check that required HTML and JS elements exist - $this->assertStringContainsString( 'This site requires a verified email address', $html ); - $this->assertStringContainsString( 'id="js-a0-resend-verification"', $html ); - $this->assertStringContainsString( 'Resend verification email', $html ); - $this->assertStringContainsString( 'var WPAuth0EmailVerification', $html ); - $this->assertStringContainsString( 'nonce:"' . wp_create_nonce( WP_Auth0_Email_Verification::RESEND_NONCE_ACTION ) . '"', $html ); - $this->assertStringContainsString( 'sub:"' . $userinfo->sub . '"', $html ); - $this->assertStringContainsString( '//code.jquery.com/jquery-', $html ); - $this->assertStringContainsString( 'assets/js/die-with-verify-email.js?ver=' . WPA0_VERSION, $html ); + $this->assertStringContainsString('This site requires a verified email address', $html); + $this->assertStringContainsString('id="js-a0-resend-verification"', $html); + $this->assertStringContainsString('Resend verification email', $html); + $this->assertStringContainsString('var WPAuth0EmailVerification', $html); + $this->assertStringContainsString('nonce:"' . wp_create_nonce(WP_Auth0_Email_Verification::RESEND_NONCE_ACTION) . '"', $html); + $this->assertStringContainsString('sub:"' . $userinfo->sub . '"', $html); + $this->assertStringContainsString('//code.jquery.com/jquery-', $html); + $this->assertStringContainsString('assets/js/die-with-verify-email.js?ver=' . WPA0_VERSION, $html); add_filter( 'auth0_verify_email_page', - function() { + function () { return '__test_auth0_verify_email_page__'; }, 10 @@ -101,65 +105,69 @@ function() { // 3. Test that the auth0_verify_email_page returns passed-in content. ob_start(); - WP_Auth0_Email_Verification::render_die( $userinfo ); - $this->assertEquals( '__test_auth0_verify_email_page__', ob_get_clean() ); + WP_Auth0_Email_Verification::render_die($userinfo); + $this->assertEquals('__test_auth0_verify_email_page__', ob_get_clean()); } - public function testThatResendActionFailsWhenBadAjaxNonce() { + public function testThatResendActionFailsWhenBadAjaxNonce() + { $this->startAjaxHalting(); $_REQUEST['_ajax_nonce'] = uniqid(); try { wp_auth0_ajax_resend_verification_email(); $error_msg = 'No exception caught'; - } catch ( Exception $e ) { + } catch (Exception $e) { $error_msg = $e->getMessage(); } - $this->assertEquals( 'bad_nonce', $error_msg ); + $this->assertEquals('bad_nonce', $error_msg); } - public function testThatResendActionFailsWithMissingSub() { + public function testThatResendActionFailsWithMissingSub() + { $this->startAjaxHalting(); - $_REQUEST['_ajax_nonce'] = wp_create_nonce( WP_Auth0_Email_Verification::RESEND_NONCE_ACTION ); + $_REQUEST['_ajax_nonce'] = wp_create_nonce(WP_Auth0_Email_Verification::RESEND_NONCE_ACTION); ob_start(); try { wp_auth0_ajax_resend_verification_email(); $error_msg = 'No exception caught'; - } catch ( Exception $e ) { + } catch (Exception $e) { $error_msg = $e->getMessage(); } - $this->assertEquals( 'die_ajax', $error_msg ); - $this->assertEquals( '{"success":false,"data":{"error":"No Auth0 user ID provided."}}', ob_get_clean() ); + $this->assertEquals('die_ajax', $error_msg); + $this->assertEquals('{"success":false,"data":{"error":"No Auth0 user ID provided."}}', ob_get_clean()); } - public function testThatResendActionFailsWhenApiCallFails() { + public function testThatResendActionFailsWhenApiCallFails() + { $this->startAjaxHalting(); - $_REQUEST['_ajax_nonce'] = wp_create_nonce( WP_Auth0_Email_Verification::RESEND_NONCE_ACTION ); + $_REQUEST['_ajax_nonce'] = wp_create_nonce(WP_Auth0_Email_Verification::RESEND_NONCE_ACTION); $_POST['sub'] = $this->getUserinfo()->sub; ob_start(); try { wp_auth0_ajax_resend_verification_email(); $error_msg = 'No exception caught'; - } catch ( Exception $e ) { + } catch (Exception $e) { $error_msg = $e->getMessage(); } - $this->assertEquals( 'die_ajax', $error_msg ); - $this->assertEquals( '{"success":false,"data":{"error":"API call failed."}}', ob_get_clean() ); + $this->assertEquals('die_ajax', $error_msg); + $this->assertEquals('{"success":false,"data":{"error":"API call failed."}}', ob_get_clean()); } /** * Test AJAX email verification send. */ - public function testResendVerificationEmail() { + public function testResendVerificationEmail() + { $this->startHttpMocking(); $this->startAjaxHalting(); - $this->setApiToken( 'update:users' ); + $this->setApiToken('update:users'); - $_REQUEST['_ajax_nonce'] = wp_create_nonce( WP_Auth0_Email_Verification::RESEND_NONCE_ACTION ); + $_REQUEST['_ajax_nonce'] = wp_create_nonce(WP_Auth0_Email_Verification::RESEND_NONCE_ACTION); $_POST['sub'] = $this->getUserinfo()->sub; $this->http_request_type = 'success_create_empty_body'; @@ -167,12 +175,12 @@ public function testResendVerificationEmail() { try { wp_auth0_ajax_resend_verification_email(); $error_msg = 'No exception caught'; - } catch ( Exception $e ) { + } catch (Exception $e) { $error_msg = $e->getMessage(); } - $this->assertEquals( 'die_ajax', $error_msg ); + $this->assertEquals('die_ajax', $error_msg); - $this->assertEquals( '{"success":true}', ob_get_clean() ); + $this->assertEquals('{"success":true}', ob_get_clean()); } /** @@ -181,7 +189,8 @@ public function testResendVerificationEmail() { * * @param string $message - HTML to show on the wp_die page. */ - public function wp_die_handler( $message ) { - echo $message; + public function wp_die_handler($message) + { + echo wp_kses($message, ['p' => [], 'a' => ['href' => []]]); } } diff --git a/tests/Unit/LoginManagerRedirectLoginTest.php b/tests/Unit/LoginManagerRedirectLoginTest.php index e91dd4d75..e3f297c54 100644 --- a/tests/Unit/LoginManagerRedirectLoginTest.php +++ b/tests/Unit/LoginManagerRedirectLoginTest.php @@ -1,4 +1,5 @@ login = new WP_Auth0_LoginManager( new WP_Auth0_UsersRepo( self::$opts ), self::$opts ); + $this->login = new WP_Auth0_LoginManager(new WP_Auth0_UsersRepo(self::$opts), self::$opts); - self::$opts->set( 'requires_verified_email', false ); + self::$opts->set('requires_verified_email', false); - self::$users_repo = new WP_Auth0_UsersRepo( self::$opts ); + self::$users_repo = new WP_Auth0_UsersRepo(self::$opts); $users_repo = self::$users_repo; // PHP 5.6. - $users_repo::update_meta( 1, 'auth0_id', 'auth0|1234567890' ); + $users_repo::update_meta(1, 'auth0_id', 'auth0|1234567890'); - add_filter( 'auth0_get_wp_user', [ $this, 'auth0_get_wp_user_handler' ], 1, 2 ); + add_filter('auth0_get_wp_user', [$this, 'auth0_get_wp_user_handler'], 1, 2); - $this->setApiToken( 'read:users' ); + $this->setApiToken('read:users'); } /** * Runs after each test method. */ - public function tearDown(): void { + public function tearDown(): void + { parent::tearDown(); - remove_filter( 'auth0_get_wp_user', [ $this, 'auth0_get_wp_user_handler' ], 1 ); - remove_filter( 'auth0_use_management_api_for_userinfo', '__return_false', 10 ); + remove_filter('auth0_get_wp_user', [$this, 'auth0_get_wp_user_handler'], 1); + remove_filter('auth0_use_management_api_for_userinfo', '__return_false', 10); } /** @@ -62,15 +66,16 @@ public function tearDown(): void { * * @throws Exception - Always. */ - public function auth0_get_wp_user_handler( $user, $userinfo ) { - throw new Exception( + public function auth0_get_wp_user_handler($user, $userinfo) + { + throw new Exception(esc_html( serialize( [ 'user' => $user, 'userinfo' => $userinfo, ] ) - ); + )); } /** @@ -84,7 +89,8 @@ public function auth0_get_wp_user_handler( $user, $userinfo ) { * * @throws Exception - If set to halt on response. */ - public function httpMock( $response_type = null, array $args = null, $url = null ) { + public function httpMock($response_type = null, array $args = null, $url = null) + { $response_type = $response_type ?: $this->getResponseType(); $id_token_payload = [ 'sub' => '__test_id_token_sub__', @@ -95,27 +101,27 @@ public function httpMock( $response_type = null, array $args = null, $url = null 'iat' => time() - 1000, ]; - switch ( $response_type ) { + switch ($response_type) { case 'success_exchange_code_valid_HS_id_token': - $id_token = self::makeHsToken( $id_token_payload, '__test_client_secret__' ); + $id_token = self::makeHsToken($id_token_payload, '__test_client_secret__'); return [ 'body' => sprintf( '{"access_token":"__test_access_token__","id_token":"%s"}', $id_token ), - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_exchange_code_valid_RS_id_token': - $id_token = self::makeRsToken( $id_token_payload ); + $id_token = self::makeRsToken($id_token_payload); return [ 'body' => sprintf( '{"access_token":"__test_access_token__","id_token":"%s"}', $id_token ), - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; } - return $this->httpMockDefault( $response_type, $args, $url ); + return $this->httpMockDefault($response_type, $args, $url); } /** @@ -124,17 +130,18 @@ public function httpMock( $response_type = null, array $args = null, $url = null * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_InvalidIdTokenException - Should not be encountered during this test. */ - public function testThatInvalidConfigurationHaltsLogin() { + public function testThatInvalidConfigurationHaltsLogin() + { $_REQUEST['code'] = uniqid(); try { $this->login->redirect_login(); $caught_exception = false; - } catch ( WP_Auth0_LoginFlowValidationException $e ) { - $caught_exception = ( 'Error exchanging code' === $e->getMessage() ); + } catch (WP_Auth0_LoginFlowValidationException $e) { + $caught_exception = ('Error exchanging code' === $e->getMessage()); } - $this->assertTrue( $caught_exception ); + $this->assertTrue($caught_exception); } /** @@ -143,21 +150,22 @@ public function testThatInvalidConfigurationHaltsLogin() { * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_InvalidIdTokenException - Should not be encountered during this test. */ - public function testThatMissingCodeHaltsLogin() { + public function testThatMissingCodeHaltsLogin() + { $this->startHttpMocking(); $this->http_request_type = 'success_code_exchange'; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); try { $this->login->redirect_login(); $caught_exception = false; - } catch ( WP_Auth0_LoginFlowValidationException $e ) { - $caught_exception = ( 'Error exchanging code' === $e->getMessage() ); + } catch (WP_Auth0_LoginFlowValidationException $e) { + $caught_exception = ('Error exchanging code' === $e->getMessage()); } - $this->assertTrue( $caught_exception ); + $this->assertTrue($caught_exception); } /** @@ -166,22 +174,23 @@ public function testThatMissingCodeHaltsLogin() { * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_InvalidIdTokenException - Should not be encountered during this test. */ - public function testThatNetworkErrorHaltsLogin() { + public function testThatNetworkErrorHaltsLogin() + { $this->startHttpMocking(); $this->http_request_type = 'wp_error'; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); $_REQUEST['code'] = uniqid(); try { $this->login->redirect_login(); $caught_exception = false; - } catch ( WP_Auth0_LoginFlowValidationException $e ) { - $caught_exception = ( 'Error exchanging code' === $e->getMessage() ); + } catch (WP_Auth0_LoginFlowValidationException $e) { + $caught_exception = ('Error exchanging code' === $e->getMessage()); } - $this->assertTrue( $caught_exception ); + $this->assertTrue($caught_exception); } /** @@ -190,22 +199,23 @@ public function testThatNetworkErrorHaltsLogin() { * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_InvalidIdTokenException - Should not be encountered during this test. */ - public function testThatApiErrorHaltsLogin() { + public function testThatApiErrorHaltsLogin() + { $this->startHttpMocking(); $this->http_request_type = 'auth0_api_error'; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); $_REQUEST['code'] = uniqid(); try { $this->login->redirect_login(); $caught_exception = false; - } catch ( WP_Auth0_LoginFlowValidationException $e ) { - $caught_exception = ( 'Error exchanging code' === $e->getMessage() ); + } catch (WP_Auth0_LoginFlowValidationException $e) { + $caught_exception = ('Error exchanging code' === $e->getMessage()); } - $this->assertTrue( $caught_exception ); + $this->assertTrue($caught_exception); } /** @@ -214,54 +224,56 @@ public function testThatApiErrorHaltsLogin() { * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_InvalidIdTokenException - Should not be encountered during this test. */ - public function testThatAccessDeniedLogsCorrectError() { + public function testThatAccessDeniedLogsCorrectError() + { $this->startHttpMocking(); $this->http_request_type = 'auth0_access_denied'; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); $_REQUEST['code'] = uniqid(); try { $caught_exception = false; $this->login->redirect_login(); - } catch ( WP_Auth0_LoginFlowValidationException $e ) { - $caught_exception = ( 'Error exchanging code' === $e->getMessage() ); + } catch (WP_Auth0_LoginFlowValidationException $e) { + $caught_exception = ('Error exchanging code' === $e->getMessage()); } - $this->assertTrue( $caught_exception ); + $this->assertTrue($caught_exception); $error_log = self::$error_log->get(); - $this->assertCount( 1, $error_log ); - $this->assertStringContainsString( 'WP_Auth0_Api_Exchange_Code::handle_response', $error_log[0]['section'] ); - $this->assertStringContainsString( 'Please check the Client Secret', $error_log[0]['message'] ); + $this->assertCount(1, $error_log); + $this->assertStringContainsString('WP_Auth0_Api_Exchange_Code::handle_response', $error_log[0]['section']); + $this->assertStringContainsString('Please check the Client Secret', $error_log[0]['message']); } /** * Test that the exchange code call is formatted properly. */ - public function testThatExchangeTokenCallIsCorrect() { + public function testThatExchangeTokenCallIsCorrect() + { $this->startHttpHalting(); - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); $_REQUEST['code'] = uniqid(); try { $http_data = []; $this->login->redirect_login(); - } catch ( Exception $e ) { - $http_data = unserialize( $e->getMessage() ); + } catch (Exception $e) { + $http_data = unserialize($e->getMessage()); } - $this->assertNotEmpty( $http_data ); - $this->assertEquals( 'https://test.auth0.com/oauth/token', $http_data['url'] ); - $this->assertEquals( site_url( '/index.php?auth0=1' ), $http_data['body']['redirect_uri'] ); - $this->assertEquals( $_REQUEST['code'], $http_data['body']['code'] ); - $this->assertEquals( '__test_client_id__', $http_data['body']['client_id'] ); - $this->assertEquals( '__test_client_secret__', $http_data['body']['client_secret'] ); - $this->assertEquals( 'authorization_code', $http_data['body']['grant_type'] ); + $this->assertNotEmpty($http_data); + $this->assertEquals('https://test.auth0.com/oauth/token', $http_data['url']); + $this->assertEquals(site_url('/index.php?auth0=1'), $http_data['body']['redirect_uri']); + $this->assertEquals($_REQUEST['code'], $http_data['body']['code']); + $this->assertEquals('__test_client_id__', $http_data['body']['client_id']); + $this->assertEquals('__test_client_secret__', $http_data['body']['client_secret']); + $this->assertEquals('authorization_code', $http_data['body']['grant_type']); } /** @@ -270,14 +282,15 @@ public function testThatExchangeTokenCallIsCorrect() { * @throws WP_Auth0_BeforeLoginException - Should not be encountered during this test. * @throws WP_Auth0_LoginFlowValidationException - Should not be encountered during this test. */ - public function testThatInvalidIdTokenHaltsLogin() { + public function testThatInvalidIdTokenHaltsLogin() + { $this->startHttpMocking(); $this->http_request_type = 'success_code_exchange'; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); - self::$opts->set( 'client_signing_algorithm', 'HS256' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); + self::$opts->set('client_signing_algorithm', 'HS256'); $_REQUEST['code'] = uniqid(); try { @@ -285,17 +298,18 @@ public function testThatInvalidIdTokenHaltsLogin() { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( WP_Auth0_InvalidIdTokenException $e ) { + } catch (WP_Auth0_InvalidIdTokenException $e) { $e_message = $e->getMessage(); } - $this->assertEquals( 'ID token could not be decoded', $e_message ); + $this->assertEquals('ID token could not be decoded', $e_message); } /** * Test that the user information is retrieved via the Management API. */ - public function testThatGetUserCallIsCorrect() { + public function testThatGetUserCallIsCorrect() + { $this->startHttpMocking(); $this->http_request_type = [ // Mocked successful code exchange with a valid ID token. @@ -304,10 +318,10 @@ public function testThatGetUserCallIsCorrect() { 'halt', ]; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); - self::$opts->set( 'client_signing_algorithm', 'HS256' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); + self::$opts->set('client_signing_algorithm', 'HS256'); $_REQUEST['code'] = uniqid(); $_COOKIE['auth0_nonce'] = '__test_nonce__'; @@ -316,19 +330,20 @@ public function testThatGetUserCallIsCorrect() { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( Exception $e ) { - $http_data = unserialize( $e->getMessage() ); + } catch (Exception $e) { + $http_data = unserialize($e->getMessage()); } - $this->assertNotEmpty( $http_data ); - $this->assertEquals( 'https://test.auth0.com/api/v2/users/__test_id_token_sub__', $http_data['url'] ); - $this->assertEquals( 'Bearer __test_access_token__', $http_data['headers']['Authorization'] ); + $this->assertNotEmpty($http_data); + $this->assertEquals('https://test.auth0.com/api/v2/users/__test_id_token_sub__', $http_data['url']); + $this->assertEquals('Bearer __test_access_token__', $http_data['headers']['Authorization']); } /** * Test that the user information is retrieved via the Management API by default. */ - public function testThatLoginUserIsCalledWithManagementApiUserinfo() { + public function testThatLoginUserIsCalledWithManagementApiUserinfo() + { $this->startHttpMocking(); $this->http_request_type = [ // Mocked successful code exchange with a valid ID token. @@ -337,10 +352,10 @@ public function testThatLoginUserIsCalledWithManagementApiUserinfo() { 'success_get_user', ]; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); - self::$opts->set( 'client_signing_algorithm', 'HS256' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); + self::$opts->set('client_signing_algorithm', 'HS256'); $_REQUEST['code'] = uniqid(); $_COOKIE['auth0_nonce'] = '__test_nonce__'; @@ -349,22 +364,23 @@ public function testThatLoginUserIsCalledWithManagementApiUserinfo() { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( Exception $e ) { - $user_data = unserialize( $e->getMessage() ); + } catch (Exception $e) { + $user_data = unserialize($e->getMessage()); } - $this->assertTrue( $user_data['user'] instanceof WP_User ); - $this->assertEquals( 1, $user_data['user']->ID ); - $this->assertEquals( 'auth0|1234567890', $user_data['userinfo']->user_id ); - $this->assertEquals( 'auth0|1234567890', $user_data['userinfo']->sub ); - $this->assertNotEmpty( $user_data['userinfo']->user_metadata ); - $this->assertNotEmpty( $user_data['userinfo']->app_metadata ); + $this->assertTrue($user_data['user'] instanceof WP_User); + $this->assertEquals(1, $user_data['user']->ID); + $this->assertEquals('auth0|1234567890', $user_data['userinfo']->user_id); + $this->assertEquals('auth0|1234567890', $user_data['userinfo']->sub); + $this->assertNotEmpty($user_data['userinfo']->user_metadata); + $this->assertNotEmpty($user_data['userinfo']->app_metadata); } /** * Test that the user information is from the ID token if the Management API fails. */ - public function testThatLoginUserIsCalledWithIdTokenIfNoApiAccess() { + public function testThatLoginUserIsCalledWithIdTokenIfNoApiAccess() + { $this->startHttpMocking(); $this->http_request_type = [ // Mocked successful code exchange with a valid ID token. @@ -373,10 +389,10 @@ public function testThatLoginUserIsCalledWithIdTokenIfNoApiAccess() { 'auth0_api_error', ]; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); - self::$opts->set( 'client_signing_algorithm', 'HS256' ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); + self::$opts->set('client_signing_algorithm', 'HS256'); $_REQUEST['code'] = uniqid(); $_COOKIE['auth0_nonce'] = '__test_nonce__'; @@ -385,19 +401,20 @@ public function testThatLoginUserIsCalledWithIdTokenIfNoApiAccess() { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( Exception $e ) { - $user_data = unserialize( $e->getMessage() ); + } catch (Exception $e) { + $user_data = unserialize($e->getMessage()); } - $this->assertEmpty( $user_data['user'] ); - $this->assertEquals( '__test_id_token_sub__', $user_data['userinfo']->user_id ); - $this->assertEquals( '__test_id_token_sub__', $user_data['userinfo']->sub ); + $this->assertEmpty($user_data['user']); + $this->assertEquals('__test_id_token_sub__', $user_data['userinfo']->user_id); + $this->assertEquals('__test_id_token_sub__', $user_data['userinfo']->sub); } /** * Test that the user information is from the ID token if migrations are being used. */ - public function testThatLoginUserIsCalledWithIdTokenIfFilterIsSetToFalse() { + public function testThatLoginUserIsCalledWithIdTokenIfFilterIsSetToFalse() + { $this->startHttpMocking(); $this->http_request_type = [ // Mocked successful code exchange with a valid ID token. @@ -406,11 +423,11 @@ public function testThatLoginUserIsCalledWithIdTokenIfFilterIsSetToFalse() { 'success_get_user', ]; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_secret', '__test_client_secret__' ); - self::$opts->set( 'client_signing_algorithm', 'HS256' ); - add_filter( 'auth0_use_management_api_for_userinfo', '__return_false', 10 ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_secret', '__test_client_secret__'); + self::$opts->set('client_signing_algorithm', 'HS256'); + add_filter('auth0_use_management_api_for_userinfo', '__return_false', 10); $_REQUEST['code'] = uniqid(); $_COOKIE['auth0_nonce'] = '__test_nonce__'; @@ -419,11 +436,11 @@ public function testThatLoginUserIsCalledWithIdTokenIfFilterIsSetToFalse() { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( Exception $e ) { - $user_data = unserialize( $e->getMessage() ); + } catch (Exception $e) { + $user_data = unserialize($e->getMessage()); } - $this->assertEquals( '__test_id_token_sub__', $user_data['userinfo']->user_id ); + $this->assertEquals('__test_id_token_sub__', $user_data['userinfo']->user_id); } /** @@ -431,7 +448,8 @@ public function testThatLoginUserIsCalledWithIdTokenIfFilterIsSetToFalse() { * @throws WP_Auth0_InvalidIdTokenException Should not be thrown in this test. * @throws WP_Auth0_LoginFlowValidationException Should not be thrown in this test. */ - public function testThatGetJwksIsCalledForRs256IdToken() { + public function testThatGetJwksIsCalledForRs256IdToken() + { $this->startHttpMocking(); $this->http_request_type = [ // Mocked successful code exchange with a valid ID token. @@ -440,22 +458,22 @@ public function testThatGetJwksIsCalledForRs256IdToken() { 'success_jwks', ]; - self::$opts->set( 'domain', 'test.auth0.com' ); - self::$opts->set( 'client_id', '__test_client_id__' ); - self::$opts->set( 'client_signing_algorithm', 'RS256' ); - self::$opts->set( 'cache_expiration', 999999 ); + self::$opts->set('domain', 'test.auth0.com'); + self::$opts->set('client_id', '__test_client_id__'); + self::$opts->set('client_signing_algorithm', 'RS256'); + self::$opts->set('cache_expiration', 999999); $_REQUEST['code'] = uniqid(); $_COOKIE['auth0_nonce'] = '__test_nonce__'; try { // Need to hide error messages here because a cookie is set. // phpcs:ignore @$this->login->redirect_login(); - } catch ( InvalidArgumentException $e ) { + } catch (InvalidArgumentException $e) { // Stop process at next exception. } - $cached_jwks = get_transient( WPA0_JWKS_CACHE_TRANSIENT_NAME ); + $cached_jwks = get_transient(WPA0_JWKS_CACHE_TRANSIENT_NAME); - $this->assertArrayHasKey( '__test_kid_1__', $cached_jwks ); + $this->assertArrayHasKey('__test_kid_1__', $cached_jwks); } } diff --git a/tests/classes/Test_WP_Auth0_Api_Abstract.php b/tests/classes/Test_WP_Auth0_Api_Abstract.php index 2dd6fd5c8..e0e29ec6a 100644 --- a/tests/classes/Test_WP_Auth0_Api_Abstract.php +++ b/tests/classes/Test_WP_Auth0_Api_Abstract.php @@ -1,4 +1,5 @@ http_method ) ) { - throw new Exception( 'No HTTP method set. Call $this->set_http_method() first.' ); + public function call() + { + if (empty($this->http_method)) { + throw new Exception('No HTTP method set. Call $this->set_http_method() first.'); } - return $this->{$this->http_method}()->handle_response( __METHOD__ ); + return $this->{$this->http_method}()->handle_response(__METHOD__); } /** @@ -41,12 +44,13 @@ public function call() { * * @return boolean */ - public function handle_response( $method ) { - if ( $this->handle_wp_error( $method ) ) { + public function handle_response($method) + { + if ($this->handle_wp_error($method)) { return 'caught_wp_error'; } - if ( $this->handle_failed_response( $method ) ) { + if ($this->handle_failed_response($method)) { return 'caught_failed_response'; } @@ -63,9 +67,10 @@ public function handle_response( $method ) { * * @throws Exception - If the method does not exist. */ - public function set_http_method( $method ) { - if ( ! method_exists( $this, $method ) ) { - throw new Exception( 'Method ' . $method . ' does not exist.' ); + public function set_http_method($method) + { + if (!method_exists($this, $method)) { + throw new Exception(esc_html('Method ' . $method . ' does not exist.')); } $this->http_method = $method; return $this; @@ -78,12 +83,13 @@ public function set_http_method( $method ) { * * @return array|mixed */ - public function get_request( $key = null ) { + public function get_request($key = null) + { $request = array( 'body' => $this->body, 'headers' => $this->headers, 'url' => $this->build_url(), ); - return $key && array_key_exists( $key, $request ) ? $request[ $key ] : $request; + return $key && array_key_exists($key, $request) ? $request[$key] : $request; } } diff --git a/tests/traits/ajaxHelpers.php b/tests/traits/ajaxHelpers.php index 7aa51d827..f29b4be23 100644 --- a/tests/traits/ajaxHelpers.php +++ b/tests/traits/ajaxHelpers.php @@ -1,4 +1,5 @@ $url, 'method' => $args['method'], 'headers' => $args['headers'], - 'body' => is_string( $args['body'] ) ? json_decode( $args['body'], true ) : $args['body'], + 'body' => is_string($args['body']) ? json_decode($args['body'], true) : $args['body'], 'preempt' => $preempt, ] ); - throw new Exception( $error_msg ); + throw new Exception(esc_html($error_msg)); } /** * Stop halting HTTP requests. * Use this in a tearDown() method in the test suite. */ - public function stopHttpHalting() { - remove_filter( 'pre_http_request', [ $this, 'httpHalt' ], 1 ); + public function stopHttpHalting() + { + remove_filter('pre_http_request', [$this, 'httpHalt'], 1); } /** * Start mocking all HTTP requests. * Use this at the top of tests that should test behavior for different HTTP responses. */ - public function startHttpMocking() { - add_filter( 'pre_http_request', [ $this, 'httpMock' ], 1, 3 ); + public function startHttpMocking() + { + add_filter('pre_http_request', [$this, 'httpMock'], 1, 3); } /** @@ -70,9 +76,10 @@ public function startHttpMocking() { * * @return string|null */ - public function getResponseType() { - if ( is_array( $this->http_request_type ) ) { - return array_shift( $this->http_request_type ); + public function getResponseType() + { + if (is_array($this->http_request_type)) { + return array_shift($this->http_request_type); } return $this->http_request_type; } @@ -88,62 +95,63 @@ public function getResponseType() { * * @throws Exception - If set to halt on response. */ - public function httpMock( $response_type = null, array $args = null, $url = null ) { - switch ( $response_type ?: $this->getResponseType() ) { + public function httpMock($response_type = null, array $args = null, $url = null) + { + switch ($response_type ?: $this->getResponseType()) { case 'halt': - $this->httpHalt( false, $args, $url ); - return new WP_Error( 3, 'Halted.' ); + $this->httpHalt(false, $args, $url); + return new WP_Error(3, 'Halted.'); case 'wp_error': - return new WP_Error( 1, 'Caught WP_Error.' ); + return new WP_Error(1, 'Caught WP_Error.'); case 'auth0_api_error': return [ 'body' => '{"statusCode":"caught_api_error","message":"Error","errorCode":"error_code"}', - 'response' => [ 'code' => 400 ], + 'response' => ['code' => 400], ]; case 'auth0_callback_error': return [ 'body' => '{"error":"caught_callback_error","error_description":"Auth0 callback error"}', - 'response' => [ 'code' => 400 ], + 'response' => ['code' => 400], ]; case 'auth0_access_denied': return [ 'body' => '{"error":"access_denied","error_description":"Unauthorized"}', - 'response' => [ 'code' => 401 ], + 'response' => ['code' => 401], ]; case 'other_error': return [ 'body' => '{"other_error":"Other error"}', - 'response' => [ 'code' => 500 ], + 'response' => ['code' => 500], ]; case 'success_empty_body': return [ 'body' => '', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_create_empty_body': return [ 'body' => '', - 'response' => [ 'code' => 201 ], + 'response' => ['code' => 201], ]; case 'success_create_connection': return [ 'body' => '{"id":"TEST_CREATED_CONN_ID"}', - 'response' => [ 'code' => 201 ], + 'response' => ['code' => 201], ]; case 'success_update_connection': return [ 'body' => '{"id":"TEST_UPDATED_CONN_ID"}', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_get_connections': @@ -154,7 +162,7 @@ public function httpMock( $response_type = null, array $args = null, $url = null "enabled_clients":["TEST_CLIENT_ID"], "options":{"passwordPolicy":"poor"} }]', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_get_user': @@ -170,7 +178,7 @@ public function httpMock( $response_type = null, array $args = null, $url = null "app_meta_key": "app_meta_value" } }', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_access_token': @@ -180,7 +188,7 @@ public function httpMock( $response_type = null, array $args = null, $url = null "scope":"update:users read:users", "expires_in":1000 }', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_code_exchange': @@ -192,17 +200,17 @@ public function httpMock( $response_type = null, array $args = null, $url = null "expires_in":86400, "token_type":"Bearer" }', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; case 'success_jwks': return [ 'body' => '{"keys":[{"x5c":["__test_x5c_1__"],"kid":"__test_kid_1__"}]}', - 'response' => [ 'code' => 200 ], + 'response' => ['code' => 200], ]; default: - return new WP_Error( 2, 'No mock type found.' ); + return new WP_Error(2, 'No mock type found.'); } } @@ -210,7 +218,8 @@ public function httpMock( $response_type = null, array $args = null, $url = null * Stop mocking API calls. * Use this in a tearDown() method in the test suite. */ - public function stopHttpMocking() { - remove_filter( 'pre_http_request', [ $this, 'httpMock' ], 1 ); + public function stopHttpMocking() + { + remove_filter('pre_http_request', [$this, 'httpMock'], 1); } } diff --git a/tests/traits/redirectHelpers.php b/tests/traits/redirectHelpers.php index 9a9c963fa..c86dafc3e 100644 --- a/tests/traits/redirectHelpers.php +++ b/tests/traits/redirectHelpers.php @@ -1,4 +1,5 @@ $location, 'status' => $status, ] ); - throw new Exception( $error_msg ); + throw new Exception(esc_html($error_msg)); } /** * Stop halting redirects. * Use this in a tearDown() method in the test suite. */ - public function stopRedirectHalting() { - remove_filter( 'wp_redirect', [ $this, 'haltRedirect' ], 1 ); + public function stopRedirectHalting() + { + remove_filter('wp_redirect', [$this, 'haltRedirect'], 1); } } diff --git a/tests/traits/wpDieHelper.php b/tests/traits/wpDieHelper.php index fc78c9e93..bb84e2170 100644 --- a/tests/traits/wpDieHelper.php +++ b/tests/traits/wpDieHelper.php @@ -1,4 +1,5 @@