Last active
May 9, 2017 12:18
-
-
Save rmccue/8156953 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note ''set_current_user'' is an action not a filter
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/