Example #1
0
 public function loginAction()
 {
     if ($this->authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('dashboard');
     }
     $storage = $this->authenticationService->getStorage();
     $this->authenticationService->setStorage(new NonPersistent());
     $redir = $this->params()->fromQuery('redir', $this->params()->fromPost('redir'));
     if ($redir !== null) {
         $this->authSession->url = $redir;
         return $this->redirect()->toRoute('login');
     }
     if ($this->getRequest()->isPost()) {
         $this->authenticateForm->setData($this->getRequest()->getPost());
         if ($this->authenticateForm->isValid()) {
             /** @var AccountInterface $account */
             $account = $this->zourceAccount();
             $this->authSession->identity = $this->identity();
             $this->authSession->verified = false;
             $this->authenticationService->setStorage($storage);
             return $this->redirectAfterLogin($account);
         }
     }
     $this->resetTwoFactorAuthentication();
     return new ViewModel(['authenticateForm' => $this->authenticateForm]);
 }
 /**
  * @var AuthenticationService
  */
 public function __construct(AuthenticationService $authService, array $config)
 {
     $roles = array();
     $this->authService = $authService;
     $this->config = $config;
     $roleKey = $this->config['identity_providers']['ldap_role_key'];
     if ($this->authService->hasIdentity()) {
         $rawObj = $this->authService->getIdentity()->getRawLdapObj();
         $data = @unserialize($rawObj);
         if ($data !== false) {
             $user = unserialize($rawObj);
             if (!is_null($user) || is_array($user)) {
                 $roles = array('user');
                 foreach ($user[$roleKey] as $role) {
                     //if (isset($definedRoles[$role]))
                     $roles[] = $role;
                 }
             }
         }
     }
     if (!is_array($roles)) {
         throw new InvalidArgumentException('ZfcUserLdapRbacIdentityProvider only accepts strings or arrays');
     }
     $this->roles = $roles;
 }
 /**
  * {@inheritDoc}
  */
 public function getIdentityRoles()
 {
     $definedRoles = $this->bjyConfig['role_providers']['BjyAuthorize\\Provider\\Role\\Config']['user']['children'];
     $roleKey = $this->config['identity_providers']['ldap_role_key'];
     if (!$this->authService->hasIdentity()) {
         return array($this->getDefaultRole());
     }
     $rawObj = $this->authService->getIdentity()->getRoles();
     //        $data = @unserialize($rawObj);
     //        if ($data === false) {
     //            return array($this->getDefaultRole());
     //        }
     //        $user = unserialize($rawObj);
     $user = $rawObj;
     if (is_null($user) || !is_array($user)) {
         return array($this->getDefaultRole());
     }
     $roles = array('user');
     //        foreach ($user[$roleKey] as $role) {
     foreach ($user as $role) {
         if (isset($definedRoles[$role])) {
             $roles[] = $role;
         }
     }
     return $roles;
 }
Example #4
0
 public function __invoke(MvcEvent $event)
 {
     if ($event->getRequest() instanceof ConsoleRequest) {
         return;
     }
     $match = $event->getRouteMatch();
     // No route match, this is a 404
     if (!$match instanceof RouteMatch) {
         return;
     }
     /** @var Application $app */
     $app = $event->getParam('application');
     $config = $app->getConfig();
     $disableForAuthorizedCallback = $config['authorized-redirect-to-route'];
     $redirectTo = $disableForAuthorizedCallback($match, $this->authService);
     if ($this->authService->hasIdentity() && !empty($redirectTo)) {
         $response = $this->redirectTo($event, $redirectTo);
         return $response;
     }
     $checkCallback = $config['need-authorization-callback'];
     // if true = authorization needed
     if (!$checkCallback($match, $this->authService)) {
         return;
     }
     // User is authenticated
     if ($this->authService->hasIdentity()) {
         return;
     }
     $response = $this->redirectTo($event, $config['not-authorized-redirect-to-route']);
     return $response;
 }
Example #5
0
 /**
  * Retrieve the current admin
  *
  * @return UserModel|boolean
  */
 public function __invoke()
 {
     if ($this->auth->hasIdentity()) {
         return $this->auth->getIdentity();
     }
     return false;
 }
 /**
  * preDispatch Event Handler
  * Handle authentication process
  * Decide where user should be redirected to when logged in or not
  * 
  * 
  * @access public
  * @uses AuthenticationService
  * @uses Response
  * 
  * @param \Zend\Mvc\MvcEvent $event
  * @throws \Exception
  */
 public function preDispatch(MvcEvent $event)
 {
     // ACL dispatcher is used only in HTTP requests not console requests
     if (!$event->getRequest() instanceof HttpRequest) {
         return;
     }
     $userAuth = new AuthenticationService();
     $user = array();
     $signInController = 'DefaultModule\\Controller\\Sign';
     if ($userAuth->hasIdentity()) {
         $user = $userAuth->getIdentity();
     }
     $routeMatch = $event->getRouteMatch();
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if ($userAuth->hasIdentity() && isset($user['status']) && $user['status'] == 2) {
         $userAuth->clearIdentity();
         // redirect to sign/out
         $url = $event->getRouter()->assemble(array('action' => 'out'), array('name' => 'defaultSign'));
     } else {
         if ($userAuth->hasIdentity() && $controller == $signInController && $action == 'in') {
             // redirect to index
             $url = $event->getRouter()->assemble(array('action' => 'index'), array('name' => 'home'));
         }
     }
     if (isset($url)) {
         $event->setResponse(new Response());
         $this->redirect()->getController()->setEvent($event);
         $response = $this->redirect()->toUrl($url);
         return $response;
     }
 }
Example #7
0
 public function logout()
 {
     if ($this->authService->hasIdentity()) {
         $this->authService->clearIdentity();
         $this->sessionManager->forgetMe();
     }
 }
Example #8
0
 public function validAuthAcl($e)
 {
     $storage = new SessionStorage();
     $auth = new AuthenticationService();
     $auth->setStorage($storage);
     //pega controller e action
     $controller = $e->getTarget();
     $em = $controller->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $matchedRoute = $controller->getEvent()->getRouteMatch()->getMatchedRouteName();
     $matchedController = $controller->getEvent()->getRouteMatch()->getParam('controller');
     $matchedAction = $controller->getEvent()->getRouteMatch()->getParam('action', 'index');
     //user logado
     if ($auth->hasIdentity()) {
         $arrayUser = $auth->getIdentity();
         $repository = $em->getRepository("Zf2User\\Entity\\User");
         $user = $repository->findOneById($arrayUser->getId());
         $role = $user->getRole()->getName();
     } elseif (!$auth->hasIdentity()) {
         $role = 'Visit';
     }
     //acl
     $acl = $controller->getServiceLocator()->get("Zf2Acl\\Permissions\\Acl");
     if (!$acl->isAllowed($role, $matchedController, $matchedAction)) {
         $e->getResponse()->setStatusCode(Response::STATUS_CODE_404);
         $e->stopPropagation();
     }
 }
 public function testFailAuthenticationOnNoToken()
 {
     $token = new AccessToken();
     $owner = $this->getMock(TokenOwnerInterface::class);
     $token->setOwner($owner);
     $this->resourceServer->expects($this->atLeastOnce())->method('getAccessToken')->with($this->isInstanceOf(PsrServerRequestInterface::class))->will($this->returnValue(null));
     $this->assertFalse($this->authenticationService->hasIdentity());
     $this->assertNull($this->authenticationService->getIdentity());
 }
 public function validaAuth(MvcEvent $e)
 {
     $auth = new AuthenticationService();
     $auth->setStorage(new SessionStorage("SessaoUsuario"));
     $controller = $e->getTarget();
     $matchedRoute = $controller->getEvent()->getRouteMatch()->getMatchedRouteName();
     if ((!$auth->hasIdentity() and $matchedRoute == "language" || $matchedRoute == "language/default") || (!$auth->hasIdentity() and $matchedRoute == "user" || $matchedRoute == "user/default") || (!$auth->hasIdentity() and $matchedRoute == "application" || $matchedRoute == "application/default") || (!$auth->hasIdentity() and $matchedRoute == "home")) {
         return $controller->redirect()->toRoute("login");
     }
 }
Example #11
0
 /**
  * Retrieve the current identity, if any.
  *
  * If none available, returns null.
  *
  * @throws Exception\RuntimeException
  * @return mixed|null
  */
 public function __invoke()
 {
     if (!$this->authenticationService instanceof AuthenticationService) {
         throw new Exception\RuntimeException('No AuthenticationService instance provided');
     }
     if (!$this->authenticationService->hasIdentity()) {
         return null;
     }
     return $this->authenticationService->getIdentity();
 }
 /**
  * If user is logged in, it calls UnauthorizedStrategy otherwise it calls RedirectStrategy
  *
  * @param  MvcEvent $event
  * @return void
  */
 public function onError(MvcEvent $event)
 {
     $app = $event->getApplication();
     $serviceManager = $app->getServiceManager();
     if ($this->authenticationService->hasIdentity()) {
         $serviceManager->get('ZfcRbac\\View\\Strategy\\UnauthorizedStrategy')->onError($event);
     } else {
         $serviceManager->get('ZfcRbac\\View\\Strategy\\RedirectStrategy')->onError($event);
     }
 }
Example #13
0
 /**
  * @param RequestInterface $request
  *
  * @return bool
  */
 public function isAllowed(RequestInterface $request)
 {
     if (!$request instanceof Http\Request) {
         return false;
     }
     if ($this->authService->hasIdentity()) {
         return true;
     }
     $path = $request->getUri()->getPath();
     return in_array($path, ['', '/']);
 }
Example #14
0
 /**
  * {@inheritDoc}
  */
 public function getIdentityRoles()
 {
     //if user was manually deleted from storage we should clear identity
     if ($this->authService->hasIdentity() && !$this->authService->getIdentity()) {
         $this->authService->clearIdentity();
     }
     if (!$this->authService->hasIdentity()) {
         return array($this->getDefaultRole());
     }
     return $this->authService->getIdentity()->getUser()->getRole();
 }
 /**
  * @return string
  */
 public function __invoke()
 {
     $template = '';
     if ($this->authService->hasIdentity()) {
         $user = $this->authService->getIdentity();
         $viewModel = new ViewModel(['user' => $user, 'coins' => $this->gameBackendService->getCoins($user), 'loggedIn' => $this->config['logged_in']]);
         $viewModel->setTemplate('helper/sidebarLoggedInWidget');
         $template = $this->getView()->render($viewModel);
     }
     return $template;
 }
Example #16
0
 /**
  * See if user is logged in.
  *
  * @param string $errorString
  *
  * @return bool
  */
 public function hasIdentity($errorString = 'ERROR')
 {
     if ($this->auth->hasIdentity()) {
         if ($this->getIdentity()) {
             return true;
         }
         return $this->clearUserData($errorString);
         // something is wrong, clear all user data
     }
     return false;
 }
Example #17
0
 /**
  * ログイン情報取得
  *
  * @return AbstractModel
  */
 public function getLoginUser()
 {
     // ログイン確認
     if ($this->auth->hasIdentity()) {
         // ログイン情報を取得する
         $identity = $this->auth->getIdentity();
         $keys = [];
         foreach ($this->table->getPrimaryKeys() as $key) {
             $keys[$key] = $identity[$key];
         }
         return $this->table->findByPrimaryKey($keys);
     }
     return false;
 }
Example #18
0
 /**
  * Returns HTML for administrator links
  *
  * @param void
  * @return string
  * @override
  **/
 public function __invoke()
 {
     if (!$this->_authService->hasIdentity()) {
         return false;
     }
     return sprintf('<div class="adminPanel">
             <h1>Administrative Panel</h1>
             <div class="breadcrumbs">
                 <a title="create post" href="%s">Create Post</a> |
                 <a title="manage posts" href="%s">Manage Posts</a> |
                 <a title="view comments" href="%s">Manage Comments</a> |
                 <a title="log out" href="%s">Logout</a>
             </div>
         </div>', $this->view->myUrl('blog/default', array('controller' => 'blog', 'action' => 'create')), $this->view->myUrl('blog/default', array('controller' => 'blog', 'action' => 'view-all')), $this->view->myUrl('blog/default', array('controller' => 'comment', 'action' => 'view')), $this->view->myUrl('blog/default', array('controller' => 'user', 'action' => 'logout')));
 }
 /**
  * verify authentication
  */
 public function verificaAuth()
 {
     $this->identity = $this->auth->getStorage()->read();
     if (!$this->auth->hasIdentity()) {
         //there is no id?
         $this->redirect()->toRoute('Locador/logoff');
     } else {
         $this->locador = $this->identity[0];
         $this->layout()->locador = $this->locador;
         $visitas = $this->getEm()->getRepository("MyClasses\\Entities\\Locador")->find($this->locador->getId())->getVisitas()->filter(function ($visita) {
             return $visita->getStatus() == "agendada";
         })->count();
         $this->layout()->visitas = $visitas;
     }
 }
 public function dispatch(MvcEvent $event)
 {
     $request = $event->getRequest();
     if ($request instanceof ConsoleRequest) {
         return true;
     }
     $auth = new AuthenticationService();
     //ALREADY LOGGED IN
     //	user has auth,
     if ($auth->hasIdentity()) {
         return true;
         //NOT LOGGED IN
         //
     } else {
         /** @var $request \Zend\Http\PhpEnvironment\Request */
         $cookies = $request->getCookie();
         /** @var $cookies \Zend\Http\Header\Cookie */
         $userService = $this->getServiceLocator()->get('Stjornvisi\\Service\\User');
         /** @var $user \Stjornvisi\Service\User */
         if ($cookies && $cookies->offsetExists('backpfeifengesicht')) {
             if (($user = $userService->getByHash($cookies->offsetGet('backpfeifengesicht'))) != false) {
                 $authAdapter = $this->getServiceLocator()->get('Stjornvisi\\Auth\\Adapter');
                 $authAdapter->setIdentifier($user->id);
                 $result = $auth->authenticate($authAdapter);
                 $result->isValid();
             }
         }
     }
 }
 public function indexAction()
 {
     /* 	$temp = $this->forward()->dispatch('Application/Controller/Album', array('action' => 'index'));
     		
     		echo '<pre>'; print_r($temp); echo '<pre>';die; */
     $auth = new AuthenticationService();
     if (!$auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $select = new Select();
     $search = @$_REQUEST['search'];
     if (!empty($search)) {
         $select->where->like('name', '%' . $search . '%');
     }
     $order_by = $this->params()->fromRoute('order_by') ? $this->params()->fromRoute('order_by') : 'id';
     $order = $this->params()->fromRoute('order') ? $this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
     $page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
     $category = $this->getCategoryTable()->fetchAllCategory($select->order($order_by . ' ' . $order), $search);
     $itemPerPage = 2;
     $category->current();
     $paginator = new Paginator(new PaginatorIterator($category));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage($itemPerPage);
     $paginator->setPageRange(10);
     return new ViewModel(array('order_by' => $order_by, 'order' => $order, 'page' => $page, 'paginator' => $paginator));
 }
Example #22
0
 /**
  * Is user logged in?
  *
  * @return boolean
  */
 public function isLoggedIn()
 {
     if ($this->authService->hasIdentity()) {
         return true;
     }
     return false;
 }
 /**
  * Handle authentication
  *
  * @param  GetResponseEvent $event
  * @throws RuntimeException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$this->isRequestNeedProcessing($request) || $this->authentication->hasIdentity()) {
         return;
     }
     /* @var $adapter \SilexCMF\ZendAuthentication\Adapter\Http\HttpBasedAdapter */
     $adapter = $this->authentication->getAdapter();
     if (!$adapter || !$adapter instanceof HttpBasedAdapter) {
         throw new RuntimeException(sprintf('Unsupported adapter type %s', is_object($adapter) ? get_class($adapter) : gettype($adapter)));
     }
     $result = $this->authentication->authenticate();
     if (!$result->isValid()) {
         $event->setResponse($adapter->getResponse());
     }
 }
Example #24
0
 public function loginAction()
 {
     if ($this->authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $this->layout('layout/layout-blank');
     $resultModel = new JsonResultModel();
     if ($this->getRequest()->isPost()) {
         $jsonData = $this->getRequest()->getPost('login');
         $data = Json::decode($jsonData, Json::TYPE_ARRAY);
         // If you used another name for the authentication service, change it here
         $adapter = $this->authenticationService->getAdapter();
         $adapter->setIdentityValue($data['username']);
         $adapter->setCredentialValue($data['password']);
         $authResult = $this->authenticationService->authenticate();
         //@todo remember me
         if ($authResult->isValid()) {
             if ($data['rememberMe']) {
                 $this->authenticationService->getStorage()->getManager()->rememberMe(36000);
             }
             return $resultModel;
         } else {
             $resultModel->addErrors('password', '登录名或密码错误');
             return $resultModel;
         }
     }
 }
 public function membreAction()
 {
     $return = null;
     $identifiantMembre = (int) $this->params()->fromRoute('id', 0);
     $auth = new AuthenticationService();
     $logged = null;
     if ($auth->hasIdentity()) {
         $session = new Container('user');
         $logged = $session->offsetGet('id');
     }
     $like = array();
     $images = $this->getImageTable()->fetchAllById($identifiantMembre);
     if ($logged != null) {
         foreach ($images as $image) {
             $isLike = $this->getLikeTable()->fetchCorrespondance($logged, $image->id);
             foreach ($isLike as $isLikeTest) {
                 if ($isLikeTest->id != null) {
                     array_push($like, 'FALSE');
                 } else {
                     array_push($like, 'TRUE');
                 }
             }
         }
     }
     return new ViewModel(array('images' => $this->getImageTable()->fetchAllById($identifiantMembre), 'user' => $this->getUserTable()->getUser($identifiantMembre), 'like' => $like));
 }
Example #26
0
 public function validaAuth($e)
 {
     $sessionStorage = new SessionStorage("geframa_admin");
     $authService = new AuthenticationService();
     $authService->setStorage($sessionStorage);
     $controller = $e->getTarget();
     $matchedRoute = $controller->getEvent()->getRouteMatch()->getMatchedRouteName();
     //        die("<pre>" . __FILE__ . "\nLinha " . __LINE__ . "\n\n" . \Zend\Debug\Debug::dump($matchedRoute) . "</pre>");
     if (!$authService->hasIdentity() and !(strpos($matchedRoute, 'geframa_login') === 0 || strpos($matchedRoute, 'layout_') === 0 || strpos($matchedRoute, 'core_') === 0)) {
         //         die("<pre>" . __FILE__ . "\nLinha " . __LINE__ . "\n\n" . print_r($matchedRoute, 1) . "</pre>");
         return $controller->redirect()->toRoute("geframa_login");
     }
     /*
            $sessionStorage = new SessionStorage($namespace);
            $this->authService = new AuthenticationService;
            $this->authService->setStorage($sessionStorage);
     
            if ($this->getAuthService()->hasIdentity()) {
                return $this->getAuthService()->getIdentity();
            }
            else {
                return false;
            }
     */
 }
Example #27
0
 public function secureAdminRoute(MvcEvent $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     if (0 === strpos($e->getRouteMatch()->getMatchedRouteName(), 'admin')) {
         /** @var Layout $layout */
         $layout = $sm->get('ControllerPluginManager')->get('Layout');
         $layout->setTemplate('admin/layout');
         /** @var Redirect $redirector */
         $redirector = $sm->get('ControllerPluginManager')->get('Redirect');
         if ('admin' == $e->getRouteMatch()->getMatchedRouteName() && $this->authenticationService->hasIdentity()) {
             $redirector->toRoute('admin/posts');
         }
         if ('admin' != $e->getRouteMatch()->getMatchedRouteName() && !$this->authenticationService->hasIdentity()) {
             $redirector->toRoute('admin');
         }
     }
 }
Example #28
0
 public function __invoke(Request $request, Response $response, callable $next)
 {
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         $auth->clearIdentity();
     }
     return $next($request, $response);
 }
Example #29
0
 public function loginAction()
 {
     $authenticationService = new AuthenticationService();
     if ($authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('dashboard');
     }
     $form = new LoginForm();
     $viewModel = new ViewModel();
     $this->layout("layout/login");
     $viewModel->setVariable("form", $form);
     $viewModel->setVariable("config", $this->config);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $login = new Login();
         $login->getInputFilter()->get('captcha')->setRequired(false);
         $form->setInputFilter($login->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $username = $form->get('username')->getValue();
             $password = $form->get('password')->getValue();
             $authSessionAdapter = $this->getAuthSessionAdapter();
             if ($authSessionAdapter->authenticate($username, $password)) {
                 $userObject = $authenticationService->getStorage()->read();
                 $rol = $userObject->rol;
                 $acl = new Acl();
                 $acl->addResource(new Resource("dashboard"));
                 $acl->addResource(new Resource("note"));
                 if ($rol == 1) {
                     $resources = $this->config['resources'];
                     foreach ($resources as $module => $resource) {
                         foreach ($resource as $resourceValue) {
                             $acl->addResource(new Resource($resourceValue));
                         }
                     }
                 } else {
                     $acl->addRole(new Role($rol));
                     $modules = $this->getModuleRolTable()->fetchAll($rol);
                     foreach ($modules as $module) {
                         $acl->addResource(new Resource($module));
                     }
                 }
                 $userObject->acl = serialize($acl);
                 return $this->redirect()->toRoute('dashboard');
             } else {
                 $form->get('username')->setValue("");
                 $form->get('password')->setValue("");
                 if ($authSessionAdapter->getCode() == -5) {
                     $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][$authSessionAdapter->getCode()]));
                 } else {
                     $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6]));
                 }
             }
         } else {
             $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6]));
         }
     }
     return $viewModel;
 }