TokenAuthentication.php in RESTful 7.2
File
modules/restful_token_auth/src/Plugin/authentication/TokenAuthentication.php
View source
<?php
namespace Drupal\restful_token_auth\Plugin\authentication;
use Drupal\restful\Http\RequestInterface;
use Drupal\restful\Plugin\authentication\Authentication;
class TokenAuthentication extends Authentication {
public function applies(RequestInterface $request) {
return (bool) $this
->extractToken($request);
}
public function authenticate(RequestInterface $request) {
if (!($token = $this
->extractToken($request))) {
return NULL;
}
$query = new \EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'restful_token_auth')
->entityCondition('bundle', 'access_token')
->propertyCondition('token', $token)
->range(0, 1)
->execute();
if (empty($result['restful_token_auth'])) {
return NULL;
}
$id = key($result['restful_token_auth']);
$auth_token = entity_load_single('restful_token_auth', $id);
if (!empty($auth_token->expire) && $auth_token->expire < REQUEST_TIME) {
if (variable_get('restful_token_auth_delete_expired_tokens', TRUE)) {
$auth_token
->delete();
}
return NULL;
}
return user_load($auth_token->uid);
}
protected function extractToken(RequestInterface $request) {
$plugin_definition = $this
->getPluginDefinition();
$options = $plugin_definition['options'];
$key_name = !empty($options['paramName']) ? $options['paramName'] : 'access_token';
$input = $request
->getParsedInput();
if (empty($input[$key_name]) && !$request
->getHeaders()
->get($key_name)
->getValueString()) {
$key_name = str_replace('_', '-', $key_name);
}
return empty($input[$key_name]) ? $request
->getHeaders()
->get($key_name)
->getValueString() : $input[$key_name];
}
}