PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.5
Jetpack – WP Security, Backup, Speed, & Growth v10.5
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.5, at modules/sso.php

1,134 lines 34.9 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 /**
502 * Filter the messeage displayed below the SSO button.
503 *
504 * @module sso
505 *
506 * @since 10.3.0
507 *
508 * @param string $sso_explanation Message displayed below the SSO button.
509 */
510 $sso_explanation = apply_filters(
511 'jetpack_sso_login_form_explanation_text',
512 sprintf(
513 /* Translators: %s is the name of the site. */
514 __( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack' ),
515 esc_html( $site_name )
516 )
517 );
518 echo esc_html( $sso_explanation );
519 ?>
520 </p>
521 <?php endif; ?>
522 </div>
523
524 <?php
525 /**
526 * Allow extension below Jetpack's SSO form.
527 *
528 * @module sso
529 *
530 * @since 8.6.0
531 */
532 do_action( 'jetpack_sso_login_form_below_wpcom' );
533
534 if ( ! Jetpack_SSO_Helpers::should_hide_login_form() ) : ?>
535 <div class="jetpack-sso-or">
536 <span><?php esc_html_e( 'Or', 'jetpack' ); ?></span>
537 </div>
538
539 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '1' ) ); ?>" class="jetpack-sso-toggle wpcom">
540 <?php
541 esc_html_e( 'Log in with username and password', 'jetpack' )
542 ?>
543 </a>
544
545 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '0' ) ); ?>" class="jetpack-sso-toggle default">
546 <?php
547 esc_html_e( 'Log in with WordPress.com', 'jetpack' )
548 ?>
549 </a>
550 <?php endif; ?>
551 </div>
552 <?php
553 }
554
555 /**
556 * Clear the cookies that store the profile information for the last
557 * WPCOM user to connect.
558 */
559 static function clear_wpcom_profile_cookies() {
560 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
561 setcookie(
562 'jetpack_sso_wpcom_name_' . COOKIEHASH,
563 ' ',
564 time() - YEAR_IN_SECONDS,
565 COOKIEPATH,
566 COOKIE_DOMAIN,
567 is_ssl()
568 );
569 }
570
571 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
572 setcookie(
573 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
574 ' ',
575 time() - YEAR_IN_SECONDS,
576 COOKIEPATH,
577 COOKIE_DOMAIN,
578 is_ssl()
579 );
580 }
581 }
582
583 /**
584 * Clear cookies that are no longer needed once the user has logged in.
585 *
586 * @since 4.8.0
587 */
588 static function clear_cookies_after_login() {
589 self::clear_wpcom_profile_cookies();
590 if ( isset( $_COOKIE[ 'jetpack_sso_nonce' ] ) ) {
591 setcookie(
592 'jetpack_sso_nonce',
593 ' ',
594 time() - YEAR_IN_SECONDS,
595 COOKIEPATH,
596 COOKIE_DOMAIN,
597 is_ssl()
598 );
599 }
600
601 if ( isset( $_COOKIE[ 'jetpack_sso_original_request' ] ) ) {
602 setcookie(
603 'jetpack_sso_original_request',
604 ' ',
605 time() - YEAR_IN_SECONDS,
606 COOKIEPATH,
607 COOKIE_DOMAIN,
608 is_ssl()
609 );
610 }
611
612 if ( isset( $_COOKIE[ 'jetpack_sso_redirect_to' ] ) ) {
613 setcookie(
614 'jetpack_sso_redirect_to',
615 ' ',
616 time() - YEAR_IN_SECONDS,
617 COOKIEPATH,
618 COOKIE_DOMAIN,
619 is_ssl()
620 );
621 }
622 }
623
624 static function delete_connection_for_user( $user_id ) {
625 if ( ! $wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true ) ) {
626 return;
627 }
628
629 $xml = new Jetpack_IXR_Client( array(
630 'wpcom_user_id' => $user_id,
631 ) );
632 $xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
633
634 if ( $xml->isError() ) {
635 return false;
636 }
637
638 // Clean up local data stored for SSO
639 delete_user_meta( $user_id, 'wpcom_user_id' );
640 delete_user_meta( $user_id, 'wpcom_user_data' );
641 self::clear_wpcom_profile_cookies();
642
643 return $xml->getResponse();
644 }
645
646 static function request_initial_nonce() {
647 $nonce = ! empty( $_COOKIE[ 'jetpack_sso_nonce' ] )
648 ? $_COOKIE[ 'jetpack_sso_nonce' ]
649 : false;
650
651 if ( ! $nonce ) {
652 $xml = new Jetpack_IXR_Client();
653 $xml->query( 'jetpack.sso.requestNonce' );
654
655 if ( $xml->isError() ) {
656 return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
657 }
658
659 $nonce = $xml->getResponse();
660
661 setcookie(
662 'jetpack_sso_nonce',
663 $nonce,
664 time() + ( 10 * MINUTE_IN_SECONDS ),
665 COOKIEPATH,
666 COOKIE_DOMAIN,
667 is_ssl()
668 );
669 }
670
671 return sanitize_key( $nonce );
672 }
673
674 /**
675 * The function that actually handles the login!
676 */
677 function handle_login() {
678 $wpcom_nonce = sanitize_key( $_GET['sso_nonce'] );
679 $wpcom_user_id = (int) $_GET['user_id'];
680
681 $xml = new Jetpack_IXR_Client();
682 $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
683
684 $user_data = $xml->isError() ? false : $xml->getResponse();
685 if ( empty( $user_data ) ) {
686 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
687 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) );
688 return;
689 }
690
691 $user_data = (object) $user_data;
692 $user = null;
693
694 /**
695 * Fires before Jetpack's SSO modifies the log in form.
696 *
697 * @module sso
698 *
699 * @since 2.6.0
700 *
701 * @param object $user_data WordPress.com User information.
702 */
703 do_action( 'jetpack_sso_pre_handle_login', $user_data );
704
705 $tracking = new Tracking();
706
707 if ( Jetpack_SSO_Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
708 $this->user_data = $user_data;
709
710 $tracking->record_user_event( 'sso_login_failed', array(
711 'error_message' => 'error_msg_enable_two_step'
712 ) );
713
714 $error = new WP_Error( 'two_step_required', __( 'You must have Two-Step Authentication enabled on your WordPress.com account.', 'jetpack' ) );
715
716 /** This filter is documented in core/src/wp-includes/pluggable.php */
717 do_action( 'wp_login_failed', $user_data->login, $error );
718 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_enable_two_step' ) );
719 return;
720 }
721
722 $user_found_with = '';
723 if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
724 $user_found_with = 'external_user_id';
725 $user = get_user_by( 'id', (int) $user_data->external_user_id );
726 if ( $user ) {
727 $expected_id = get_user_meta( $user->ID, 'wpcom_user_id', true );
728 if ( $expected_id && $expected_id != $user_data->ID ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
729 $error = new WP_Error( 'expected_wpcom_user', __( 'Something got a little mixed up and an unexpected WordPress.com user logged in.', 'jetpack' ) );
730
731 /** This filter is documented in core/src/wp-includes/pluggable.php */
732 do_action( 'wp_login_failed', $user_data->login, $error );
733 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.
734 return;
735 }
736 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
737 }
738 }
739
740 // If we don't have one by wpcom_user_id, try by the email?
741 if ( empty( $user ) && Jetpack_SSO_Helpers::match_by_email() ) {
742 $user_found_with = 'match_by_email';
743 $user = get_user_by( 'email', $user_data->email );
744 if ( $user ) {
745 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
746 }
747 }
748
749 // If we've still got nothing, create the user.
750 $new_user_override_role = false;
751 if ( empty( $user ) && ( get_option( 'users_can_register' ) || ( $new_user_override_role = Jetpack_SSO_Helpers::new_user_override( $user_data ) ) ) ) {
752 /**
753 * If not matching by email we still need to verify the email does not exist
754 * or this blows up
755 *
756 * If match_by_email is true, we know the email doesn't exist, as it would have
757 * been found in the first pass. If get_user_by( 'email' ) doesn't find the
758 * user, then we know that email is unused, so it's safe to add.
759 */
760 if ( Jetpack_SSO_Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
761
762 if ( $new_user_override_role ) {
763 $user_data->role = $new_user_override_role;
764 }
765
766 $user = Jetpack_SSO_Helpers::generate_user( $user_data );
767 if ( ! $user ) {
768 $tracking->record_user_event( 'sso_login_failed', array(
769 'error_message' => 'could_not_create_username'
770 ) );
771 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_unable_to_create_user' ) );
772 return;
773 }
774
775 $user_found_with = $new_user_override_role
776 ? 'user_created_new_user_override'
777 : 'user_created_users_can_register';
778 } else {
779 $tracking->record_user_event( 'sso_login_failed', array(
780 'error_message' => 'error_msg_email_already_exists'
781 ) );
782
783 $this->user_data = $user_data;
784 add_action( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_email_already_exists' ) );
785 return;
786 }
787 }
788
789 /**
790 * Fires after we got login information from WordPress.com.
791 *
792 * @module sso
793 *
794 * @since 2.6.0
795 *
796 * @param WP_User|false|null $user Local User information.
797 * @param object $user_data WordPress.com User Login information.
798 */
799 do_action( 'jetpack_sso_handle_login', $user, $user_data );
800
801 if ( $user ) {
802 // Cache the user's details, so we can present it back to them on their user screen
803 update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
804
805 add_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
806 wp_set_auth_cookie( $user->ID, true );
807 remove_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
808
809 /** This filter is documented in core/src/wp-includes/user.php */
810 do_action( 'wp_login', $user->user_login, $user );
811
812 wp_set_current_user( $user->ID );
813
814 $_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( $_REQUEST['redirect_to'] ) : '';
815 $redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
816
817 // If we have a saved redirect to request in a cookie
818 if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
819 // Set that as the requested redirect to
820 $redirect_to = $_request_redirect_to = esc_url_raw( $_COOKIE['jetpack_sso_redirect_to'] );
821 }
822
823 $json_api_auth_environment = Jetpack_SSO_Helpers::get_json_api_auth_environment();
824
825 $is_json_api_auth = ! empty( $json_api_auth_environment );
826 $is_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected( $user->ID );
827 $roles = new Roles();
828 $tracking->record_user_event( 'sso_user_logged_in', array(
829 'user_found_with' => $user_found_with,
830 'user_connected' => (bool) $is_user_connected,
831 'user_role' => $roles->translate_current_user_to_role(),
832 'is_json_api_auth' => (bool) $is_json_api_auth,
833 ) );
834
835 if ( $is_json_api_auth ) {
836 Jetpack::init()->verify_json_api_authorization_request( $json_api_auth_environment );
837 Jetpack::init()->store_json_api_authorization_token( $user->user_login, $user );
838
839 } else if ( ! $is_user_connected ) {
840 wp_safe_redirect(
841 add_query_arg(
842 array(
843 'redirect_to' => $redirect_to,
844 'request_redirect_to' => $_request_redirect_to,
845 'calypso_env' => Jetpack::get_calypso_env(),
846 'jetpack-sso-auth-redirect' => '1',
847 ),
848 admin_url()
849 )
850 );
851 exit;
852 }
853
854 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
855 wp_safe_redirect(
856 /** This filter is documented in core/src/wp-login.php */
857 apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
858 );
859 exit;
860 }
861
862 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
863
864 $tracking->record_user_event( 'sso_login_failed', array(
865 'error_message' => 'cant_find_user'
866 ) );
867
868 $this->user_data = $user_data;
869
870 $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' ) );
871
872 /** This filter is documented in core/src/wp-includes/pluggable.php */
873 do_action( 'wp_login_failed', $user_data->login, $error );
874 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'cant_find_user' ) );
875 }
876
877 static function profile_page_url() {
878 return admin_url( 'profile.php' );
879 }
880
881 /**
882 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
883 *
884 * @param array $args An array of arguments to add to the SSO URL.
885 * @param boolean $is_primary Should the button have the `button-primary` class?
886 * @return string Returns the HTML markup for the button.
887 */
888 function build_sso_button( $args = array(), $is_primary = false ) {
889 $url = $this->build_sso_button_url( $args );
890 $classes = $is_primary
891 ? 'jetpack-sso button button-primary'
892 : 'jetpack-sso button';
893
894 return sprintf(
895 '<a rel="nofollow" href="%1$s" class="%2$s">%3$s %4$s</a>',
896 esc_url( $url ),
897 $classes,
898 '<span class="genericon genericon-wordpress"></span>',
899 esc_html__( 'Log in with WordPress.com', 'jetpack' )
900 );
901 }
902
903 /**
904 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
905 *
906 * @param array $args An array of arguments to add to the SSO URL.
907 * @return string The URL used for SSO.
908 */
909 function build_sso_button_url( $args = array() ) {
910 $defaults = array(
911 'action' => 'jetpack-sso',
912 );
913
914 $args = wp_parse_args( $args, $defaults );
915
916 if ( ! empty( $_GET['redirect_to'] ) ) {
917 $args['redirect_to'] = urlencode( esc_url_raw( $_GET['redirect_to'] ) );
918 }
919
920 return add_query_arg( $args, wp_login_url() );
921 }
922
923 /**
924 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
925 *
926 * @param boolean $reauth Should the user be forced to reauthenticate on WordPress.com?
927 * @param array $args Optional query parameters.
928 * @return string The WordPress.com SSO URL.
929 */
930 function get_sso_url_or_die( $reauth = false, $args = array() ) {
931 $custom_login_url = Jetpack_SSO_Helpers::get_custom_login_url();
932 if ( $custom_login_url ) {
933 $args['login_url'] = rawurlencode( $custom_login_url );
934 }
935
936 if ( empty( $reauth ) ) {
937 $sso_redirect = $this->build_sso_url( $args );
938 } else {
939 self::clear_wpcom_profile_cookies();
940 $sso_redirect = $this->build_reauth_and_sso_url( $args );
941 }
942
943 // If there was an error retrieving the SSO URL, then error.
944 if ( is_wp_error( $sso_redirect ) ) {
945 $error_message = sanitize_text_field(
946 sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() )
947 );
948 $tracking = new Tracking();
949 $tracking->record_user_event( 'sso_login_redirect_failed', array(
950 'error_message' => $error_message
951 ) );
952 wp_die( $error_message );
953 }
954
955 return $sso_redirect;
956 }
957
958 /**
959 * Build WordPress.com SSO URL with appropriate query parameters.
960 *
961 * @param array $args Optional query parameters.
962 * @return string WordPress.com SSO URL
963 */
964 public function build_sso_url( $args = array() ) {
965 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
966 $defaults = array(
967 'action' => 'jetpack-sso',
968 'site_id' => Jetpack_Options::get_option( 'id' ),
969 'sso_nonce' => $sso_nonce,
970 'calypso_auth' => '1',
971 );
972
973 $args = wp_parse_args( $args, $defaults );
974
975 if ( is_wp_error( $args['sso_nonce'] ) ) {
976 return $args['sso_nonce'];
977 }
978
979 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
980 }
981
982 /**
983 * Build WordPress.com SSO URL with appropriate query parameters,
984 * including the parameters necessary to force the user to reauthenticate
985 * on WordPress.com.
986 *
987 * @param array $args Optional query parameters.
988 * @return string WordPress.com SSO URL
989 */
990 public function build_reauth_and_sso_url( $args = array() ) {
991 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
992 $redirect = $this->build_sso_url( array( 'force_auth' => '1', 'sso_nonce' => $sso_nonce ) );
993
994 if ( is_wp_error( $redirect ) ) {
995 return $redirect;
996 }
997
998 $defaults = array(
999 'action' => 'jetpack-sso',
1000 'site_id' => Jetpack_Options::get_option( 'id' ),
1001 'sso_nonce' => $sso_nonce,
1002 'reauth' => '1',
1003 'redirect_to' => urlencode( $redirect ),
1004 'calypso_auth' => '1',
1005 );
1006
1007 $args = wp_parse_args( $args, $defaults );
1008
1009 if ( is_wp_error( $args['sso_nonce'] ) ) {
1010 return $args['sso_nonce'];
1011 }
1012
1013 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
1014 }
1015
1016 /**
1017 * Determines local user associated with a given WordPress.com user ID.
1018 *
1019 * @since 2.6.0
1020 *
1021 * @param int $wpcom_user_id User ID from WordPress.com
1022 * @return object Local user object if found, null if not.
1023 */
1024 static function get_user_by_wpcom_id( $wpcom_user_id ) {
1025 $user_query = new WP_User_Query( array(
1026 'meta_key' => 'wpcom_user_id',
1027 'meta_value' => (int) $wpcom_user_id,
1028 'number' => 1,
1029 ) );
1030
1031 $users = $user_query->get_results();
1032 return $users ? array_shift( $users ) : null;
1033 }
1034
1035 /**
1036 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1037 * WordPress.com authorization flow.
1038 *
1039 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1040 * calls menu_page_url() which doesn't work properly until admin menus are registered.
1041 */
1042 function maybe_authorize_user_after_sso() {
1043 if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) {
1044 return;
1045 }
1046
1047 $redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : admin_url();
1048 $request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( $_GET['request_redirect_to'] ) : $redirect_to;
1049
1050 /** This filter is documented in core/src/wp-login.php */
1051 $redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1052
1053 /**
1054 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1055 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1056 */
1057 $redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1058 $redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1059
1060 /**
1061 * Return the raw connect URL with our redirect and attribute connection to SSO.
1062 * We remove any other filters that may be turning on the in-place connection
1063 * since we will be redirecting the user as opposed to iFraming.
1064 */
1065 remove_all_filters( 'jetpack_use_iframe_authorization_flow' );
1066 add_filter( 'jetpack_use_iframe_authorization_flow', '__return_false' );
1067 $connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1068
1069 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
1070 wp_safe_redirect( $connect_url );
1071 exit;
1072 }
1073
1074 /**
1075 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1076 * stored when the user logs out, and then deleted when the user logs in.
1077 */
1078 function store_wpcom_profile_cookies_on_logout() {
1079 if ( ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected( get_current_user_id() ) ) {
1080 return;
1081 }
1082
1083 $user_data = $this->get_user_data( get_current_user_id() );
1084 if ( ! $user_data ) {
1085 return;
1086 }
1087
1088 setcookie(
1089 'jetpack_sso_wpcom_name_' . COOKIEHASH,
1090 $user_data->display_name,
1091 time() + WEEK_IN_SECONDS,
1092 COOKIEPATH,
1093 COOKIE_DOMAIN,
1094 is_ssl()
1095 );
1096
1097 setcookie(
1098 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1099 get_avatar_url(
1100 $user_data->email,
1101 array( 'size' => 144, 'default' => 'mystery' )
1102 ),
1103 time() + WEEK_IN_SECONDS,
1104 COOKIEPATH,
1105 COOKIE_DOMAIN,
1106 is_ssl()
1107 );
1108 }
1109
1110 /**
1111 * Determines if a local user is connected to WordPress.com
1112 *
1113 * @since 2.8
1114 * @param integer $user_id - Local user id
1115 * @return boolean
1116 **/
1117 public function is_user_connected( $user_id ) {
1118 return $this->get_user_data( $user_id );
1119 }
1120
1121 /**
1122 * Retrieves a user's WordPress.com data
1123 *
1124 * @since 2.8
1125 * @param integer $user_id - Local user id
1126 * @return mixed null or stdClass
1127 **/
1128 public function get_user_data( $user_id ) {
1129 return get_user_meta( $user_id, 'wpcom_user_data', true );
1130 }
1131 }
1132
1133 Jetpack_SSO::get_instance();
1134