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; }
/** * Ensure that exceptions are caught */ public function testCatchExceptionBadSql() { $this->setExpectedException('Zend\\Authentication\\Adapter\\Exception\\RuntimeException', 'The supplied parameters to'); $this->_adapter->setTableName('bad_table_name'); $this->_adapter->setIdentity('value'); $this->_adapter->setCredential('value'); $this->_adapter->authenticate(); }
public function getAdapter() { $adapter = new AuthAdapter($this->db, 'credentials_password', 'credentials_password.email', 'credentials_password.password'); $adapter->getDbSelect()->join('accounts', 'accounts.id = credentials_password.account'); $adapter->setIdentity($this->email); $adapter->setCredential($this->getHashedPassword()); return $adapter; }
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)); }
public function awakeSignIn() { $this->auth = new AuthenticationService(); $sm = $this->getApplicationServiceLocator(); $sm->setAllowOverride(true); $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter'); $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password'); $authAdapter->setIdentity('*****@*****.**'); $authAdapter->setCredential(md5('123')); $this->auth->authenticate($authAdapter); $this->assertTrue($this->auth->hasIdentity()); }
public function testSigninWithWrongCredentials() { $auth = new AuthenticationService(); $sm = $this->getApplicationServiceLocator(); $sm->setAllowOverride(true); $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter'); $messages = null; $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password'); $authAdapter->setIdentity('*****@*****.**'); $authAdapter->setCredential(md5('456')); $this->result = $auth->authenticate($authAdapter); foreach ($this->result->getMessages() as $message) { $messages .= "{$message}"; } $this->assertEquals($messages, 'Supplied credential is invalid.'); }
/** * Metodo para validar acceso al portal * @return \Zend\View\Model\ViewModel */ public function ingresoAction() { if ($this->getRequest()->isPost()) { $auth = new AuthenticationService(); $validate = $this->getRequest()->getPost(); $authAdapter = new AuthAdapter($this->adapter(), 'usuario', 'usuario_correo', 'usuario_password'); $authAdapter->setIdentity($validate['correo']); $authAdapter->setCredential(md5($validate['password'])); $resultado = $auth->authenticate($authAdapter); switch ($resultado->getCode()) { case Result::FAILURE_IDENTITY_NOT_FOUND: $this->message = "Usuario y/o contraseña incorrectos"; $this->flashMessenger()->addMessage($this->message); return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login'); case Result::FAILURE_CREDENTIAL_INVALID: $this->message = "Usuario y/o contraseña incorrectos"; $this->flashMessenger()->addMessage($this->message); return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login'); case Result::SUCCESS: $this->flashMessenger()->clearMessages(); $store = $auth->getStorage(); $store->write($authAdapter->getResultRowObject(null, 'usuario_password')); $sessionConfig = new StandardConfig(); $sessionConfig->setRememberMeSeconds(20)->setCookieLifetime(30)->setCookieSecure(true)->setGcMaxlifetime(60)->setGcDivisor(60); $sesionMa = new SessionManager($sessionConfig); $sesionMa->rememberMe(30); $container = new Container('cbol'); $container->setExpirationSeconds(1800); $sesionMa->start(); $container->idSession = $auth->getIdentity()->perfil_id; $permisos = $this->getPermisos($auth->getIdentity()->usuario_id); $container->permisosUser = $permisos; $indexProfile = \Login\IndexAllProfile::listIndexAllProfiles($auth->getIdentity()->perfil_id); if ($indexProfile == 'vias') { $container->reportesVias = $this->getReportesViales(); } if ($indexProfile == 'admin') { $container->sugerencias = $this->getSugerenciasAction(); } $container->setDefaultManager($sesionMa); return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . "/{$indexProfile}"); default: echo 'Mensaje por defecto'; break; } } }
public function loginAction() { $authStorage = new AuthenticationStorage(self::NAMESPACE_ZENDSTORE_FRONT); $authService = new AuthenticationService($authStorage); if ($authService->hasIdentity()) { echo 'You have logined'; exit; } $form = new UserForm(); $request = $this->getRequest(); if ($request->isPost()) { $user = new User(); $form->setInputFilter($user->getInputFilter()); $form->setData($request->post()); if ($form->isValid()) { $data = $form->getData(); // Authentication $sm = $this->getServiceLocator(); $db = $sm->get('db-adapter'); //$authAdapter = new AuthenticationAdapter($db, 'user', 'email', 'password', 'MD5(?)'); $authAdapter = new AuthenticationAdapter($db, 'user', 'email', 'password', 'MD5(CONCAT(?, password_salt))'); $authAdapter->setIdentity($data['email']); $authAdapter->setCredential($data['password']); $result = $authService->authenticate($authAdapter); if ($result->isValid()) { return $this->redirect()->toRoute('user-front-user'); } else { var_dump($result->getMessages()); exit; } } else { echo '<h1>ERROR: Form data is invalid.</h1>'; echo '<pre>'; print_r($form->getMessages()); exit; } } $viewVars = array('form' => $form); $viewModel = $this->getViewModel(); $viewModel->setVariables($viewVars); return $viewModel; }
public function userLogin($useremail, $password, $remember_me = 0) { $authAdapter = new AuthAdapter($this->getAdapter(), 'userlist', 'useremail', 'password', 'CONCAT(?,salt_key) and is_active=1 and is_delete=0'); $authAdapter->setIdentity(trim($useremail)); $authAdapter->setCredential(base64_encode(trim($password))); $auth = new AuthenticationService(); $result = $authAdapter->authenticate($authAdapter); if ($result->isValid()) { if ($remember_me == 1) { setcookie('discoveryCRMcookieEmail', $useremail, time() + 86400 * 365, "/"); setcookie('discoveryCRMcookiePswd', $password, time() + 86400 * 365, "/"); } else { setcookie('discoveryCRMcookieEmail', $useremail, time() - 86400, "/"); setcookie('discoveryCRMcookiePswd', $password, time() - 86400, "/"); } $data = $authAdapter->getResultRowObject(); $auth->getStorage()->write($data); $identity = $auth->getIdentity(); $this->getModel()->generateOTP(); return 1; } else { return 0; } }
function authenticate(Adapter $adapter) { /* * Criando o auth adapter: passando o primeiro parâmetro o * adaptador do banco de dados $zendDb segundo parâmetro a tabela de * usuarios terceiro parâmetro a coluna da tabela aonde está o login * quarto parâmetro a coluna da tabela aonde está a senha */ $bcrypt = new Bcrypt(); if ($bcrypt->verify($this->authPassword, $this->storedHash)) { $authAdapter = new DbTable($adapter, 'tb_user', 'email', 'password'); /* * Seta o credential tratment: tratamento da senha para ser * criptografada em md5 passado um parâmetro status para logar o * usuario que esteja ativo no sistema no caso dos parâmetros você * pode passar quantos forem necessários usando o AND na sequência * seta o Identity que é o login e Credential que é a senha */ $authAdapter->setCredentialTreatment('? AND status = 1'); $authAdapter->setIdentity($this->authEmail); $authAdapter->setCredential($this->storedHash); // Instanciando o AutenticationService para fazer a altenticação com // os dados passados para o authAdapter $authService = new AuthenticationService(); // Autenticando o passando para a variável result o resultado da // autenticação $result = $authService->authenticate($authAdapter); // Validando a autenticação if ($result->isValid()) { // Se validou damos um get nos dados autenticados usando o // $result->getIdentity() $identity = $result->getIdentity(); /* * Imprimindo os dados na tela para confirmar os dados * autenticados pronto, se aparecer os dados isso quer dizer que * o usuario está autenticado no sistema */ // var_dump ( $identity ); return true; } else { /* * Caso falhe a autenticação, será gerado o log abaixo que será * impresso na tela do computador para você sabe do * problema ocorrido. os erros listados abaixo são os erros mais * comuns que podem ocorrer. */ switch ($result->getCode()) { case Result::FAILURE_IDENTITY_NOT_FOUND: //echo "O email não existe"; break; case Result::FAILURE_CREDENTIAL_INVALID: //echo "A senha não confere"; break; default: foreach ($result->getMessages() as $message) { //echo $message; } } return false; } } else { //echo "A senha não confere"; return false; } }
public function signinAction() { $user = $this->identity(); $auth = new AuthenticationService(); if (!$auth->hasIdentity()) { $messages = null; $form = new SigninForm(); $request = $this->getRequest(); if ($request->isPost()) { $signinFormFilter = new SigninUserModel(); $form->setInputFilter($signinFormFilter->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'); $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password'); $authAdapter->setIdentity($data['email']); $authAdapter->setCredential(md5($data['password'])); $result = $auth->authenticate($authAdapter); switch ($result->getCode()) { case Result::FAILURE_IDENTITY_NOT_FOUND: break; case Result::FAILURE_CREDENTIAL_INVALID: break; case Result::SUCCESS: $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(null, 'password')); $time = 604800; //7 days if ($data['rememberme']) { $sessionManager = new \Zend\Session\SessionManager(); $sessionManager->rememberMe($time); } return $this->redirect()->toRoute('user', array('action' => 'index')); default: break; } foreach ($result->getMessages() as $message) { $messages .= "{$message}\n"; } } } return new ViewModel(array('form' => $form, 'messages' => $messages)); } else { return $this->redirect()->toRoute('user', array('action' => 'index')); } // $user_session = new \Zend\Session\Container('user'); // if ($user_session->email!=null) { // return $this->redirect()->toRoute('user',array('action'=>'index')); // } // $form = new SigninForm(); // $item = new SigninUserModel(); // $request = $this->getRequest(); // if ($request->isPost()) { // $form->setInputFilter($item->getInputFilter()); // $form->setData($request->getPost()); // if ($form->isValid()) { // $item->email = $form->get('email')->getValue(); // $item->password = $form->get('password')->getValue(); // $success = $this->getTable()->signin($item); // if ($success) { // $user_session = new \Zend\Session\Container('user'); // $user_session->email=$success->email; // $user_session->role=$success->role; // return $this->redirect()->toRoute('user'); // } else { // $error='Wrong email or password'; // } // } // } // // return array( // 'form'=>$form, // 'error'=>$error // ); }
/** * This action is called when a user is to be authenticated by their username and password * * @return \Zend\View\Model\ViewModel */ public function authenticateAction() { $Logform = new LoginForm(); //Gets the username $email = $this->request->getPost('email'); //Get the password and encrypt it using md5 $password = md5($this->request->getPost('password')); //Create a connection to the database $db = $this->getServiceLocator()->get('dbcon'); if ($this->request->isPost()) { //Perform a check to see if username and password are not empty if ($email != null and $password != null) { //Create an instance of the Auth Adapter $auth = new AuthAdapter($db); //Set the user name $auth->setIdentity($email); //Set the password $auth->setCredential($password); //Set the Table name $auth->setTableName('users'); //Set the user name colum $auth->setIdentityColumn('email'); //Set the password column $auth->setCredentialColumn('password'); //Authenticate the user $auth->authenticate(); //If authentication is valid if ($auth->authenticate()->isValid()) { //Convert the user credentials from an object into an array $array = get_object_vars($auth->getResultRowObject()); //Set the username and store it in session $this->session->offsetSet('email', $array['email']); $this->session->offsetSet('username', $array['username']); //Set the user id and store in session $this->session->offsetSet('id', $array['id']); //Set the user full name and store in session $this->session->offsetSet('fullname', $array['full_name']); $this->AuthenticationLogger("user logged in successfully at " . date('y-m-d H:i:s')); $this->ActivityLogs("user logged in successfully at " . date('Y-m-d H:i:s')); //Redirect the user to the admin page $this->getUrl('ekontact', 'Ekontact', 'dashboard'); } else { $msg = $this->flashMessenger()->addMessage(sprintf(" %s Invalid email or password %s", '<div class="error">', '</div>')); return $this->redirect()->toRoute('authentication', array('controller' => 'Authentication', 'action' => 'login')); } } else { $msg = $this->flashMessenger()->addMessage(sprintf(" %s Please make sure both email and password fields are not empty %s", '<div class="error">', '</div>')); $this->getUrl('authentication', 'Authentication', 'login'); } } $view = new ViewModel(array('form' => $Logform)); $this->layout('layout/login_layout'); return $view; }