Skip to content

Instantly share code, notes, and snippets.

@fabiopaiva
Created August 11, 2015 17:47
Show Gist options
  • Save fabiopaiva/6dbfa10778fe3928b309 to your computer and use it in GitHub Desktop.
Save fabiopaiva/6dbfa10778fe3928b309 to your computer and use it in GitHub Desktop.
Check scope on apigility authenticated resource
<?php
namespace API\V1\Rest\Usuario;
use ZF\Apigility\Doctrine\Server\Resource\DoctrineResource;
use Oauth2;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\ResourceEvent;
class UsuarioResource extends DoctrineResource
{
/**
*
* @var Oauth2\Server
*/
private $oauthServer;
/**
* Validar todas ações da API de acordo com o scope padrão cadastro:usuario
* @param ResourceEvent
* @return mixed
*/
public function dispatch(ResourceEvent $event)
{
if (!$this->checkScope('cadastro:usuario')) {
return new ApiProblem(401, 'Scope não autorizado');
}
return parent::dispatch($event);
}
/**
* Verificar o scope
* @param string nome dos scopes
* @return boolean
*/
private function checkScope($scopeRequired)
{
$request = OAuth2\Request::createFromGlobals();
$response = new OAuth2\Response();
if ($this->getOauthServer()->verifyResourceRequest($request, $response, $scopeRequired)) {
return true;
}
return false;
}
private function getOauthServer()
{
if ($this->oauthServer == null) {
$serverInstance = $this->getServiceManager()->get('ZF\OAuth2\Service\OAuth2Server');
$this->oauthServer = $serverInstance();
}
return $this->oauthServer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment