Wordpress Authentication Middleware

What I want to achieve is:

For every request , if the user is not logged he / she will be redirected to the log in page. If the user is logged in then he / she can access the site.

class Auth{

    protected static $instance = null;

    public function checkAuth(){
        auth_redirect();
    }

    public static function getInstance() {

        if (null == self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

}

Having this draft class what is the best action hook for this check? wp, init, template_redirect ?

Example of usage:

add_action('wp', array(Auth::getInstance(), 'checkAuth'));

UPDATE

I played a bit around with the hooks and I noticed that:

When I hook it to 'wp' or on 'template_redirect' then I get the log in page but every time I logged in it prompt me to log in again, and again and again.

When I hook it to 'init' I get a

Request-URI Too Long

The requested URL's length exceeds the capacity limit for this server.

The problem seems to be with auth_redirect() wordpress function.

I change my checkAuth function inside of Auth class with

if(!is_user_logged_in()) wp_safe_redirect(site_url('/wp-login.php'));

I test again the three hooks and now wp and template_redirect works fine but the init hook cause a redirect loop error.

Any ideas why is this happening ? (Refrence: Using `auth_redirect` : keeps asking me to login even when Im logged in)

Topic authorization authentication users Wordpress

Category Web


Here is part of a multisite plugin I wrote that forces a user to log in. It required a user to be registered for the site; not just be a network user. It could be modified to check if user has a higher role. I did modify it to fit the OP requirements.

add_action( 'init', 'registration_check',5);

function registration_check() {
    if ( is_user_logged_in() ) { return; }
    // if ( current_user_can('read') ) { return; }  // orig for multisite

    // This is a base array of pages that will be EXCLUDED from being blocked
    $exclusions = array(
            'wp-login.php',
            'wp-register.php',
            'wp-cron.php', // Just incase
            'wp-trackback.php',
            'wp-app.php',
            'xmlrpc.php',
            );
    // If the current script name is in the exclusion list, abort
    if ( in_array( basename($_SERVER['PHP_SELF']), $exclusions ) ) {
        return;
    }

    // if ( is_user_logged_in() ) { wp_die('<strong>You are logged in but do not have enough privileges to access this site.</strong>'); } // orig for multisite
    // Still here? Okay, then redirect to the login form
    auth_redirect();
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.