Skip to content

Instantly share code, notes, and snippets.

@rmccue
Last active May 9, 2017 12:18
Show Gist options
  • Save rmccue/8156953 to your computer and use it in GitHub Desktop.
Save rmccue/8156953 to your computer and use it in GitHub Desktop.
<?php
class YourAwesomeAuthenticationTokenHandler {
protected $correct_null_user = false;
public function __construct() {
add_filter( 'auth_cookie_malformed', array( $this, 'check_authentication_token' ) );
add_filter( 'set_current_user', array( $this, 'correct_null_user' ) );
}
/**
* Check the authentication token from the request
*
* This is where you set the current user based on HTTP headers, CLI
* parameters, or whatever else you can think of
*
* Make sure to also set the $correct_null_user property
*/
public function check_authentication_token() {
// Get your user ID!
// $user = check_awesome()
wp_set_current_user($user);
self::$correct_null_user = $user;
}
/**
* Undo the `wp_set_current_user( 0 )` from `get_currentuserinfo()`
*
* Changes the user back to the one we set in `check_authentication_token()`
*/
public function correct_null_user() {
global $current_user;
if ( ! self::$correct_null_user || $current_user->ID !== 0 ) {
return;
}
$real_user = self::$correct_null_user;
// Ensure we don't get stuck in an infinite loop here
self::$correct_null_user = false;
wp_set_current_user( $real_user );
}
}
@kitchin
Copy link

kitchin commented May 12, 2014

Note ''set_current_user'' is an action not a filter

Line 8:
-       add_filter( 'set_current_user',      array( $this, 'correct_null_user' ) );
+       add_action( 'set_current_user',      array( $this, 'correct_null_user' ) );

I realize this gist is a workaround for a fixed bug though, https://core.trac.wordpress.org/ticket/26706 see http://journal.ryanmccue.info/311/custom-auth-tokens/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment