PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.6.2
Jetpack – WP Security, Backup, Speed, & Growth v7.6.2
16.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 All 502 releases
jetpack / modules / sso.php

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

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