Skip to content

Instantly share code, notes, and snippets.

@HDias
Created May 20, 2015 17:30
Show Gist options
  • Save HDias/b75cd6563eda0993e56a to your computer and use it in GitHub Desktop.
Save HDias/b75cd6563eda0993e56a to your computer and use it in GitHub Desktop.
<?php
namespace User;
use Base\Hydrator\Strategy\DateTimeStrategy;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\FormElementProviderInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\Feature\ViewHelperProviderInterface;
use Zend\ModuleManager\ModuleManager;
use Zend\Mvc\MvcEvent;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Hydrator\ClassMethods;
use Auth\View\Helper\UserIdentity;
class Module implements
AutoloaderProviderInterface,
FormElementProviderInterface,
ServiceProviderInterface,
ViewHelperProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/', __NAMESPACE__),
'Perfil' => __DIR__ . '/src/' . str_replace('\\', '/', 'Perfil'),
'Auth' => __DIR__ . '/src/' . str_replace('\\', '/', 'Auth'),
),
),
);
}
public function init(ModuleManager $moduleManager)
{
//Get eventos compartilhados
$sharedEvents = $moduleManager->getEventManager()
->getSharedManager();
//Anexar (atach) nosso evento mvcPreDispatch ao sharedEvents
//É rodado antes de dar o dispatch na página
$sharedEvents->attach(
'Zend\Mvc\Controller\AbstractActionController', //tipo
MvcEvent::EVENT_DISPATCH,
array(
$this, //aonde está o método
'mvcPreDispatch' //nome do método
),
100 //prioridade
);
}
//Valida Autenticaçãode usuário
public function mvcPreDispatch(MvcEvent $e)
{
$routeAuth = 'user-auth';
//Pega Controller
$controller = $e->getTarget();
//Get sessão de usuário autenticado
$auth = $controller->getServicelocator()
->get('Authentication');
//Verifica pela rota se o user pode ou não acessar (matchedRoute = Rota correspondente)
$matched = $controller->getEvent()
->getRouteMatch();
$matchedRoute = $matched->getMatchedRouteName(); //Pega a rota que está sendo acessada
$matchedAction = $matched->getParam('action');
//Se não estiver Logado e sua rota não for rota de autenticação redireciona
if (!$auth->hasIdentity() and
$matchedRoute != $routeAuth and
$matchedAction != 'add' and
$matchedRoute != 'home'
) {
$controller->flashMessenger()->addErrorMessage("Você não está Logado.");
return $controller->redirect()->toRoute($routeAuth);
} elseif ($auth->hasIdentity()) {
$this->verificaAcl(
$e,
$auth->getIdentity()['user'] //Dados do usuário Logado
);
}
}
public function verificaAcl(MvcEvent $e, $user)
{
$acl = $e->getApplication()
->getServiceManager()
->get('Acl\Permissions\Acl');
$matches = $e->getRouteMatch();
//Rota Acessada
$matchedRoute = $matches->getMatchedRouteName();
//Controller acessado
$matchedController = ucfirst($matches->getParam('controller'));
//Action Acessada
$matchecAction = $matches->getParam('action');
$role = $this->verifyRole($user->getPerfil());
if (!$acl->isAllowed($role, $matchedController, $matchecAction)) {
$controller = $e->getTarget();
$controller->flashMessenger()
->addErrorMessage("Você não tem permissão para acessar está área.");
$url = $e->getRouter()->assemble(array(), array('name' => 'user-perfil'));
$response = $e->getResponse();
$response->getHeaders()->addHeaders(array(
array('Location' => $url )
));
$response->setStatusCode(302);
$response->sendHeaders();
exit;
}
}
//Se Role estiver vazia ou não existir é dado o Papel de Cliente
public function verifyRole($role)
{
if (isset($role) and !empty($role))
return $role;
return $role = 'Cliente';
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return include __DIR__ . '/config/service.config.php';
}
public function getFormElementConfig()
{
return array(
'invokables' => array(
'User\Form\CreateUser' => 'User\Form\CreateUser'
),
'factories' => array(
'User\Form\UserFieldset' => function (ServiceLocatorInterface $sm) {
$serviceLocator = $sm->getServiceLocator();
$entity = $serviceLocator->get('User\Entity\User');
$em = $serviceLocator->get('Doctrine\ORM\EntityManager');
//Strategie para datade Nascimento
$hydrator = new ClassMethods(false);
$hydrator->addStrategy('dataNascimento', new DateTimeStrategy());
$userFieldset = new Form\UserFieldset('user', $hydrator, $entity);
$userFieldset->setObjectManager($em);
return $userFieldset;
},
'User\Form\AddressFieldset' => function (ServiceLocatorInterface $sm) {
$hydrator = new ClassMethods(false);
$serviceLocator = $sm->getServiceLocator();
$entity = $serviceLocator->get('User\Entity\Address');
return new Form\AddressFieldset(
'address',
$hydrator,
$entity
);
},
)
);
}
public function getViewHelperConfig()
{
return array(
'invokables' => array(
'userIdentity' => 'Auth\View\Helper\UserIdentity'
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment