PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.8.3
Jetpack – WP Security, Backup, Speed, & Growth v7.8.3
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
1,142 lines 34.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use Automattic\Jetpack\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
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 $xml = new Jetpack_IXR_Client( array(
624 'user_id' => get_current_user_id(),
625 ) );
626 $xml->query( 'jetpack.sso.requestNonce' );
627
628 if ( $xml->isError() ) {
629 return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
630 }
631
632 $nonce = $xml->getResponse();
633
634 setcookie(
635 'jetpack_sso_nonce',
636 $nonce,
637 time() + ( 10 * MINUTE_IN_SECONDS ),
638 COOKIEPATH,
639 COOKIE_DOMAIN,
640 is_ssl()
641 );
642 }
643
644 return sanitize_key( $nonce );
645 }
646
647 /**
648 * The function that actually handles the login!
649 */
650 function handle_login() {
651 $wpcom_nonce = sanitize_key( $_GET['sso_nonce'] );
652 $wpcom_user_id = (int) $_GET['user_id'];
653
654 $xml = new Jetpack_IXR_Client( array(
655 'user_id' => get_current_user_id(),
656 ) );
657 $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
658
659 $user_data = $xml->isError() ? false : $xml->getResponse();
660 if ( empty( $user_data ) ) {
661 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
662 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) );
663 return;
664 }
665
666 $user_data = (object) $user_data;
667 $user = null;
668
669 /**
670 * Fires before Jetpack's SSO modifies the log in form.
671 *
672 * @module sso
673 *
674 * @since 2.6.0
675 *
676 * @param object $user_data WordPress.com User information.
677 */
678 do_action( 'jetpack_sso_pre_handle_login', $user_data );
679
680 $tracking = new Tracking();
681
682 if ( Jetpack_SSO_Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
683 $this->user_data = $user_data;
684
685 $tracking->record_user_event( 'sso_login_failed', array(
686 'error_message' => 'error_msg_enable_two_step'
687 ) );
688
689 /** This filter is documented in core/src/wp-includes/pluggable.php */
690 do_action( 'wp_login_failed', $user_data->login );
691 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_enable_two_step' ) );
692 return;
693 }
694
695 $user_found_with = '';
696 if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
697 $user_found_with = 'external_user_id';
698 $user = get_user_by( 'id', intval( $user_data->external_user_id ) );
699 if ( $user ) {
700 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
701 }
702 }
703
704 // If we don't have one by wpcom_user_id, try by the email?
705 if ( empty( $user ) && Jetpack_SSO_Helpers::match_by_email() ) {
706 $user_found_with = 'match_by_email';
707 $user = get_user_by( 'email', $user_data->email );
708 if ( $user ) {
709 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
710 }
711 }
712
713 // If we've still got nothing, create the user.
714 $new_user_override_role = false;
715 if ( empty( $user ) && ( get_option( 'users_can_register' ) || ( $new_user_override_role = Jetpack_SSO_Helpers::new_user_override( $user_data ) ) ) ) {
716 /**
717 * If not matching by email we still need to verify the email does not exist
718 * or this blows up
719 *
720 * If match_by_email is true, we know the email doesn't exist, as it would have
721 * been found in the first pass. If get_user_by( 'email' ) doesn't find the
722 * user, then we know that email is unused, so it's safe to add.
723 */
724 if ( Jetpack_SSO_Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
725
726 if ( $new_user_override_role ) {
727 $user_data->role = $new_user_override_role;
728 }
729
730 $user = Jetpack_SSO_Helpers::generate_user( $user_data );
731 if ( ! $user ) {
732 $tracking->record_user_event( 'sso_login_failed', array(
733 'error_message' => 'could_not_create_username'
734 ) );
735 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_unable_to_create_user' ) );
736 return;
737 }
738
739 $user_found_with = $new_user_override_role
740 ? 'user_created_new_user_override'
741 : 'user_created_users_can_register';
742 } else {
743 $tracking->record_user_event( 'sso_login_failed', array(
744 'error_message' => 'error_msg_email_already_exists'
745 ) );
746
747 $this->user_data = $user_data;
748 add_action( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_email_already_exists' ) );
749 return;
750 }
751 }
752
753 /**
754 * Fires after we got login information from WordPress.com.
755 *
756 * @module sso
757 *
758 * @since 2.6.0
759 *
760 * @param array $user Local User information.
761 * @param object $user_data WordPress.com User Login information.
762 */
763 do_action( 'jetpack_sso_handle_login', $user, $user_data );
764
765 if ( $user ) {
766 // Cache the user's details, so we can present it back to them on their user screen
767 update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
768
769 add_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
770 wp_set_auth_cookie( $user->ID, true );
771 remove_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
772
773 /** This filter is documented in core/src/wp-includes/user.php */
774 do_action( 'wp_login', $user->user_login, $user );
775
776 wp_set_current_user( $user->ID );
777
778 $_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( $_REQUEST['redirect_to'] ) : '';
779 $redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
780
781 // If we have a saved redirect to request in a cookie
782 if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
783 // Set that as the requested redirect to
784 $redirect_to = $_request_redirect_to = esc_url_raw( $_COOKIE['jetpack_sso_redirect_to'] );
785 }
786
787 $json_api_auth_environment = Jetpack_SSO_Helpers::get_json_api_auth_environment();
788
789 $is_json_api_auth = ! empty( $json_api_auth_environment );
790 $is_user_connected = Jetpack::is_user_connected( $user->ID );
791 $roles = new Roles();
792 $tracking->record_user_event( 'sso_user_logged_in', array(
793 'user_found_with' => $user_found_with,
794 'user_connected' => (bool) $is_user_connected,
795 'user_role' => $roles->translate_current_user_to_role(),
796 'is_json_api_auth' => (bool) $is_json_api_auth,
797 ) );
798
799 if ( $is_json_api_auth ) {
800 Jetpack::init()->verify_json_api_authorization_request( $json_api_auth_environment );
801 Jetpack::init()->store_json_api_authorization_token( $user->user_login, $user );
802
803 } else if ( ! $is_user_connected ) {
804 wp_safe_redirect(
805 add_query_arg(
806 array(
807 'redirect_to' => $redirect_to,
808 'request_redirect_to' => $_request_redirect_to,
809 'calypso_env' => Jetpack::get_calypso_env(),
810 'jetpack-sso-auth-redirect' => '1',
811 ),
812 admin_url()
813 )
814 );
815 exit;
816 }
817
818 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
819 wp_safe_redirect(
820 /** This filter is documented in core/src/wp-login.php */
821 apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
822 );
823 exit;
824 }
825
826 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
827
828 $tracking->record_user_event( 'sso_login_failed', array(
829 'error_message' => 'cant_find_user'
830 ) );
831
832 $this->user_data = $user_data;
833 /** This filter is documented in core/src/wp-includes/pluggable.php */
834 do_action( 'wp_login_failed', $user_data->login );
835 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'cant_find_user' ) );
836 }
837
838 static function profile_page_url() {
839 return admin_url( 'profile.php' );
840 }
841
842 /**
843 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
844 *
845 * @param array $args An array of arguments to add to the SSO URL.
846 * @param boolean $is_primary Should the button have the `button-primary` class?
847 * @return string Returns the HTML markup for the button.
848 */
849 function build_sso_button( $args = array(), $is_primary = false ) {
850 $url = $this->build_sso_button_url( $args );
851 $classes = $is_primary
852 ? 'jetpack-sso button button-primary'
853 : 'jetpack-sso button';
854
855 return sprintf(
856 '<a rel="nofollow" href="%1$s" class="%2$s"><span>%3$s %4$s</span></a>',
857 esc_url( $url ),
858 $classes,
859 '<span class="genericon genericon-wordpress"></span>',
860 esc_html__( 'Log in with WordPress.com', 'jetpack' )
861 );
862 }
863
864 /**
865 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
866 *
867 * @param array $args An array of arguments to add to the SSO URL.
868 * @return string The URL used for SSO.
869 */
870 function build_sso_button_url( $args = array() ) {
871 $defaults = array(
872 'action' => 'jetpack-sso',
873 );
874
875 $args = wp_parse_args( $args, $defaults );
876
877 if ( ! empty( $_GET['redirect_to'] ) ) {
878 $args['redirect_to'] = urlencode( esc_url_raw( $_GET['redirect_to'] ) );
879 }
880
881 return add_query_arg( $args, wp_login_url() );
882 }
883
884 /**
885 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
886 *
887 * @param boolean $reauth Should the user be forced to reauthenticate on WordPress.com?
888 * @param array $args Optional query parameters.
889 * @return string The WordPress.com SSO URL.
890 */
891 function get_sso_url_or_die( $reauth = false, $args = array() ) {
892 if ( empty( $reauth ) ) {
893 $sso_redirect = $this->build_sso_url( $args );
894 } else {
895 self::clear_wpcom_profile_cookies();
896 $sso_redirect = $this->build_reauth_and_sso_url( $args );
897 }
898
899 // If there was an error retrieving the SSO URL, then error.
900 if ( is_wp_error( $sso_redirect ) ) {
901 $error_message = sanitize_text_field(
902 sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() )
903 );
904 $tracking = new Tracking();
905 $tracking->record_user_event( 'sso_login_redirect_failed', array(
906 'error_message' => $error_message
907 ) );
908 wp_die( $error_message );
909 }
910
911 return $sso_redirect;
912 }
913
914 /**
915 * Build WordPress.com SSO URL with appropriate query parameters.
916 *
917 * @param array $args Optional query parameters.
918 * @return string WordPress.com SSO URL
919 */
920 function build_sso_url( $args = array() ) {
921 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
922 $defaults = array(
923 'action' => 'jetpack-sso',
924 'site_id' => Jetpack_Options::get_option( 'id' ),
925 'sso_nonce' => $sso_nonce,
926 'calypso_auth' => '1',
927 );
928
929 $args = wp_parse_args( $args, $defaults );
930
931 if ( is_wp_error( $args['sso_nonce'] ) ) {
932 return $args['sso_nonce'];
933 }
934
935 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
936 }
937
938 /**
939 * Build WordPress.com SSO URL with appropriate query parameters,
940 * including the parameters necessary to force the user to reauthenticate
941 * on WordPress.com.
942 *
943 * @param array $args Optional query parameters.
944 * @return string WordPress.com SSO URL
945 */
946 function build_reauth_and_sso_url( $args = array() ) {
947 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
948 $redirect = $this->build_sso_url( array( 'force_auth' => '1', 'sso_nonce' => $sso_nonce ) );
949
950 if ( is_wp_error( $redirect ) ) {
951 return $redirect;
952 }
953
954 $defaults = array(
955 'action' => 'jetpack-sso',
956 'site_id' => Jetpack_Options::get_option( 'id' ),
957 'sso_nonce' => $sso_nonce,
958 'reauth' => '1',
959 'redirect_to' => urlencode( $redirect ),
960 'calypso_auth' => '1',
961 );
962
963 $args = wp_parse_args( $args, $defaults );
964
965 if ( is_wp_error( $args['sso_nonce'] ) ) {
966 return $args['sso_nonce'];
967 }
968
969 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
970 }
971
972 /**
973 * Determines local user associated with a given WordPress.com user ID.
974 *
975 * @since 2.6.0
976 *
977 * @param int $wpcom_user_id User ID from WordPress.com
978 * @return object Local user object if found, null if not.
979 */
980 static function get_user_by_wpcom_id( $wpcom_user_id ) {
981 $user_query = new WP_User_Query( array(
982 'meta_key' => 'wpcom_user_id',
983 'meta_value' => intval( $wpcom_user_id ),
984 'number' => 1,
985 ) );
986
987 $users = $user_query->get_results();
988 return $users ? array_shift( $users ) : null;
989 }
990
991 /**
992 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
993 * WordPress.com authorization flow.
994 *
995 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
996 * calls menu_page_url() which doesn't work properly until admin menus are registered.
997 */
998 function maybe_authorize_user_after_sso() {
999 if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) {
1000 return;
1001 }
1002
1003 $redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : admin_url();
1004 $request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( $_GET['request_redirect_to'] ) : $redirect_to;
1005
1006 /** This filter is documented in core/src/wp-login.php */
1007 $redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1008
1009 /**
1010 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1011 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1012 */
1013 $redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1014 $redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1015
1016 /**
1017 * Return the raw connect URL with our redirect and attribute connection to SSO.
1018 */
1019 $connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1020
1021 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
1022 wp_safe_redirect( $connect_url );
1023 exit;
1024 }
1025
1026 /**
1027 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1028 * stored when the user logs out, and then deleted when the user logs in.
1029 */
1030 function store_wpcom_profile_cookies_on_logout() {
1031 if ( ! Jetpack::is_user_connected( get_current_user_id() ) ) {
1032 return;
1033 }
1034
1035 $user_data = $this->get_user_data( get_current_user_id() );
1036 if ( ! $user_data ) {
1037 return;
1038 }
1039
1040 setcookie(
1041 'jetpack_sso_wpcom_name_' . COOKIEHASH,
1042 $user_data->display_name,
1043 time() + WEEK_IN_SECONDS,
1044 COOKIEPATH,
1045 COOKIE_DOMAIN,
1046 is_ssl()
1047 );
1048
1049 setcookie(
1050 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1051 get_avatar_url(
1052 $user_data->email,
1053 array( 'size' => 144, 'default' => 'mystery' )
1054 ),
1055 time() + WEEK_IN_SECONDS,
1056 COOKIEPATH,
1057 COOKIE_DOMAIN,
1058 is_ssl()
1059 );
1060 }
1061
1062 /**
1063 * Determines if a local user is connected to WordPress.com
1064 *
1065 * @since 2.8
1066 * @param integer $user_id - Local user id
1067 * @return boolean
1068 **/
1069 public function is_user_connected( $user_id ) {
1070 return $this->get_user_data( $user_id );
1071 }
1072
1073 /**
1074 * Retrieves a user's WordPress.com data
1075 *
1076 * @since 2.8
1077 * @param integer $user_id - Local user id
1078 * @return mixed null or stdClass
1079 **/
1080 public function get_user_data( $user_id ) {
1081 return get_user_meta( $user_id, 'wpcom_user_data', true );
1082 }
1083
1084 /**
1085 * Mark SSO as discovered when an SSO JITM is viewed.
1086 *
1087 * @since 6.9.0
1088 *
1089 * @param array $envelopes Array of JITM messages received after API call.
1090 *
1091 * @return array $envelopes New array of JITM messages. May now contain only one message, about SSO.
1092 */
1093 public function inject_sso_jitm( $envelopes ) {
1094 // Bail early if that's not the first time the user uses SSO.
1095 if ( true != Jetpack_Options::get_option( 'sso_first_login' ) ) {
1096 return $envelopes;
1097 }
1098
1099 // Update our option to mark that SSO was discovered.
1100 Jetpack_Options::update_option( 'sso_first_login', false );
1101
1102 return $this->prepare_sso_first_login_jitm();
1103 }
1104
1105 /**
1106 * Prepare JITM array for new SSO users
1107 *
1108 * @since 6.9.0
1109 *
1110 * @return array $sso_first_login_jitm array containting one object of information about our message.
1111 */
1112 private function prepare_sso_first_login_jitm() {
1113 // Build our custom SSO JITM.
1114 $discover_sso_message = array(
1115 'content' => array(
1116 'message' => esc_html__( "You've successfully signed in with WordPress.com Secure Sign On!", 'jetpack' ),
1117 'icon' => 'jetpack',
1118 'list' => array(),
1119 'description' => esc_html__( 'Interested in learning more about how Secure Sign On keeps your site safer?', 'jetpack' ),
1120 'classes' => '',
1121 ),
1122 'CTA' => array(
1123 'message' => esc_html__( 'Learn More', 'jetpack' ),
1124 'hook' => '',
1125 'newWindow' => true,
1126 'primary' => true,
1127 ),
1128 'template' => 'default',
1129 'ttl' => 300,
1130 'id' => 'sso_discover',
1131 'feature_class' => 'sso',
1132 'expires' => 3628800,
1133 'max_dismissal' => 1,
1134 'activate_module' => null,
1135 );
1136
1137 return array( json_decode( json_encode( $discover_sso_message ) ) );
1138 }
1139 }
1140
1141 Jetpack_SSO::get_instance();
1142