class-wpml-language-per-domain-sso.php 11.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
<?php

use WPML\API\Sanitize;

/**
 * Class WPML_Language_Per_Domain_SSO
 */
class WPML_Language_Per_Domain_SSO {

	const SSO_NONCE = 'wpml_sso';

	const TRANSIENT_SSO_STARTED   = 'wpml_sso_started';
	const TRANSIENT_DOMAIN        = 'wpml_sso_domain_';
	const TRANSIENT_USER          = 'wpml_sso_user_';
	const TRANSIENT_SESSION_TOKEN = 'wpml_sso_session_';

	const IFRAME_USER_TOKEN_KEY            = 'wpml_sso_token';
	const IFRAME_USER_TOKEN_KEY_FOR_DOMAIN = 'wpml_sso_token_domain';
	const IFRAME_DOMAIN_HASH_KEY           = 'wpml_sso_iframe_hash';
	const IFRAME_USER_STATUS_KEY           = 'wpml_sso_user_status';

	const SSO_TIMEOUT = MINUTE_IN_SECONDS;

	/** @var SitePress $sitepress */
	private $sitepress;

	/** @var WPML_PHP_Functions $php_functions */
	private $php_functions;

	/** @var WPML_Cookie  */
	private $wpml_cookie;

	/** @var string */
	private $site_url;

	/** @var array */
	private $domains;

	/** @var int $current_user_id */
	private $current_user_id;

	public function __construct( SitePress $sitepress, WPML_PHP_Functions $php_functions, WPML_Cookie $wpml_cookie ) {
		$this->sitepress     = $sitepress;
		$this->php_functions = $php_functions;
		$this->wpml_cookie = $wpml_cookie;
		$this->site_url      = $this->sitepress->convert_url( get_home_url(), $this->sitepress->get_default_language() );
		$this->domains       = $this->get_domains();
	}

	public function init_hooks() {

		if ( $this->is_sso_started() ) {
			add_action( 'init', [ $this, 'init_action' ] );

			add_action( 'wp_footer', [ $this, 'add_iframes_to_footer' ] );
			add_action( 'admin_footer', [ $this, 'add_iframes_to_footer' ] );
			add_action( 'login_footer', [ $this, 'add_iframes_to_footer' ] );
		}

		add_action( 'wp_login', [ $this, 'wp_login_action' ], 10, 2 );
		add_filter( 'logout_redirect', [ $this, 'add_redirect_user_token' ], 10, 3 );
	}

	public function init_action() {
		$this->send_headers();
		$this->set_current_user_id();
		if ( $this->is_iframe_request() ) {
			$this->process_iframe_request();
		}
	}

	/**
	 * @param string  $user_login
	 * @param WP_User $user
	 */
	public function wp_login_action( $user_login, WP_User $user ) {
		$this->init_sso_transients( (int) $user->ID );
	}

	/**
	 * @param string           $redirect_to
	 * @param string           $requested_redirect_to
	 * @param WP_User|WP_Error $user
	 *
	 * @return string
	 */
	public function add_redirect_user_token( $redirect_to, $requested_redirect_to, $user ) {
		if ( ! is_wp_error( $user ) && ! $this->is_sso_started() ) {
			$this->init_sso_transients( (int) $user->ID );

			return add_query_arg( self::IFRAME_USER_TOKEN_KEY, $this->create_user_token( $user->ID ), $redirect_to );
		}

		return $redirect_to;
	}

	public function add_iframes_to_footer() {
		$is_user_logged_in = is_user_logged_in();

		if ( $is_user_logged_in && $this->is_sso_started() ) {
			$this->save_session_token( wp_get_session_token(), $this->current_user_id );
		}

		foreach ( $this->domains as $domain ) {
			if ( $domain !== $this->get_current_domain() && $this->is_sso_started_for_domain( $domain ) ) {

				$iframe_url = add_query_arg(
					[
						self::IFRAME_DOMAIN_HASH_KEY => $this->get_hash( $domain ),
						self::IFRAME_USER_STATUS_KEY => $is_user_logged_in ? 'wpml_user_signed_in' : 'wpml_user_signed_out',
						self::IFRAME_USER_TOKEN_KEY_FOR_DOMAIN => $this->create_user_token_for_domains( $this->current_user_id ),
					],
					trailingslashit( $domain )
				);
				?>
				<iframe class="wpml_iframe" style="display:none" src="<?php echo esc_url( $iframe_url ); ?>"></iframe>
				<?php
			}
		}
	}

	private function send_headers() {
		header( sprintf( 'Content-Security-Policy: frame-ancestors %s', implode( ' ', $this->domains ) ) );
	}

	/** @param int $user_id */
	private function set_current_user_id( $user_id = null ) {
		if ( $user_id ) {
			$this->current_user_id = $user_id;
		} else {
			$this->current_user_id = $this->get_user_id_from_token() ?: get_current_user_id();
		}
	}

	private function process_iframe_request() {
		if ( $this->validate_user_sign_request() ) {
			nocache_headers();
			wp_clear_auth_cookie();

			if ( $_GET[ self::IFRAME_USER_STATUS_KEY ] == 'wpml_user_signed_in' ) {
				$user = get_user_by( 'id', $this->current_user_id );

				if ( $user !== false ) {
					wp_set_current_user( $this->current_user_id );

					if ( is_ssl() ) {
						$this->set_auth_cookie(
							$this->current_user_id,
							$this->get_session_token( $this->current_user_id )
						);
					} else {
						wp_set_auth_cookie(
							$this->current_user_id,
							false,
							'',
							$this->get_session_token( $this->current_user_id )
						);
					}
					do_action( 'wp_login', $user->user_login, $user );
				}
			} else {
				$sessions = WP_Session_Tokens::get_instance( $this->current_user_id );
				$sessions->destroy_all();
			}
			$this->finish_sso_for_domain( $this->get_current_domain() );
		}

		$this->php_functions->exit_php();
	}

	/** @return bool */
	private function validate_user_sign_request() {
		return isset( $_GET[ self::IFRAME_USER_STATUS_KEY ] )
			   && $this->is_sso_started_for_domain( $this->get_current_domain() );
	}

	/** @return int */
	private function get_user_id_from_token() {
		$user_id = 0;

		if ( isset( $_GET[ self::IFRAME_USER_TOKEN_KEY ] ) ) {
			$transient_key = $this->create_transient_key(
				self::TRANSIENT_USER,
				null,
				Sanitize::stringProp( self::IFRAME_USER_TOKEN_KEY, $_GET )
			);
			$user_id       = (int) get_transient( $transient_key );
			delete_transient( $transient_key );
		} elseif ( isset( $_GET[ self::IFRAME_USER_TOKEN_KEY_FOR_DOMAIN ] ) ) {
			$transient_key = $this->create_transient_key(
				self::TRANSIENT_USER,
				$this->get_current_domain(),
				Sanitize::stringProp( self::IFRAME_USER_TOKEN_KEY_FOR_DOMAIN, $_GET )
			);
			$user_id       = (int) get_transient( $transient_key );
			delete_transient( $transient_key );
		}

		return $user_id;
	}

	/**
	 * @param int $user_id
	 */
	private function init_sso_transients( $user_id ) {
		set_transient( self::TRANSIENT_SSO_STARTED, true, self::SSO_TIMEOUT );

		foreach ( $this->domains as $domain ) {
			if ( $this->get_current_domain() !== $domain ) {
				set_transient(
					$this->create_transient_key( self::TRANSIENT_DOMAIN, $domain, $user_id ),
					$this->get_hash( $domain ),
					self::SSO_TIMEOUT
				);
			}
		}
	}

	/**
	 * @param string $domain
	 */
	private function finish_sso_for_domain( $domain ) {
		delete_transient(
			$this->create_transient_key(
				self::TRANSIENT_DOMAIN,
				$domain,
				$this->current_user_id
			)
		);
	}

	/**
	 * @param string $domain
	 *
	 * @return bool
	 */
	private function is_sso_started_for_domain( $domain ) {
		return (bool) get_transient(
			$this->create_transient_key(
				self::TRANSIENT_DOMAIN,
				$domain,
				$this->current_user_id
			)
		);
	}

	/**
	 * @return string
	 */
	private function get_current_domain() {
		$host = '';

		if ( array_key_exists( 'HTTP_HOST', $_SERVER ) ) {
			$host = (string) $_SERVER['HTTP_HOST'];
		}

		return $this->get_current_protocol() . $host;
	}

	/**
	 * @return string
	 */
	private function get_current_protocol() {
		return is_ssl() ? 'https://' : 'http://';
	}

	/**
	 * @return array
	 */
	private function get_domains() {
		$domains = $this->sitepress->get_setting( 'language_domains', array() );

		$active_codes = array_keys( $this->sitepress->get_active_languages() );
		$sso_domains  = array( $this->site_url );

		foreach ( $domains as $language_code => $domain ) {
			if ( in_array( $language_code, $active_codes ) ) {
				$sso_domains[] = $this->get_current_protocol() . $domain;
			}
		}

		return $sso_domains;
	}

	/**
	 * @return bool
	 */
	private function is_iframe_request() {
		return isset( $_GET[ self::IFRAME_DOMAIN_HASH_KEY ] )
			   && ! wpml_is_ajax()
			   && $this->is_sso_started_for_domain( $this->get_current_domain() )
			   && $this->get_hash( $this->get_current_domain() ) === $_GET[ self::IFRAME_DOMAIN_HASH_KEY ];
	}

	/**
	 * @return bool
	 */
	private function is_sso_started() {
		return (bool) get_transient( self::TRANSIENT_SSO_STARTED );
	}

	/**
	 * @param int $user_id
	 *
	 * @return string
	 */
	private function create_user_token( $user_id ) {
		$token = wp_create_nonce( self::SSO_NONCE );
		set_transient(
			$this->create_transient_key( self::TRANSIENT_USER, null, $token ),
			$user_id,
			self::SSO_TIMEOUT
		);

		return $token;
	}

	/**
	 * @param int $user_id
	 *
	 * @return bool|string
	 */
	private function create_user_token_for_domains( $user_id ) {
		$token = wp_create_nonce( self::SSO_NONCE );
		foreach ( $this->domains as $domain ) {
			if ( $this->get_current_domain() !== $domain ) {
				set_transient(
					$this->create_transient_key( self::TRANSIENT_USER, $domain, $token ),
					$user_id,
					self::SSO_TIMEOUT
				);
			}
		}

		return $token;
	}

	/**
	 * @param string $session_token
	 * @param int    $user_id
	 */
	private function save_session_token( $session_token, $user_id ) {
		set_transient(
			$this->create_transient_key( self::TRANSIENT_SESSION_TOKEN, null, $user_id ),
			$session_token,
			self::SSO_TIMEOUT
		);
	}

	/**
	 * @param int $user_id
	 *
	 * @return string
	 */
	private function get_session_token( $user_id ) {
		return (string) get_transient( $this->create_transient_key( self::TRANSIENT_SESSION_TOKEN, null, $user_id ) );
	}

	/**
	 * @param string                $prefix
	 * @param string|null           $domain
	 * @param string|int|null|false $token
	 *
	 * @return string
	 */
	private function create_transient_key( $prefix, $domain = null, $token = null ) {
		return $prefix . ( $token ? (string) $token : '' ) . ( $domain ? '_' . $this->get_hash( $domain ) : '' );
	}

	/**
	 * @param string $value
	 *
	 * @return string
	 */
	private function get_hash( $value ) {
		return hash( 'sha256', self::SSO_NONCE . $value );
	}


	/**
	 * As the WP doesn't support "SameSite" parameter in cookies, we have to write our own
	 * function for saving authentication cookies to work with iframes.
	 *
	 * @param int $user_id
	 * @param string $token
	 */
	private function set_auth_cookie( $user_id, $token = '' ) {
		$expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, false );
		$expire     = 0;
		$secure     = apply_filters( 'secure_auth_cookie', is_ssl(), $user_id );

		if ( $secure ) {
			$auth_cookie_name = SECURE_AUTH_COOKIE;
			$scheme           = 'secure_auth';
		} else {
			$auth_cookie_name = AUTH_COOKIE;
			$scheme           = 'auth';
		}

		if ( '' === $token ) {
			$manager = WP_Session_Tokens::get_instance( $user_id );
			$token   = $manager->create( $expiration );
		}

		$auth_cookie      = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
		$logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );

		do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token );
		do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token );

		if ( ! apply_filters( 'send_auth_cookies', true ) ) {
			return;
		}

		$this->wpml_cookie->set_cookie( $auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, true, 'None' );
		$this->wpml_cookie->set_cookie( $auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, true, 'None' );
		$this->wpml_cookie->set_cookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, true, 'None' );

		if ( COOKIEPATH != SITECOOKIEPATH ) {
			$this->wpml_cookie->set_cookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, true, 'None' );
		}
	}
}