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

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