RestfulTokenAuthController.php in RESTful 7.2
File
modules/restful_token_auth/src/Entity/RestfulTokenAuthController.php
View source
<?php
namespace Drupal\restful_token_auth\Entity;
use Drupal\restful\Exception\ServerConfigurationException;
class RestfulTokenAuthController extends \EntityAPIController {
public function generateAccessToken($uid) {
$refresh_token = $this
->generateRefreshToken($uid);
$values = array(
'uid' => $uid,
'type' => 'access_token',
'created' => REQUEST_TIME,
'name' => t('Access token for: @uid', array(
'@uid' => $uid,
)),
'token' => drupal_random_key(),
'expire' => $this
->getExpireTime(),
'refresh_token_reference' => array(
LANGUAGE_NONE => array(
array(
'target_id' => $refresh_token->id,
),
),
),
);
$access_token = $this
->create($values);
$this
->save($access_token);
return $access_token;
}
private function generateRefreshToken($uid) {
$query = new \EntityFieldQuery();
$results = $query
->entityCondition('entity_type', 'restful_token_auth')
->entityCondition('bundle', 'refresh_token')
->propertyCondition('uid', $uid)
->execute();
if (!empty($results['restful_token_auth'])) {
entity_delete_multiple('restful_token_auth', array_keys($results['restful_token_auth']));
}
$values = array(
'uid' => $uid,
'type' => 'refresh_token',
'created' => REQUEST_TIME,
'name' => t('Refresh token for: @uid', array(
'@uid' => $uid,
)),
'token' => drupal_random_key(),
);
$refresh_token = $this
->create($values);
$this
->save($refresh_token);
return $refresh_token;
}
protected function getExpireTime() {
$now = new \DateTime();
try {
$expiration = $now
->add(new \DateInterval(variable_get('restful_token_auth_expiration_period', 'P1D')));
} catch (\Exception $e) {
throw new ServerConfigurationException('Invalid DateInterval format provided.');
}
return $expiration
->format('U');
}
}