2

I'm looking to run some of my automated acceptance tests as a logged in user. My acceptance tests are run using Ghost Inspector which can send basic authentication headers.

There is a basic authentication plugin for the REST API, so unless someone answers this with a better solution, I'm hacking that to work with any request.

Yes, basic authentication is not super-secure, but it's as secure as wp-login -- IE fine if using HTTPS. Also, this is a test site, not crazy worried about security.

1
7

I would just hook into determine_current_user filter and check HTTP basic auth data to return the user.

Maybe, just maybe, I would allow only specific user to be logged via HTTP auth.

That could be done, for example, by setting an user option.

The code could look like something like this (tested by OP):

add_filter( 'determine_current_user', function( $cur_user ) {

    // If user already logged in or no HTTP AUTH info, return
    if ($cur_user || empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW'])) {
        return $cur_user;
    }

    // If there's no user with given username, return
    $found_user = get_user_by('login', $_SERVER['PHP_AUTH_USER']);
    if (!$found_user) {
        return $cur_user;
    }

    // If password does not match, return
    if ( ! wp_check_password( $_SERVER['PHP_AUTH_PW'], $found_user->user_pass ) ) {
        return $cur_user;
    }

    // Return found user ID only if allowed to login via HTTP in user meta
    return get_user_option( 'http_auth_login_allowed', $found_user->ID )
        ? $found_user->ID
        : $cur_user;

}, 30);

I used priority 30 because WP uses 20 (IIRC) to log user from cookie, so this will run later and if user is found in cookie this does nothing.

A check to ensure requst is_ssl() could be added for better security, even if -in all honesty- I would not run this in a production site. But considering that OP says target is a test site... this should do just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.