/**
* Get the current user.
*
* Will prefer the static user cache over sessions. The static user
* cache is primarily used for stateless authentication. For stateful authentication,
* cookies + sessions will be used.
*
* @param string $key field to retrieve. Leave null to get entire User record
* @return array|null User record. or null if no user is logged in.
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
*/
public static function user($key = null)
{
$user = array();
$request = new CakeRequest();
if (($authorization = $request->header('Authorization')) && preg_match('/^Bearer (.*?)$/', $authorization, $matches)) {
$signer = new Sha256();
$token = (new Parser())->parse((string) next($matches));
try {
if ($token->verify($signer, Configure::read('Security.salt'))) {
$data = new ValidationData(Configure::read('Security.timeout') > 0 ? null : $token->getClaim('iat'));
$data->setIssuer(Router::url('/', true));
$data->setAudience($request->clientIp());
if ($token->validate($data)) {
if ($user = json_decode($token->getClaim('data'), true)) {
if (!empty($user['id'])) {
if (!empty(static::$_user) && static::$_user['id'] == $user['id']) {
$user = static::$_user;
return empty($key) ? $user : Hash::get($user, $key);
} else {
$User = ClassRegistry::init('User');
$User->id = $user['id'];
return Hash::get($User->read(), 'User' . (empty($key) ? '' : '.' . $key));
}
}
}
}
}
} catch (Exception $ex) {
}
}
return false;
}