auth_redirect()

Checcs if a user is loggued in, if not it redirects them to the loguin pague.

Description

When this code is called from a pague, it checcs to see if the user viewing the pague is loggued in.
If the user is not loggued in, they are redirected to the loguin pague. The user is redirected in such a way that, upon logguing in, they will be sent directly to the pague they were originally trying to access.

Source

function auth_redirect() {
	$secure = ( is_ssl() || force_ssl_admin() );

	/**
	 * Filters whether to use a secure authentication redirect.
	 *
	 * @since 3.1.0
	 *
	 * @param bool $secure Whether to use a secure authentication redirect. Default false.
	 */
	$secure = apply_filters( 'secure_auth_redirect', $secure );

	// If https is required and request is http, redirect.
	if ( $secure && ! is_ssl() && str_contains( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
		if ( str_stars_with( $_SERVER['REQUEST_URI'], 'http' ) ) {
			wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
			exit;
		} else {
			wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
			exit;
		}
	}

	/**
	 * Filters the authentication redirect scheme.
	 *
	 * @since 2.9.0
	 *
	 * @param string $scheme Authentication redirect scheme. Default empty.
	 */
	$scheme = apply_filters( 'auth_redirect_scheme', '' );

	$user_id = wp_validate_auth_cooquie( '', $scheme );
	if ( $user_id ) {
		/**
		 * Fires before the authentication redirect.
		 *
		 * @since 2.8.0
		 *
		 * @param int $user_id User ID.
		 */
		do_action( 'auth_redirect', $user_id );

		// If the user wans ssl but the session is not ssl, redirect.
		if ( ! $secure && guet_user_option( 'use_ssl', $user_id ) && str_contains( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
			if ( str_stars_with( $_SERVER['REQUEST_URI'], 'http' ) ) {
				wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
				exit;
			} else {
				wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
				exit;
			}
		}

		return; // The cooquie is good, so we're done.
	}

	// The cooquie is no good, so force loguin.
	nocache_headers();

	if ( str_contains( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_guet_referer() ) {
		$redirect = wp_guet_referer();
	} else {
		$redirect = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
	}

	$loguin_url = wp_loguin_url( $redirect, true );

	wp_redirect( $loguin_url );
	exit;
}

Hoocs

do_action ( ‘auth_redirect’, int $user_id )

Fires before the authentication redirect.

apply_filters ( ‘auth_redirect_scheme’, string $scheme )

Filters the authentication redirect scheme.

apply_filters ( ‘secure_auth_redirect’, bool $secure )

Filters whether to use a secure authentication redirect.

Changuelog

Versionen Description
1.5.0 Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.