Skip to content

Instantly share code, notes, and snippets.

@artoodetoo
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artoodetoo/0d8cd9be2c67483976d1 to your computer and use it in GitHub Desktop.
Save artoodetoo/0d8cd9be2c67483976d1 to your computer and use it in GitHub Desktop.
Authenticate by WordPress

The Goal

Get WordPress user identity without need to include huge and unclear WP files.
Assumed that you place scripts somewhere near by WP, so you can access config, database and cookie.

Prerequisites

  • PHP 5.4+
  • Installed WP. I made it for WP 4.1 but I hope it is valid for earlier versions too.
  • Some DataBase Access Level library. I use my own DBAL you can obvoiusly replace it to your own.
<?php
//
// Get your own constants from actual wp-config.php
//
$site_url = 'http://example.com';
$LOGGED_IN_KEY = 'D^3*f,[}VS,$@j>{kl*uMNK-,)zor9ZJCg2X)=(Xv GD!Gy:>3@dpZi8F(J~ZGnz';
$LOGGED_IN_SALT = ',;r|2xEgGm/`F(nf^B+sn64kw[iF!]Qfq?;gYL~(v$ziQG:A {7aL{)c:gqxM>?s';
$salt = $LOGGED_IN_KEY.$LOGGED_IN_SALT;
$cookie_name = 'wordpress_logged_in_'.md5($site_url);
$db_params = [
'username' => 'wp',
'password' => 'wpPassz3',
'dbname' => 'wp',
'prefix' => 'wp1_'
];
$db = new \R2\DBAL\PDOMySQL($db_params);
$auth = new WPAuth(compact('cookie_name', 'salt', 'db'));
var_export($auth->authByCookie()); // false or array with user data
<?php
class WPAuth
{
private $config;
public function __construct(array $config)
{
$this->config = array_replace(
[
'cookie_name' => 'wordpress',
'salt' => '',
'db' => null,
],
$config
);
}
public function authByCookie()
{
if (!isset($_COOKIE[$this->config['cookie_name']])
|| count($tmp = explode('|', $_COOKIE[$this->config['cookie_name']])) !== 4
|| $tmp[1] < time()) {
return false;
}
list($username, $expiration, $token, $hmac) = $tmp;
$db = $this->config['db'];
$user = $db
->query(
"SELECT * ".
"FROM `:p_users` ".
"WHERE `user_login` = :username",
compact('username')
)
->fetchAssoc();
if (!$user) {
return false;
}
$pass_frag = substr($user['user_pass'], 8, 4);
$key = hash_hmac('md5', $username.'|'.$pass_frag.'|'.$expiration.'|'.$token, $this->config['salt']);
$hash = hash_hmac('sha256', $username.'|'.$expiration.'|'.$token, $key);
if ($hash !== $hmac) {
return false;
}
$meta = $db
->query(
"SELECT `meta_value` ".
"FROM `:p_usermeta` ".
"WHERE `user_id` = :ID AND `meta_key` = 'session_tokens'",
$user
)
->result();
if (empty($meta)) {
return false;
}
$sessions = unserialize($meta);
$hash_token = hash('sha256', $token);
if (!isset($sessions[$hash_token]) || $sessions[$hash_token]['expiration'] < time()) {
return false;
}
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment