PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.1.2
Jetpack – WP Security, Backup, Speed, & Growth v10.1.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / sso.php

sso.php in Jetpack – WP Security, Backup, Speed, & Growth 10.1.2, at modules/sso.php

1,122 lines 34.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
4 use Automattic\Jetpack\Roles;
5 use Automattic\Jetpack\Status;
6 use Automattic\Jetpack\Tracking;
7
8 require_once( JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' );
9 require_once( JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-notices.php' );
10
11 /**
12 * Module Name: Secure Sign On
13 * Module Description: Allow users to log in to this site using WordPress.com accounts
14 * Sort Order: 30
15 * Recommendation Order: 5
16 * First Introduced: 2.6
17 * Requires Connection: Yes
18 * Requires User Connection: Yes
19 * Auto Activate: No
20 * Module Tags: Developers
21 * Feature: Security
22 * Additional Search Queries: sso, single sign on, login, log in, 2fa, two-factor
23 */
24
25 class Jetpack_SSO {
26 static $instance = null;
27
28 private function __construct() {
29
30 self::$instance = $this;
31
32 add_action( 'admin_init', array( $this, 'maybe_authorize_user_after_sso' ), 1 );
33 add_action( 'admin_init', array( $this, 'register_settings' ) );
34 add_action( 'login_init', array( $this, 'login_init' ) );
35 add_action( 'delete_user', array( $this, 'delete_connection_for_user' ) );
36 add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
37 add_action( 'init', array( $this, 'maybe_logout_user' ), 5 );
38 add_action( 'jetpack_modules_loaded', array( $this, 'module_configure_button' ) );
39 add_action( 'login_form_logout', array( $this, 'store_wpcom_profile_cookies_on_logout' ) );
40 add_action( 'jetpack_unlinked_user', array( $this, 'delete_connection_for_user') );
41 add_action( 'wp_login', array( 'Jetpack_SSO', 'clear_cookies_after_login' ) );
42
43 // Adding this action so that on login_init, the action won't be sanitized out of the $action global.
44 add_action( 'login_form_jetpack-sso', '__return_true' );
45 }
46
47 /**
48 * Returns the single instance of the Jetpack_SSO object
49 *
50 * @since 2.8
51 * @return Jetpack_SSO
52 **/
53 public static function get_instance() {
54 if ( ! is_null( self::$instance ) ) {
55 return self::$instance;
56 }
57
58 return self::$instance = new Jetpack_SSO;
59 }
60
61 /**
62 * Add configure button and functionality to the module card on the Jetpack screen
63 **/
64 public static function module_configure_button() {
65 Jetpack::enable_module_configurable( __FILE__ );
66 }
67
68 /**
69 * If jetpack_force_logout == 1 in current user meta the user will be forced
70 * to logout and reauthenticate with the site.
71 **/
72 public function maybe_logout_user() {
73 global $current_user;
74
75 if ( 1 == $current_user->jetpack_force_logout ) {
76 delete_user_meta( $current_user->ID, 'jetpack_force_logout' );
77 self::delete_connection_for_user( $current_user->ID );
78 wp_logout();
79 wp_safe_redirect( wp_login_url() );
80 exit;
81 }
82 }
83
84 /**
85 * Adds additional methods the WordPress xmlrpc API for handling SSO specific features
86 *
87 * @param array $methods
88 * @return array
89 **/
90 public function xmlrpc_methods( $methods ) {
91 $methods['jetpack.userDisconnect'] = array( $this, 'xmlrpc_user_disconnect' );
92 return $methods;
93 }
94
95 /**
96 * Marks a user's profile for disconnect from WordPress.com and forces a logout
97 * the next time the user visits the site.
98 **/
99 public function xmlrpc_user_disconnect( $user_id ) {
100 $user_query = new WP_User_Query(
101 array(
102 'meta_key' => 'wpcom_user_id',
103 'meta_value' => $user_id,
104 )
105 );
106 $user = $user_query->get_results();
107 $user = $user[0];
108
109 if ( $user instanceof WP_User ) {
110 $user = wp_set_current_user( $user->ID );
111 update_user_meta( $user->ID, 'jetpack_force_logout', '1' );
112 self::delete_connection_for_user( $user->ID );
113 return true;
114 }
115 return false;
116 }
117
118 /**
119 * Enqueues scripts and styles necessary for SSO login.
120 */
121 public function login_enqueue_scripts() {
122 global $action;
123
124 if ( ! Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
125 return;
126 }
127
128 if ( is_rtl() ) {
129 wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login-rtl.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
130 } else {
131 wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
132 }
133
134 wp_enqueue_script( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION );
135 }
136
137 /**
138 * Adds Jetpack SSO classes to login body
139 *
140 * @param array $classes Array of classes to add to body tag
141 * @return array Array of classes to add to body tag
142 */
143 public function login_body_class( $classes ) {
144 global $action;
145
146 if ( ! Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
147 return $classes;
148 }
149
150 // Always add the jetpack-sso class so that we can add SSO specific styling even when the SSO form isn't being displayed.
151 $classes[] = 'jetpack-sso';
152
153 if ( ! ( new Status() )->is_staging_site() ) {
154 /**
155 * Should we show the SSO login form?
156 *
157 * $_GET['jetpack-sso-default-form'] is used to provide a fallback in case JavaScript is not enabled.
158 *
159 * The default_to_sso_login() method allows us to dynamically decide whether we show the SSO login form or not.
160 * The SSO module uses the method to display the default login form if we can not find a user to log in via SSO.
161 * But, the method could be filtered by a site admin to always show the default login form if that is preferred.
162 */
163 if ( empty( $_GET['jetpack-sso-show-default-form'] ) && Jetpack_SSO_Helpers::show_sso_login() ) {
164 $classes[] = 'jetpack-sso-form-display';
165 }
166 }
167
168 return $classes;
169 }
170
171 public function print_inline_admin_css() {
172 ?>
173 <style>
174 .jetpack-sso .message {
175 margin-top: 20px;
176 }
177
178 .jetpack-sso #login .message:first-child,
179 .jetpack-sso #login h1 + .message {
180 margin-top: 0;
181 }
182 </style>
183 <?php
184 }
185
186 /**
187 * Adds settings fields to Settings > General > Secure Sign On that allows users to
188 * turn off the login form on wp-login.php
189 *
190 * @since 2.7
191 **/
192 public function register_settings() {
193
194 add_settings_section(
195 'jetpack_sso_settings',
196 __( 'Secure Sign On' , 'jetpack' ),
197 '__return_false',
198 'jetpack-sso'
199 );
200
201 /*
202 * Settings > General > Secure Sign On
203 * Require two step authentication
204 */
205 register_setting(
206 'jetpack-sso',
207 'jetpack_sso_require_two_step',
208 array( $this, 'validate_jetpack_sso_require_two_step' )
209 );
210
211 add_settings_field(
212 'jetpack_sso_require_two_step',
213 '', // __( 'Require Two-Step Authentication' , 'jetpack' ),
214 array( $this, 'render_require_two_step' ),
215 'jetpack-sso',
216 'jetpack_sso_settings'
217 );
218
219 /*
220 * Settings > General > Secure Sign On
221 */
222 register_setting(
223 'jetpack-sso',
224 'jetpack_sso_match_by_email',
225 array( $this, 'validate_jetpack_sso_match_by_email' )
226 );
227
228 add_settings_field(
229 'jetpack_sso_match_by_email',
230 '', // __( 'Match by Email' , 'jetpack' ),
231 array( $this, 'render_match_by_email' ),
232 'jetpack-sso',
233 'jetpack_sso_settings'
234 );
235 }
236
237 /**
238 * Builds the display for the checkbox allowing user to require two step
239 * auth be enabled on WordPress.com accounts before login. Displays in Settings > General
240 *
241 * @since 2.7
242 **/
243 public function render_require_two_step() {
244 ?>
245 <label>
246 <input
247 type="checkbox"
248 name="jetpack_sso_require_two_step"
249 <?php checked( Jetpack_SSO_Helpers::is_two_step_required() ); ?>
250 <?php disabled( Jetpack_SSO_Helpers::is_require_two_step_checkbox_disabled() ); ?>
251 >
252 <?php esc_html_e( 'Require Two-Step Authentication' , 'jetpack' ); ?>
253 </label>
254 <?php
255 }
256
257 /**
258 * Validate the require two step checkbox in Settings > General
259 *
260 * @since 2.7
261 * @return boolean
262 **/
263 public function validate_jetpack_sso_require_two_step( $input ) {
264 return ( ! empty( $input ) ) ? 1 : 0;
265 }
266
267 /**
268 * Builds the display for the checkbox allowing the user to allow matching logins by email
269 * Displays in Settings > General
270 *
271 * @since 2.9
272 **/
273 public function render_match_by_email() {
274 ?>
275 <label>
276 <input
277 type="checkbox"
278 name="jetpack_sso_match_by_email"
279 <?php checked( Jetpack_SSO_Helpers::match_by_email() ); ?>
280 <?php disabled( Jetpack_SSO_Helpers::is_match_by_email_checkbox_disabled() ); ?>
281 >
282 <?php esc_html_e( 'Match by Email', 'jetpack' ); ?>
283 </label>
284 <?php
285 }
286
287 /**
288 * Validate the match by email check in Settings > General
289 *
290 * @since 2.9
291 * @return boolean
292 **/
293 public function validate_jetpack_sso_match_by_email( $input ) {
294 return ( ! empty( $input ) ) ? 1 : 0;
295 }
296
297 /**
298 * Checks to determine if the user wants to login on wp-login
299 *
300 * This function mostly exists to cover the exceptions to login
301 * that may exist as other parameters to $_GET[action] as $_GET[action]
302 * does not have to exist. By default WordPress assumes login if an action
303 * is not set, however this may not be true, as in the case of logout
304 * where $_GET[loggedout] is instead set
305 *
306 * @return boolean
307 **/
308 private function wants_to_login() {
309 $wants_to_login = false;
310
311 // Cover default WordPress behavior
312 $action = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : 'login';
313
314 // And now the exceptions
315 $action = isset( $_GET['loggedout'] ) ? 'loggedout' : $action;
316
317 if ( Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
318 $wants_to_login = true;
319 }
320
321 return $wants_to_login;
322 }
323
324 function login_init() {
325 global $action;
326
327 $tracking = new Tracking();
328
329 if ( Jetpack_SSO_Helpers::should_hide_login_form() ) {
330 /**
331 * Since the default authenticate filters fire at priority 20 for checking username and password,
332 * let's fire at priority 30. wp_authenticate_spam_check is fired at priority 99, but since we return a
333 * WP_Error in disable_default_login_form, then we won't trigger spam processing logic.
334 */
335 add_filter( 'authenticate', array( 'Jetpack_SSO_Notices', 'disable_default_login_form' ), 30 );
336
337 /**
338 * Filter the display of the disclaimer message appearing when default WordPress login form is disabled.
339 *
340 * @module sso
341 *
342 * @since 2.8.0
343 *
344 * @param bool true Should the disclaimer be displayed. Default to true.
345 */
346 $display_sso_disclaimer = apply_filters( 'jetpack_sso_display_disclaimer', true );
347 if ( $display_sso_disclaimer ) {
348 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'msg_login_by_jetpack' ) );
349 }
350 }
351
352 if ( 'jetpack-sso' === $action ) {
353 if ( isset( $_GET['result'], $_GET['user_id'], $_GET['sso_nonce'] ) && 'success' == $_GET['result'] ) {
354 $this->handle_login();
355 $this->display_sso_login_form();
356 } else {
357 if ( ( new Status() )->is_staging_site() ) {
358 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'sso_not_allowed_in_staging' ) );
359 } else {
360 // Is it wiser to just use wp_redirect than do this runaround to wp_safe_redirect?
361 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
362 $reauth = ! empty( $_GET['force_reauth'] );
363 $sso_url = $this->get_sso_url_or_die( $reauth );
364
365 $tracking->record_user_event( 'sso_login_redirect_success' );
366 wp_safe_redirect( $sso_url );
367 exit;
368 }
369 }
370 } else if ( Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
371
372 // Save cookies so we can handle redirects after SSO
373 $this->save_cookies();
374
375 /**
376 * Check to see if the site admin wants to automagically forward the user
377 * to the WordPress.com login page AND that the request to wp-login.php
378 * is not something other than login (Like logout!)
379 */
380 if ( Jetpack_SSO_Helpers::bypass_login_forward_wpcom() && $this->wants_to_login() ) {
381 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
382 $reauth = ! empty( $_GET['force_reauth'] );
383 $sso_url = $this->get_sso_url_or_die( $reauth );
384 $tracking->record_user_event( 'sso_login_redirect_bypass_success' );
385 wp_safe_redirect( $sso_url );
386 exit;
387 }
388
389 $this->display_sso_login_form();
390 }
391 }
392
393 /**
394 * Ensures that we can get a nonce from WordPress.com via XML-RPC before setting
395 * up the hooks required to display the SSO form.
396 */
397 public function display_sso_login_form() {
398 add_filter( 'login_body_class', array( $this, 'login_body_class' ) );
399 add_action( 'login_head', array( $this, 'print_inline_admin_css' ) );
400
401 if ( ( new Status() )->is_staging_site() ) {
402 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'sso_not_allowed_in_staging' ) );
403 return;
404 }
405
406 $sso_nonce = self::request_initial_nonce();
407 if ( is_wp_error( $sso_nonce ) ) {
408 return;
409 }
410
411 add_action( 'login_form', array( $this, 'login_form' ) );
412 add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts' ) );
413 }
414
415 /**
416 * Conditionally save the redirect_to url as a cookie.
417 *
418 * @since 4.6.0 Renamed to save_cookies from maybe_save_redirect_cookies
419 */
420 public static function save_cookies() {
421 if ( headers_sent() ) {
422 return new WP_Error( 'headers_sent', __( 'Cannot deal with cookie redirects, as headers are already sent.', 'jetpack' ) );
423 }
424
425 setcookie(
426 'jetpack_sso_original_request',
427 esc_url_raw( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ),
428 time() + HOUR_IN_SECONDS,
429 COOKIEPATH,
430 COOKIE_DOMAIN,
431 is_ssl(),
432 true
433 );
434
435 if ( ! empty( $_GET['redirect_to'] ) ) {
436 // If we have something to redirect to
437 $url = esc_url_raw( $_GET['redirect_to'] );
438 setcookie( 'jetpack_sso_redirect_to', $url, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
439 } elseif ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
440 // Otherwise, if it's already set, purge it.
441 setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
442 }
443 }
444
445 /**
446 * Outputs the Jetpack SSO button and description as well as the toggle link
447 * for switching between Jetpack SSO and default login.
448 */
449 function login_form() {
450 $site_name = get_bloginfo( 'name' );
451 if ( ! $site_name ) {
452 $site_name = get_bloginfo( 'url' );
453 }
454
455 $display_name = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] )
456 ? $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ]
457 : false;
458 $gravatar = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] )
459 ? $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ]
460 : false;
461
462 ?>
463 <div id="jetpack-sso-wrap">
464 <?php
465 /**
466 * Allow extension above Jetpack's SSO form.
467 *
468 * @module sso
469 *
470 * @since 8.6.0
471 */
472 do_action( 'jetpack_sso_login_form_above_wpcom' );
473
474 if ( $display_name && $gravatar ) : ?>
475 <div id="jetpack-sso-wrap__user">
476 <img width="72" height="72" src="<?php echo esc_html( $gravatar ); ?>" />
477
478 <h2>
479 <?php
480 echo wp_kses(
481 sprintf( __( 'Log in as <span>%s</span>', 'jetpack' ), esc_html( $display_name ) ),
482 array( 'span' => true )
483 );
484 ?>
485 </h2>
486 </div>
487
488 <?php endif; ?>
489
490
491 <div id="jetpack-sso-wrap__action">
492 <?php echo $this->build_sso_button( array(), 'is_primary' ); ?>
493
494 <?php if ( $display_name && $gravatar ) : ?>
495 <a rel="nofollow" class="jetpack-sso-wrap__reauth" href="<?php echo esc_url( $this->build_sso_button_url( array( 'force_reauth' => '1' ) ) ); ?>">
496 <?php esc_html_e( 'Log in as a different WordPress.com user', 'jetpack' ); ?>
497 </a>
498 <?php else : ?>
499 <p>
500 <?php
501 echo esc_html(
502 sprintf(
503 __( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack' ),
504 esc_html( $site_name )
505 )
506 );
507 ?>
508 </p>
509 <?php endif; ?>
510 </div>
511
512 <?php
513 /**
514 * Allow extension below Jetpack's SSO form.
515 *
516 * @module sso
517 *
518 * @since 8.6.0
519 */
520 do_action( 'jetpack_sso_login_form_below_wpcom' );
521
522 if ( ! Jetpack_SSO_Helpers::should_hide_login_form() ) : ?>
523 <div class="jetpack-sso-or">
524 <span><?php esc_html_e( 'Or', 'jetpack' ); ?></span>
525 </div>
526
527 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '1' ) ); ?>" class="jetpack-sso-toggle wpcom">
528 <?php
529 esc_html_e( 'Log in with username and password', 'jetpack' )
530 ?>
531 </a>
532
533 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '0' ) ); ?>" class="jetpack-sso-toggle default">
534 <?php
535 esc_html_e( 'Log in with WordPress.com', 'jetpack' )
536 ?>
537 </a>
538 <?php endif; ?>
539 </div>
540 <?php
541 }
542
543 /**
544 * Clear the cookies that store the profile information for the last
545 * WPCOM user to connect.
546 */
547 static function clear_wpcom_profile_cookies() {
548 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
549 setcookie(
550 'jetpack_sso_wpcom_name_' . COOKIEHASH,
551 ' ',
552 time() - YEAR_IN_SECONDS,
553 COOKIEPATH,
554 COOKIE_DOMAIN,
555 is_ssl()
556 );
557 }
558
559 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
560 setcookie(
561 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
562 ' ',
563 time() - YEAR_IN_SECONDS,
564 COOKIEPATH,
565 COOKIE_DOMAIN,
566 is_ssl()
567 );
568 }
569 }
570
571 /**
572 * Clear cookies that are no longer needed once the user has logged in.
573 *
574 * @since 4.8.0
575 */
576 static function clear_cookies_after_login() {
577 self::clear_wpcom_profile_cookies();
578 if ( isset( $_COOKIE[ 'jetpack_sso_nonce' ] ) ) {
579 setcookie(
580 'jetpack_sso_nonce',
581 ' ',
582 time() - YEAR_IN_SECONDS,
583 COOKIEPATH,
584 COOKIE_DOMAIN,
585 is_ssl()
586 );
587 }
588
589 if ( isset( $_COOKIE[ 'jetpack_sso_original_request' ] ) ) {
590 setcookie(
591 'jetpack_sso_original_request',
592 ' ',
593 time() - YEAR_IN_SECONDS,
594 COOKIEPATH,
595 COOKIE_DOMAIN,
596 is_ssl()
597 );
598 }
599
600 if ( isset( $_COOKIE[ 'jetpack_sso_redirect_to' ] ) ) {
601 setcookie(
602 'jetpack_sso_redirect_to',
603 ' ',
604 time() - YEAR_IN_SECONDS,
605 COOKIEPATH,
606 COOKIE_DOMAIN,
607 is_ssl()
608 );
609 }
610 }
611
612 static function delete_connection_for_user( $user_id ) {
613 if ( ! $wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true ) ) {
614 return;
615 }
616
617 $xml = new Jetpack_IXR_Client( array(
618 'wpcom_user_id' => $user_id,
619 ) );
620 $xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
621
622 if ( $xml->isError() ) {
623 return false;
624 }
625
626 // Clean up local data stored for SSO
627 delete_user_meta( $user_id, 'wpcom_user_id' );
628 delete_user_meta( $user_id, 'wpcom_user_data' );
629 self::clear_wpcom_profile_cookies();
630
631 return $xml->getResponse();
632 }
633
634 static function request_initial_nonce() {
635 $nonce = ! empty( $_COOKIE[ 'jetpack_sso_nonce' ] )
636 ? $_COOKIE[ 'jetpack_sso_nonce' ]
637 : false;
638
639 if ( ! $nonce ) {
640 $xml = new Jetpack_IXR_Client();
641 $xml->query( 'jetpack.sso.requestNonce' );
642
643 if ( $xml->isError() ) {
644 return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
645 }
646
647 $nonce = $xml->getResponse();
648
649 setcookie(
650 'jetpack_sso_nonce',
651 $nonce,
652 time() + ( 10 * MINUTE_IN_SECONDS ),
653 COOKIEPATH,
654 COOKIE_DOMAIN,
655 is_ssl()
656 );
657 }
658
659 return sanitize_key( $nonce );
660 }
661
662 /**
663 * The function that actually handles the login!
664 */
665 function handle_login() {
666 $wpcom_nonce = sanitize_key( $_GET['sso_nonce'] );
667 $wpcom_user_id = (int) $_GET['user_id'];
668
669 $xml = new Jetpack_IXR_Client();
670 $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
671
672 $user_data = $xml->isError() ? false : $xml->getResponse();
673 if ( empty( $user_data ) ) {
674 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
675 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) );
676 return;
677 }
678
679 $user_data = (object) $user_data;
680 $user = null;
681
682 /**
683 * Fires before Jetpack's SSO modifies the log in form.
684 *
685 * @module sso
686 *
687 * @since 2.6.0
688 *
689 * @param object $user_data WordPress.com User information.
690 */
691 do_action( 'jetpack_sso_pre_handle_login', $user_data );
692
693 $tracking = new Tracking();
694
695 if ( Jetpack_SSO_Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
696 $this->user_data = $user_data;
697
698 $tracking->record_user_event( 'sso_login_failed', array(
699 'error_message' => 'error_msg_enable_two_step'
700 ) );
701
702 $error = new WP_Error( 'two_step_required', __( 'You must have Two-Step Authentication enabled on your WordPress.com account.', 'jetpack' ) );
703
704 /** This filter is documented in core/src/wp-includes/pluggable.php */
705 do_action( 'wp_login_failed', $user_data->login, $error );
706 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_enable_two_step' ) );
707 return;
708 }
709
710 $user_found_with = '';
711 if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
712 $user_found_with = 'external_user_id';
713 $user = get_user_by( 'id', (int) $user_data->external_user_id );
714 if ( $user ) {
715 $expected_id = get_user_meta( $user->ID, 'wpcom_user_id', true );
716 if ( $expected_id && $expected_id != $user_data->ID ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
717 $error = new WP_Error( 'expected_wpcom_user', __( 'Something got a little mixed up and an unexpected WordPress.com user logged in.', 'jetpack' ) );
718
719 /** This filter is documented in core/src/wp-includes/pluggable.php */
720 do_action( 'wp_login_failed', $user_data->login, $error );
721 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) ); // @todo Need to have a better notice. This is only for the sake of testing the validation.
722 return;
723 }
724 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
725 }
726 }
727
728 // If we don't have one by wpcom_user_id, try by the email?
729 if ( empty( $user ) && Jetpack_SSO_Helpers::match_by_email() ) {
730 $user_found_with = 'match_by_email';
731 $user = get_user_by( 'email', $user_data->email );
732 if ( $user ) {
733 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
734 }
735 }
736
737 // If we've still got nothing, create the user.
738 $new_user_override_role = false;
739 if ( empty( $user ) && ( get_option( 'users_can_register' ) || ( $new_user_override_role = Jetpack_SSO_Helpers::new_user_override( $user_data ) ) ) ) {
740 /**
741 * If not matching by email we still need to verify the email does not exist
742 * or this blows up
743 *
744 * If match_by_email is true, we know the email doesn't exist, as it would have
745 * been found in the first pass. If get_user_by( 'email' ) doesn't find the
746 * user, then we know that email is unused, so it's safe to add.
747 */
748 if ( Jetpack_SSO_Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
749
750 if ( $new_user_override_role ) {
751 $user_data->role = $new_user_override_role;
752 }
753
754 $user = Jetpack_SSO_Helpers::generate_user( $user_data );
755 if ( ! $user ) {
756 $tracking->record_user_event( 'sso_login_failed', array(
757 'error_message' => 'could_not_create_username'
758 ) );
759 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_unable_to_create_user' ) );
760 return;
761 }
762
763 $user_found_with = $new_user_override_role
764 ? 'user_created_new_user_override'
765 : 'user_created_users_can_register';
766 } else {
767 $tracking->record_user_event( 'sso_login_failed', array(
768 'error_message' => 'error_msg_email_already_exists'
769 ) );
770
771 $this->user_data = $user_data;
772 add_action( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_email_already_exists' ) );
773 return;
774 }
775 }
776
777 /**
778 * Fires after we got login information from WordPress.com.
779 *
780 * @module sso
781 *
782 * @since 2.6.0
783 *
784 * @param WP_User|false|null $user Local User information.
785 * @param object $user_data WordPress.com User Login information.
786 */
787 do_action( 'jetpack_sso_handle_login', $user, $user_data );
788
789 if ( $user ) {
790 // Cache the user's details, so we can present it back to them on their user screen
791 update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
792
793 add_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
794 wp_set_auth_cookie( $user->ID, true );
795 remove_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
796
797 /** This filter is documented in core/src/wp-includes/user.php */
798 do_action( 'wp_login', $user->user_login, $user );
799
800 wp_set_current_user( $user->ID );
801
802 $_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( $_REQUEST['redirect_to'] ) : '';
803 $redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
804
805 // If we have a saved redirect to request in a cookie
806 if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
807 // Set that as the requested redirect to
808 $redirect_to = $_request_redirect_to = esc_url_raw( $_COOKIE['jetpack_sso_redirect_to'] );
809 }
810
811 $json_api_auth_environment = Jetpack_SSO_Helpers::get_json_api_auth_environment();
812
813 $is_json_api_auth = ! empty( $json_api_auth_environment );
814 $is_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected( $user->ID );
815 $roles = new Roles();
816 $tracking->record_user_event( 'sso_user_logged_in', array(
817 'user_found_with' => $user_found_with,
818 'user_connected' => (bool) $is_user_connected,
819 'user_role' => $roles->translate_current_user_to_role(),
820 'is_json_api_auth' => (bool) $is_json_api_auth,
821 ) );
822
823 if ( $is_json_api_auth ) {
824 Jetpack::init()->verify_json_api_authorization_request( $json_api_auth_environment );
825 Jetpack::init()->store_json_api_authorization_token( $user->user_login, $user );
826
827 } else if ( ! $is_user_connected ) {
828 wp_safe_redirect(
829 add_query_arg(
830 array(
831 'redirect_to' => $redirect_to,
832 'request_redirect_to' => $_request_redirect_to,
833 'calypso_env' => Jetpack::get_calypso_env(),
834 'jetpack-sso-auth-redirect' => '1',
835 ),
836 admin_url()
837 )
838 );
839 exit;
840 }
841
842 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
843 wp_safe_redirect(
844 /** This filter is documented in core/src/wp-login.php */
845 apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
846 );
847 exit;
848 }
849
850 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
851
852 $tracking->record_user_event( 'sso_login_failed', array(
853 'error_message' => 'cant_find_user'
854 ) );
855
856 $this->user_data = $user_data;
857
858 $error = new WP_Error( 'account_not_found', __( 'Account not found. If you already have an account, make sure you have connected to WordPress.com.', 'jetpack' ) );
859
860 /** This filter is documented in core/src/wp-includes/pluggable.php */
861 do_action( 'wp_login_failed', $user_data->login, $error );
862 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'cant_find_user' ) );
863 }
864
865 static function profile_page_url() {
866 return admin_url( 'profile.php' );
867 }
868
869 /**
870 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
871 *
872 * @param array $args An array of arguments to add to the SSO URL.
873 * @param boolean $is_primary Should the button have the `button-primary` class?
874 * @return string Returns the HTML markup for the button.
875 */
876 function build_sso_button( $args = array(), $is_primary = false ) {
877 $url = $this->build_sso_button_url( $args );
878 $classes = $is_primary
879 ? 'jetpack-sso button button-primary'
880 : 'jetpack-sso button';
881
882 return sprintf(
883 '<a rel="nofollow" href="%1$s" class="%2$s"><span>%3$s %4$s</span></a>',
884 esc_url( $url ),
885 $classes,
886 '<span class="genericon genericon-wordpress"></span>',
887 esc_html__( 'Log in with WordPress.com', 'jetpack' )
888 );
889 }
890
891 /**
892 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
893 *
894 * @param array $args An array of arguments to add to the SSO URL.
895 * @return string The URL used for SSO.
896 */
897 function build_sso_button_url( $args = array() ) {
898 $defaults = array(
899 'action' => 'jetpack-sso',
900 );
901
902 $args = wp_parse_args( $args, $defaults );
903
904 if ( ! empty( $_GET['redirect_to'] ) ) {
905 $args['redirect_to'] = urlencode( esc_url_raw( $_GET['redirect_to'] ) );
906 }
907
908 return add_query_arg( $args, wp_login_url() );
909 }
910
911 /**
912 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
913 *
914 * @param boolean $reauth Should the user be forced to reauthenticate on WordPress.com?
915 * @param array $args Optional query parameters.
916 * @return string The WordPress.com SSO URL.
917 */
918 function get_sso_url_or_die( $reauth = false, $args = array() ) {
919 $custom_login_url = Jetpack_SSO_Helpers::get_custom_login_url();
920 if ( $custom_login_url ) {
921 $args['login_url'] = rawurlencode( $custom_login_url );
922 }
923
924 if ( empty( $reauth ) ) {
925 $sso_redirect = $this->build_sso_url( $args );
926 } else {
927 self::clear_wpcom_profile_cookies();
928 $sso_redirect = $this->build_reauth_and_sso_url( $args );
929 }
930
931 // If there was an error retrieving the SSO URL, then error.
932 if ( is_wp_error( $sso_redirect ) ) {
933 $error_message = sanitize_text_field(
934 sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() )
935 );
936 $tracking = new Tracking();
937 $tracking->record_user_event( 'sso_login_redirect_failed', array(
938 'error_message' => $error_message
939 ) );
940 wp_die( $error_message );
941 }
942
943 return $sso_redirect;
944 }
945
946 /**
947 * Build WordPress.com SSO URL with appropriate query parameters.
948 *
949 * @param array $args Optional query parameters.
950 * @return string WordPress.com SSO URL
951 */
952 public function build_sso_url( $args = array() ) {
953 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
954 $defaults = array(
955 'action' => 'jetpack-sso',
956 'site_id' => Jetpack_Options::get_option( 'id' ),
957 'sso_nonce' => $sso_nonce,
958 'calypso_auth' => '1',
959 );
960
961 $args = wp_parse_args( $args, $defaults );
962
963 if ( is_wp_error( $args['sso_nonce'] ) ) {
964 return $args['sso_nonce'];
965 }
966
967 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
968 }
969
970 /**
971 * Build WordPress.com SSO URL with appropriate query parameters,
972 * including the parameters necessary to force the user to reauthenticate
973 * on WordPress.com.
974 *
975 * @param array $args Optional query parameters.
976 * @return string WordPress.com SSO URL
977 */
978 public function build_reauth_and_sso_url( $args = array() ) {
979 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
980 $redirect = $this->build_sso_url( array( 'force_auth' => '1', 'sso_nonce' => $sso_nonce ) );
981
982 if ( is_wp_error( $redirect ) ) {
983 return $redirect;
984 }
985
986 $defaults = array(
987 'action' => 'jetpack-sso',
988 'site_id' => Jetpack_Options::get_option( 'id' ),
989 'sso_nonce' => $sso_nonce,
990 'reauth' => '1',
991 'redirect_to' => urlencode( $redirect ),
992 'calypso_auth' => '1',
993 );
994
995 $args = wp_parse_args( $args, $defaults );
996
997 if ( is_wp_error( $args['sso_nonce'] ) ) {
998 return $args['sso_nonce'];
999 }
1000
1001 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
1002 }
1003
1004 /**
1005 * Determines local user associated with a given WordPress.com user ID.
1006 *
1007 * @since 2.6.0
1008 *
1009 * @param int $wpcom_user_id User ID from WordPress.com
1010 * @return object Local user object if found, null if not.
1011 */
1012 static function get_user_by_wpcom_id( $wpcom_user_id ) {
1013 $user_query = new WP_User_Query( array(
1014 'meta_key' => 'wpcom_user_id',
1015 'meta_value' => (int) $wpcom_user_id,
1016 'number' => 1,
1017 ) );
1018
1019 $users = $user_query->get_results();
1020 return $users ? array_shift( $users ) : null;
1021 }
1022
1023 /**
1024 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1025 * WordPress.com authorization flow.
1026 *
1027 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1028 * calls menu_page_url() which doesn't work properly until admin menus are registered.
1029 */
1030 function maybe_authorize_user_after_sso() {
1031 if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) {
1032 return;
1033 }
1034
1035 $redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : admin_url();
1036 $request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( $_GET['request_redirect_to'] ) : $redirect_to;
1037
1038 /** This filter is documented in core/src/wp-login.php */
1039 $redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1040
1041 /**
1042 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1043 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1044 */
1045 $redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1046 $redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1047
1048 /**
1049 * Return the raw connect URL with our redirect and attribute connection to SSO.
1050 * We remove any other filters that may be turning on the in-place connection
1051 * since we will be redirecting the user as opposed to iFraming.
1052 */
1053 remove_all_filters( 'jetpack_use_iframe_authorization_flow' );
1054 add_filter( 'jetpack_use_iframe_authorization_flow', '__return_false' );
1055 $connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1056
1057 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
1058 wp_safe_redirect( $connect_url );
1059 exit;
1060 }
1061
1062 /**
1063 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1064 * stored when the user logs out, and then deleted when the user logs in.
1065 */
1066 function store_wpcom_profile_cookies_on_logout() {
1067 if ( ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected( get_current_user_id() ) ) {
1068 return;
1069 }
1070
1071 $user_data = $this->get_user_data( get_current_user_id() );
1072 if ( ! $user_data ) {
1073 return;
1074 }
1075
1076 setcookie(
1077 'jetpack_sso_wpcom_name_' . COOKIEHASH,
1078 $user_data->display_name,
1079 time() + WEEK_IN_SECONDS,
1080 COOKIEPATH,
1081 COOKIE_DOMAIN,
1082 is_ssl()
1083 );
1084
1085 setcookie(
1086 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1087 get_avatar_url(
1088 $user_data->email,
1089 array( 'size' => 144, 'default' => 'mystery' )
1090 ),
1091 time() + WEEK_IN_SECONDS,
1092 COOKIEPATH,
1093 COOKIE_DOMAIN,
1094 is_ssl()
1095 );
1096 }
1097
1098 /**
1099 * Determines if a local user is connected to WordPress.com
1100 *
1101 * @since 2.8
1102 * @param integer $user_id - Local user id
1103 * @return boolean
1104 **/
1105 public function is_user_connected( $user_id ) {
1106 return $this->get_user_data( $user_id );
1107 }
1108
1109 /**
1110 * Retrieves a user's WordPress.com data
1111 *
1112 * @since 2.8
1113 * @param integer $user_id - Local user id
1114 * @return mixed null or stdClass
1115 **/
1116 public function get_user_data( $user_id ) {
1117 return get_user_meta( $user_id, 'wpcom_user_data', true );
1118 }
1119 }
1120
1121 Jetpack_SSO::get_instance();
1122