public function __invoke(Request $req, Response $res, callable $next) { $res = $next($req, $res); $identity = $this->authService->getIdentity(); if (!$identity) { return $res; } try { $user = R::findOne('user', 'mail = ?', [$identity->mail]); if (!$user) { $user = R::dispense('user'); $user->uid = $identity->uid; $user->mail = $identity->mail; $user->display_name = $identity->displayName; $user->office_name = $identity->officeName; $user->authentication_source = $identity->authenticationSource; $user->password = ''; $user->created = time(); $user->role = 'school'; $this->logger->info(sprintf('User %s imported from sso.sch.gr to database', $identity->mail)); } $user->last_login = time(); $user_id = R::store($user); $identityClass = get_class($identity); $newIdentity = new $identityClass($user_id, $user->uid, $user->mail, $user->display_name, $user->office_name, $user->authentication_source); $this->authService->getStorage()->write($newIdentity); } catch (\Exception $e) { $this->authService->clearIdentity(); $this->flash->addMessage('danger', 'A problem occured storing user in database. <a href="%s" title="SSO logout">SSO Logout</a>'); $this->logger->error('Problem inserting user form CAS in database', $identity->toArray()); $this->logger->debug('Exception', [$e->getMessage(), $e->getTraceAsString()]); return $res->withRedirect($this->userErrorRedirectUrl); } return $res; }
/** * {@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; }
/** * Get the user value to set on a Loggable field * * @param object $meta * @param string $field * * @return mixed */ public function getUserValue($meta, $field) { if (empty($this->user) || !$this->user instanceof User) { $this->user = $this->authService->getIdentity(); } return $this->user; }
/** * @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; }
/** * Retrieve the current admin * * @return UserModel|boolean */ public function __invoke() { if ($this->auth->hasIdentity()) { return $this->auth->getIdentity(); } return false; }
/** * @param $resource * @param $permission * @return bool */ public function isAllowed($module, $permission, $element = null, $entity = null) { if (!$this->getAclService()->getUser()) { $this->getAclService()->setUser($this->authService->getIdentity()); } return $this->getAclService()->isAllowed($module, $permission, $element, $entity); }
public function indexAction() { $form = new LoginForm(); $error = false; $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); $auth = new AuthenticationService(); $sessionStorage = new SessionStorage("AssistenteAdmin"); $auth->setStorage($sessionStorage); $authAdapter = $this->getServiceLocator()->get('Assitente\\Auth\\Adapter'); $authAdapter->setUsername($data['email'])->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $dadosUsuario = $auth->getIdentity()['user']; //cria um container(sessao) chamada usuario $user_session = new Container('usuario'); $user_session->id = $dadosUsuario['id']; $user_session->nome = $dadosUsuario['nome']; $user_session->matricula = $dadosUsuario['matricula']; $user_session->foto = $dadosUsuario['foto']; $user_session->dataNascimento = $dadosUsuario['dataNascimento']; $user_session->email = $dadosUsuario['email']; $sessionStorage->write($auth->getIdentity()['user'], null); return $this->redirect()->toRoute("assistente", array('controller' => 'usuarios')); } else { $error = true; } } } return new ViewModel(array('form' => $form, 'error' => $error)); }
/** * @param MvcEvent $e * @return bool */ public function AuthAndAcl($e) { $acl = new MyAcl(); $auth = new AuthenticationService(); // Get User Role $role = $auth->getIdentity() ? User::getUserRole($auth->getIdentity()) : 'guest'; return $acl->isAllowed($role, $e->getRouteMatch()->getParam('controller')); }
/** * Get the identity * * @return IdentityInterface|null */ public function getIdentity() { $identity = $this->authenticationService->getIdentity(); $rbacIdentity = new RbacIdentity(); if ($identity) { $rbacIdentity->setRoles($identity->getRoles()); } return $rbacIdentity; }
public function testFailAuthenticationOnExpiredToken() { $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->throwException(new OAuth2Exception('Expired token', 123))); $this->setExpectedException(OAuth2Exception::class, 'Expired token', 123); $this->authenticationService->getIdentity(); }
/** * {@inheritDoc} */ public function getIdentityRoles() { $identity = $this->authService->getIdentity(); if ($identity) { return explode(',', $identity->getGroups()); } else { return array($this->defaultRole); } }
/** * 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(); }
/** * @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; }
/** * {@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(); }
/** * Returns an array of common actions and whether they are allowed for current user * * This should NOT be used in our own code, because it is suboptimal, * instead a direct, single call to Authorization service is preferred. It exists here * only for ease of use for REST API. * @param AbstractModel $object * @return array */ private function getPermissions(AbstractModel $object) { $identity = $this->authentification->getIdentity(); $resourceId = $this->getResourceId($object); $resource = new \Application\Authorization\ModelResource($resourceId, $object); $result = []; $result['read'] = $this->authorization->isAuthorized($identity, $resource, Request::METHOD_GET); $result['update'] = $this->authorization->isAuthorized($identity, $resource, Request::METHOD_PUT); $result['delete'] = $this->authorization->isAuthorized($identity, $resource, Request::METHOD_DELETE); return $result; }
/** * Send mail * * @return array|ViewModel */ public function sendAction() { $sm = $this->getServiceLocator(); $userService = $sm->get('Stjornvisi\\Service\\User'); //AUTHENTICATION // get authentication service $auth = new AuthenticationService(); $access = $userService->getTypeByGroup($auth->hasIdentity() ? $auth->getIdentity()->id : null, null); //ACCESS // user has access if ($access->is_admin) { //POST // post request if ($this->request->isPost()) { $post = $this->getRequest()->getPost(); /** @var $post \ArrayObject */ $form = new GroupEmail(); $form->setData($post); $form->setAttribute('action', $this->url()->fromRoute('email/send', ['type' => $this->params()->fromRoute('type', 'allir')])); //VALID // form is valid if ($form->isValid()) { //TEST // send out test e-mail if ($post->offsetGet('test')) { $this->getEventManager()->trigger('notify', $this, ['action' => 'Stjornvisi\\Notify\\All', 'data' => (object) array('recipients' => $this->params()->fromRoute('type', 'allir'), 'test' => true, 'subject' => $form->get('subject')->getValue(), 'body' => $form->get('body')->getValue(), 'sender_id' => (int) $auth->getIdentity()->id)]); return new ViewModel(array('form' => $form, 'msg' => "Prufupóstur hefur verið sendur á {$auth->getIdentity()->email}")); //SEND // send out full e-mail } else { $this->getEventManager()->trigger('notify', $this, ['action' => 'Stjornvisi\\Notify\\All', 'data' => (object) array('recipients' => $this->params()->fromRoute('type', 'allir'), 'test' => false, 'subject' => $form->get('subject')->getValue(), 'body' => $form->get('body')->getValue(), 'sender_id' => (int) $auth->getIdentity()->id)]); return new ViewModel(array('form' => null, 'msg' => 'Póstur sendur')); } //INVALID // the form is invalid } else { return new ViewModel(array('form' => $form, 'msg' => '')); } //QUERY // get request } else { $from = new GroupEmail(); $from->setAttribute('action', $this->url()->fromRoute('email/send', ['type' => $this->params()->fromRoute('type', 'allir')])); return new ViewModel(array('form' => $from)); } //NO ACCESS } else { $this->getResponse()->setStatusCode(401); $model = new ViewModel(); $model->setTemplate('error/401'); return $model; } }
public function testCanAuthenticateWithGoodCredentials() { $authAdapter = Bootstrap::getServiceManager()->get('ZfSimpleAuth\\Authentication\\Adapter'); $authAdapter->setIdentity('demo-admin'); $authAdapter->setCredential('foobar'); $result = $this->authenticationService->authenticate($authAdapter); $this->assertTrue($result->isValid()); $identity = $this->authenticationService->getIdentity(); $this->assertInstanceOf('\\ZfSimpleAuth\\Authentication\\Identity', $identity); /* @var \ZfSimpleAuth\Authentication\Identity $identity */ $this->assertEquals('demo-admin', $identity->getName()); $this->assertEquals(array('admin', 'member'), $identity->getRoles()); }
/** * {@inheritDoc} */ public function getIdentityRoles() { if (!($identity = $this->authService->getIdentity())) { return array($this->defaultRole); } if ($identity instanceof RoleInterface) { return array($identity); } if ($identity instanceof RoleProviderInterface) { return $identity->getRoles(); } return array($this->authenticatedRole); }
/** * ログイン情報取得 * * @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; }
/** * Get the Client the logged in user is associated with * * @return Client */ public function getClient() { if (empty($this->client) || !$this->client instanceof Client) { /** * @type $user User */ $user = $this->authService->getIdentity(); if (empty($user) || !$user instanceof User) { return null; } $client = $user->getClient(); $this->client = $client; } return $this->client; }
/** * @return \Zend\Http\Response|ViewModel */ public function indexAction() { $form = new LoginForm(); $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); $authAdapter = $this->getServiceLocator()->get('SONUser\\Auth\\Adapter'); $authAdapter->setUsername($data['email']); $authAdapter->setPassword($data['password']); $auth = new AuthenticationService(); $sessionStorage = new SessionStorage('SONUser'); $auth->setStorage($sessionStorage); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $sessionStorage->write($auth->getIdentity()['user'], null); return $this->redirect()->toRoute('sonuser-admin/default', array('controller' => 'users')); } else { $this->error = true; } } } return new ViewModel(array('form' => $form, 'error' => $this->error)); }
/** * 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; } }
public function indexAction() { $form = new LoginForm(); $error = FALSE; $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); $sessionStorage = new SessionStorage("EOSUser"); //Storage para guardar sessão de autenticação $auth = new AuthenticationService(); $auth->setStorage($sessionStorage); //define sessionStorage para Auth $authAdapter = $this->getServiceLocator()->get('EOSUser\\Auth\\Adapter'); $authAdapter->setUsername($data['email']); $authAdapter->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $user = $auth->getIdentity(); $user = $user['user']; $sessionStorage->write($user, null); // $sessionStorage->write($auth->getIdentity()['user'], NULL); return $this->redirect()->toRoute('eosuser-admin/default', array('controller' => 'users')); } else { $error = TRUE; } } } return new ViewModel(array('form' => $form, 'error' => $error)); }
public function indexAction() { $form = new LoginForm('login'); $error = false; $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); // Criando Storage para gravar sessão da authtenticação $sessionStorage = new SessionStorage("geframa_admin"); $auth = new AuthenticationService(); $auth->setStorage($sessionStorage); // Definindo o SessionStorage para a auth $authAdapter = $this->getServiceLocator()->get("Admin\\Auth\\Adapter"); $authAdapter->setUsername($data['email']); $authAdapter->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { /* $user = $auth->getIdentity(); $user = $user['user']; $sessionStorage->write($user,null); */ $sessionStorage->write($auth->getIdentity()['user'], null); return $this->redirect()->toRoute('geframa_admin', array('controller' => 'users')); } else { $error = true; } } } $view = new ViewModel(array('form' => $form, 'error' => $error)); $view->setTerminal(true); return $view; }
/** * Login User * * @return \Zend\Http\Response|ViewModel */ public function indexAction() { $form = new FormLogin(); $error = false; $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); $auth = new AuthenticationService(); $sessionStorage = new SessionStorage('BookstoreAdmin'); $auth->setStorage($sessionStorage); $authAdapter = $this->getServiceLocator()->get('Bookstore\\Auth\\Adapter'); $authAdapter->setUsername($data['email'])->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $sessionStorage->write($auth->getIdentity()['user'], null); return $this->redirect()->toRoute('home-admin', ['controller' => 'categories']); } else { $error = true; } } } return new ViewModel(['form' => $form, 'error' => $error]); }
public function indexAction() { $form = new LoginForm(); $error = false; $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $data = $request->getPost()->toArray(); } $auth = new AuthenticationService(); $sessionStorage = new SessionStorage("Application"); $auth->setStorage($sessionStorage); $authAdapter = $this->getServiceLocator()->get('Application\\Auth\\DoctrineAdapter'); $authAdapter->setUsername($data['email'])->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $sessionStorage->write($auth->getIdentity()['user'], null); return $this->redirect()->toRoute("Application", array('controller' => 'IndexController', 'action' => 'index')); } else { $error = true; } } return new ViewModel(array('form' => $form, 'error' => $error)); }
public function indexAction() { $this->layout('layout/layoutLogin'); $request = $this->getRequest(); $form = new LoginForm(); if ($request->isPost()) { $form->setData($request->getPost()->toArray()); if ($form->isValid()) { $post = $request->getPost()->toArray(); #Criando storage para gravar sessão de authenticacação $sessionStorage = new SessionStorage('FuncSessao'); $auth = new AuthenticationService(); $auth->setStorage($sessionStorage); #Definindo session storage pra auth $authAdapter = $this->getServiceLocator()->get('Application\\Auth\\Adapter'); $authAdapter->setUsername($post['usuarioFunc']); $authAdapter->setPassword($post['senhaFunc']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $sessionStorage->write($auth->getIdentity()['funcionarioUser']); return $this->redirect()->toUrl('/application/index/index'); } else { var_dump("ERROR"); $error = true; } } } $view = new ViewModel(); $view->setVariable('form', $form); return $view; }
public function changePasswordAction() { $resultModel = new JsonResultModel(); if ($this->getRequest()->isPost()) { try { $jsonData = $this->params()->fromPost('password'); $data = Json::decode($jsonData); $this->accountService->changePassword($this->authenticationService->getIdentity()->getId(), $data->password, $data->newPassword); } catch (ValidationException $ve) { return $resultModel->setErrors($ve->getValidationError()); } catch (\Exception $e) { return $resultModel->addErrors('error', 'unknow error'); } return $resultModel; } }
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 loginAction() { $messages = null; $isAuth = false; $form = new LoginForm(); $auth = new AuthenticationService(); $sessionStorage = new SessionStorage("Login"); $request = $this->getRequest(); if ($request->isPost()) { $data = $request->getPost()->toArray(); $form->setData($data); if ($form->isValid()) { $auth->setStorage($sessionStorage); $authAdapter = $this->getPluginManager()->getServiceLocator()->get('VMBLogin\\Auth\\Adapter'); $authAdapter->setUsername($data['username'])->setPassword($data['password']); $result = $auth->authenticate($authAdapter); if ($result->isValid()) { $sessionStorage->write($auth->getIdentity()['user'], null); $messages = "you are now authenticated"; $isAuth = true; } else { $messages = "username or password is incorrect"; } } } return new ViewModel(array('form' => $form, 'messages' => $messages, 'auth' => $isAuth)); }