Example #1
1
 public function indexAction()
 {
     $request = $this->getRequest();
     $user = new User();
     $this->connexionForm->bind($user);
     if ($request->isPost()) {
         $data = $request->getPost();
         $this->connexionForm->setData($data);
         if ($this->connexionForm->isValid()) {
             /** @var User $user */
             $user = $this->connexionForm->getData();
             $adapter = $this->authenticationService->getAdapter();
             $adapter->setIdentityValue($user->getUsername());
             $adapter->setCredentialValue($user->getPassword());
             $result = $this->authenticationService->authenticate();
             if ($result->isValid()) {
                 $this->flashMessenger()->addSuccessMessage($this->getTranslation('FORM_SUCCESS_LOGIN'));
                 return $this->redirect()->toRoute('admin/posts');
             }
         }
         $this->flashMessenger()->addErrorMessage($this->getTranslation('FORM_ERROR_LOGIN'));
         return $this->redirect()->toRoute('admin');
     }
     return new ViewModel(array('form' => $this->connexionForm));
 }
 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());
 }
 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()
 {
     try {
         $request = $this->getRequest();
         if ($request->isPost()) {
             $data = $request->getPost();
             $auth = new AuthenticationService();
             $sessionStorage = new SessionStorage();
             $auth->setStorage($sessionStorage);
             $authAdapter = $this->getServiceLocator()->get('Application\\Model\\Adapter');
             $authAdapter->setName($data['userName']);
             $authAdapter->setPassword($data['password']);
             $result = $auth->authenticate($authAdapter);
             $user = $result->getIdentity()['user'];
             if ($result->isValid()) {
                 $this->session = new Container('App_Auth');
                 $this->session->user = $result->getIdentity()['user'];
                 $this->session->selectedPill = 1;
                 return $this->redirect()->toUrl('/home');
             } else {
                 return $this->errorMessage('Usuário ou senha inválidos', '/login');
             }
         } else {
             if ($this->isLogged()) {
                 return $this->redirect()->toUrl('/home');
             }
             return array();
         }
     } catch (\Exception $e) {
         return $this->errorMessage('Não foi possível realizar o login', '/login');
     }
 }
 public function authenticate(AdapterInterface $adapter = null)
 {
     if (!$adapter) {
         if (!($adapter = $this->getAdapter())) {
             throw new \Exception('An adapter must be set or passed prior to calling authenticate()');
         }
     }
     if ($this->hasIdentity()) {
         $identity = $this->getIdentity();
         // if some of fields is empty, put '.' - otherwise DbTable will return a RuntimeException
         if (!isset($identity[$this->getIdentityColumn('login')])) {
             $identity[$this->getIdentityColumn('login')] = '.';
         }
         if (!isset($identity[$this->getIdentityColumn('password')])) {
             $identity[$this->getIdentityColumn('password')] = '.';
         }
         if (!isset($identity['signature'])) {
             $identity['signature'] = '.';
         }
         if (!isset($identity['timeout'])) {
             $identity['timeout'] = '.';
         }
         $adapter->setFirstLogin(false);
         $adapter->setIdentity($identity[$this->getIdentityColumn('login')]);
         $adapter->setCredential($identity[$this->getIdentityColumn('password')]);
         $adapter->setSessionFingerprinting($identity['signature']);
         $adapter->setSessionLimit($identity['timeout']);
     }
     $result = parent::authenticate($adapter);
     if (Result::SUCCESS == $result->getCode() && ($this->regenerateId || time() % 2 == 0)) {
         session_regenerate_id(true);
     }
     return $result;
 }
Example #6
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;
         }
     }
 }
Example #7
0
 public function authenticate($username, $password)
 {
     $callback = function ($password, $hash) {
         $bcrypt = new Bcrypt();
         return $bcrypt->verify($hash, $password);
     };
     $authenticationService = new AuthenticationService();
     $callbackCheckAdapter = new CallbackCheckAdapter($this->dbAdapter, "users", 'username', 'password', $callback);
     $callbackCheckAdapter->setIdentity($username)->setCredential($password);
     $authenticationService->setAdapter($callbackCheckAdapter);
     $authResult = $authenticationService->authenticate();
     if ($authResult->isValid()) {
         $userObject = $callbackCheckAdapter->getResultRowObject();
         $authenticationService->getStorage()->write($userObject);
         if ($userObject->status == 0) {
             $authenticationService->clearIdentity();
             $this->setCode(-5);
             return false;
         } else {
             return true;
         }
     } else {
         $this->setCode($authResult->getCode());
         return false;
     }
 }
 /**
  * @param Request $request
  * @param Response $response
  * @param callable $next
  * @return \Psr\Http\Message\MessageInterface|HtmlResponse
  * @throws Exception
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     //$form = new LoginForm('Login', []);
     //$form->get('submit')->setValue('Login');
     if ($request->getMethod() == 'POST') {
         $auth = new AuthenticationService();
         $query = $request->getParsedBody();
         $authAdapter = new AuthAdapter($query['login'], $query['password'], $this->authConfig);
         $result = $auth->authenticate($authAdapter);
         if (!$result->isValid()) {
             //$response->getBody()->write("Not valid authentication\n");
             //return $response->withStatus(403)->withHeader("Content-type", 'text/html');
             throw new Exception("Not valid authentication\n", 403);
         } else {
             if ($request->getUri()->getPath() === '/auth') {
                 $render = $this->template->render('app::homepage');
                 $query = $request->getParsedBody();
                 $query['view']['render'] = $render;
                 $query['view']['code'] = 200;
                 $request = $request->withParsedBody($query);
             }
             return $next($request, $response);
         }
     } else {
         $render = $this->template->render('app::login', ['error' => null]);
         $query = $request->getParsedBody();
         $query['view']['render'] = $render;
         $query['view']['code'] = 200;
         $request = $request->withParsedBody($query);
         return $next($request, $response);
     }
 }
 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));
 }
Example #10
0
 public function authenticate(array $credentials)
 {
     $username = $credentials['username'];
     $password = $credentials['password'];
     $dbAdapter = $this->serviceManager->get('Zend\\Db\\Adapter\\Adapter');
     $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'users', 'username', 'password', 'MD5(?)');
     $dbTableAuthAdapter->setIdentity($username);
     $dbTableAuthAdapter->setCredential($password);
     $authService = new AuthenticationService();
     $authService->setAdapter($dbTableAuthAdapter);
     //$authService->setStorage($this->getServiceManager()->get('IdAuth\Storage'));
     $authResult = $authService->authenticate();
     $result = new ProviderResult();
     $result->setAuthCode($authResult->getCode());
     $result->setMessages($authResult->getMessages());
     $result->setValid($authResult->isValid());
     $result->setName('IdAuth\\Providers\\DbTable');
     $config = $this->serviceManager->get('Config');
     $options = $config['idAuth']['providerOptions']['DbTable'];
     $result->setOptions($options);
     if ($authResult->isValid()) {
         $result->setIdentity($this->queryIdentity($username));
     }
     return $result;
 }
 public function authenticateAction()
 {
     if ($this->identity()) {
         return $this->redirect()->toRoute($this->routes['redirect']['name'], $this->routes['redirect']['params'], $this->routes['redirect']['options'], $this->routes['redirect']['reuseMatchedParams']);
     }
     $form = new SigninForm();
     $form->setAttribute('action', $this->url()->fromRoute($this->routes['authenticate']['name'], $this->routes['authenticate']['params'], $this->routes['authenticate']['options'], $this->routes['authenticate']['reuseMatchedParams']));
     $request = $this->getRequest();
     if ($request->isPost()) {
         $post = $request->getPost();
         $form->setData($post);
         if ($form->isValid()) {
             $authAdapter = $this->authenticationService->getAdapter();
             $authAdapter->setIdentityValue($form->get('username')->getValue());
             $authAdapter->setCredentialValue(sha1(sha1($form->get('password')->getValue())));
             $authResult = $this->authenticationService->authenticate();
             if ($authResult->isValid()) {
                 $identity = $authResult->getIdentity();
                 $authStorage = $this->authenticationService->getStorage();
                 if ($form->get('remember-me')->getValue() == 1) {
                     $authStorage->setRememberMe(1);
                 }
                 $authStorage->write($identity);
                 $this->flashMessenger()->addSuccessMessage(_('Sign in with success!'));
                 return $this->redirect()->toRoute($this->routes['redirect']['name'], $this->routes['redirect']['params'], $this->routes['redirect']['options'], $this->routes['redirect']['reuseMatchedParams']);
             } else {
                 $this->flashMessenger()->addErrorMessage(_('Username or password is invalid.'));
             }
         }
     }
     return $this->redirect()->toRoute($this->routes['signin']['name'], $this->routes['signin']['params'], $this->routes['signin']['options'], $this->routes['signin']['reuseMatchedParams']);
 }
 /**
  * @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));
 }
Example #13
0
 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()
 {
     $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;
 }
Example #16
0
 public function loginAction()
 {
     $messages = null;
     $form = new AuthForm();
     $form->get('submit')->setvalue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_name', 'usr_password', "MD5(CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
             // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
             // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
             $result = $auth->authenticate($authAdapter);
             //                echo '<pre>';
             //                print_r($result);
             //                echo '</pre>';
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                     //                                if ($data['rememberme']) {
                     //                                        $sessionManager = new \Zend\Session\SessionManager();
                     //                                        $sessionManager->rememberMe($time);
                     //                                }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         } else {
             echo '<h1> The form is NOT valid </h1>';
         }
     }
     //        echo '<pre>';
     //        print_r($_SESSION);
     //        echo '</pre>';
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
Example #17
0
 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));
 }
 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));
 }
Example #19
0
 public function indexAction()
 {
     //$this->modelUsers->createQuery('');
     $users = $this->modelUsers->findBy(array('isdelete' => '0'));
     //tableTitle = table heading
     //datarow row of table... render by heading key
     //heading key = table column name
     $dataRow = $this->modelUsers->convertToArray($users);
     $data = array('title' => $this->translator->translate('Login'), 'link' => '/admin/login', 'buttonLogin' => $this->translator->translate('Login'), 'userNameText' => $this->translator->translate('User name'), 'passwordText' => $this->translator->translate('Password'));
     if ($this->getRequest()->isPost()) {
         $userName = $this->params()->fromPost('userName');
         $password = $this->params()->fromPost('password');
         $data = $this->params()->fromPost();
         //login here
         $login_obj = new AuthenticationService(null, $this->modelUsers);
         $this->modelUsers->setLoginUser($data);
         $login_obj->authenticate();
         //check login
         $user = Utility::checkLogin($this);
         if ($user != null) {
             Utility::insertHistory('login');
             $this->redirect()->toRoute('admin/child', array('controller' => 'dashboard'));
         } else {
             $this->redirect()->toRoute('admin/child', array('controller' => 'login'));
         }
         //end check login
     }
     return new ViewModel($data);
 }
 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();
             }
         }
     }
 }
Example #21
0
 /**
  * Authenticates against the supplied adapter
  *
  * @param   AdapterInterface    $adapter
  * @return  \Zend\Authentication\Result
  * @throws  \Zend\Authentication\Exception\RuntimeException
  */
 public function authenticate(AdapterInterface $adapter = null)
 {
     $result = parent::authenticate($adapter);
     if ($result->isValid()) {
         $this->identityRefreshed = true;
     }
     return $result;
 }
Example #22
0
 public function __invoke(Request $req, Response $res)
 {
     if ($req->isPost()) {
         $adapter = $this->authService->getAdapter();
         if ($adapter instanceof ValidatableAdapterInterface) {
             $adapter->setIdentity($req->getParam('identity'));
             $adapter->setCredential($req->getParam('credential'));
         }
         $result = $this->authService->authenticate($adapter);
         if (!$result->isValid()) {
             $this->flash->addMessage('danger', reset($result->getMessages()));
             return $res->withRedirect($req->getUri());
         }
         return $res->withRedirect($this->successUrl);
     }
     return $this->view->render($res, 'user/login.twig', []);
 }
Example #23
0
 /**
  * Authentificate user by username/password pair
  *
  * @param string $username
  * @param string $password
  * @param boolean $remember
  * @return \Zend\Authentication\Result
  * @throws \Exception
  */
 public function authentificate($username, $password, $remember = false)
 {
     $adapter = $this->authService->getAdapter();
     if (!$adapter instanceof \Zend\Authentication\Adapter\DbTable) {
         throw new \Exception('invalid auth adapter type');
     }
     $adapter->setIdentity($username)->setCredential($password);
     $result = $this->authService->authenticate();
     if ($result->getCode() == \Zend\Authentication\Result::SUCCESS) {
         if ($remember) {
             $this->sessionContainer->getManager()->rememberMe();
         }
         $this->sessionContainer->userEntity = (array) $adapter->getResultRowObject();
     } else {
         $this->sessionContainer->userEntity = null;
     }
     return $result;
 }
Example #24
0
 public function indexAction()
 {
     $viewModel = new ViewModel();
     $request = $this->getRequest();
     if (!$request->isPost()) {
         $this->layout('layout/login');
         return $viewModel;
     }
     $user = $this->identity();
     $messages = null;
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $sm = $this->getServiceLocator();
         $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
         $authAdapter = new AuthAdapter($dbAdapter, 'users', 'username', 'password', 'MD5(?) AND block = 1');
         $authAdapter->setIdentity($request->getPost('username'))->setCredential($request->getPost('password'));
         if (trim($request->getPost('username')) == "" || trim($request->getPost('password')) == "") {
             return $this->redirect()->toRoute('auth');
         }
         // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
         // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
         // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
         $result = $auth->authenticate($authAdapter);
         switch ($result->getCode()) {
             case Result::FAILURE_IDENTITY_NOT_FOUND:
                 // do stuff for nonexistent identity
                 break;
             case Result::FAILURE_CREDENTIAL_INVALID:
                 // do stuff for invalid credential
                 break;
             case Result::SUCCESS:
                 $storage = $auth->getStorage();
                 $storage->write($authAdapter->getResultRowObject(null, 'password'));
                 $time = 28800;
                 // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                 //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                 if ($request->getPost('username')) {
                     $sessionManager = new \Zend\Session\SessionManager();
                     $sessionManager->rememberMe($time);
                 }
                 return $this->redirect()->toRoute('home');
                 break;
             default:
                 // do stuff for other failure
                 break;
         }
         foreach ($result->getMessages() as $message) {
             $messages .= "{$message}\n";
         }
     }
     $this->layout('layout/login');
     return $viewModel;
 }
 /**
  * onAuthenticate
  *
  * Perform the authentication action and stop event propagation
  * if the result returned is a success.
  *
  * @param AuthenticationEvent $event  The authentication event.
  */
 public function onAuthentication(AuthenticationEvent $event)
 {
     $result = $this->auth->authenticate();
     if ($result instanceof AuthResult) {
         $event->setResult($result);
         if (AuthResult::SUCCESS === $result->getCode() && $result->getIdentity()) {
             $event->stopPropagation(true);
             return;
         }
     }
 }
 public function authenticate(AdapterInterface $adapter = null)
 {
     $profiles = $this->container->profiles;
     $result = parent::authenticate($adapter);
     if ($result->isValid()) {
         $this->getStorage()->write(true);
         $this->container->profiles = $profiles;
         $this->container->profiles[] = $result->getIdentity();
     }
     return $result;
 }
Example #27
0
 public function loginAction()
 {
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     // process the form
     $form = new LoginForm();
     $request = $this->getRequest();
     if ($this->getRequest()->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             // check if the user exists
             $sm = $this->getServiceLocator();
             $mapper = $sm->get('User\\Model\\UserMapper');
             $params = array('where' => 'username = "******"');
             $users = $mapper->select($params);
             if ($users) {
                 $user = $users[0];
                 /**
                  * If the account is not active, prompt the user to activate
                  * the account
                  */
                 if (!$user->getActive()) {
                     return $this->redirect()->toRoute('registration', array('action' => 'confirm', 'id' => $user->getId()));
                 }
                 // authenticate the user
                 $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
                 $adapter = new AuthAdapter($dbAdapter, 'user', 'username', 'password_hash');
                 $adapter->setIdentity($data['credential']);
                 $adapter->setCredential(hash('sha256', $user->getPassword_salt() . $data['password']));
                 $result = $auth->authenticate($adapter);
                 if ($result->isValid()) {
                     // store session information in database
                     $mapper = $sm->get('User\\Model\\SessionMapper');
                     $session = new Session(array('user_id' => $user->getId(), 'ip_address' => $_SERVER['REMOTE_ADDR'], 'login_timestamp' => date('Y-m-d H:i:s')));
                     $mapper->save($session);
                     // store user information in session variable
                     $container = new Container('user');
                     $container->user = $user->get_array();
                     return $this->redirect()->toRoute('home');
                 } else {
                     foreach ($result->getMessages() as $message) {
                         print "{$message}\n";
                     }
                 }
             } else {
                 print "Invalid username/email";
             }
         }
     }
     return new ViewModel(array('form' => $form));
 }
Example #28
0
 public function isAuthenticated($ident, $cred)
 {
     $auth = new AuthenticationService();
     $authAdapter = ServiceLocatorFactory::getInstance()->get('LoginAuthAdapter');
     $authAdapter->setIdentity($ident)->setCredential($cred);
     $this->authStatus = $auth->authenticate($authAdapter);
     if ($this->authStatus->isValid()) {
         return $this->authStatus;
     }
     return false;
 }
 public function loginAction()
 {
     $user = $this->identity();
     $form = new LoginForm();
     $messages = null;
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter(new LoginFilter($this->getServiceLocator()));
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password', "MD5(?)");
             $authAdapter->setIdentity($data['email'])->setCredential($data['password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'password'));
                     $user = $auth->getIdentity();
                     switch ($user->role_id) {
                         case 1:
                             return $this->redirect()->toRoute('admin');
                             break;
                         case 2:
                             return $this->redirect()->toRoute('teacher');
                             break;
                         case 3:
                             return $this->redirect()->toRoute('student');
                             break;
                         default:
                             return $this->redirect()->toRoute('home');
                             break;
                     }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         }
     }
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
 public function authenticate(Adapter\AdapterInterface $adapter = null)
 {
     $result = parent::authenticate($adapter);
     if ($result->isValid()) {
         // Set authentication indicator cookie
         $lifetime = (int) $this->sessionConfig->getCookieLifetime();
         $expires = $lifetime !== 0 ? time() + $lifetime : null;
         $lifetime = $lifetime !== 0 ? $lifetime : null;
         $this->setCookie(true, $expires, $lifetime);
     }
     return $result;
 }