/** * * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed * @return Zend_Auth_Result * @see Zend_Auth_Adapter_Interface::authenticate() */ public function authenticate() { $result = array('code' => Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, 'identity' => null, 'messages' => array()); /** @var Zend_Config */ $config = Zend_Registry::get('config'); if (isset($config['admin']['pass']) && $this->_data['code'] == $config['admin']['pass'] && $this->_data['email'] == 'admin') { $result['code'] = Zend_Auth_Result::SUCCESS; $result['identity'] = new Reg2_Model_Identity('admin'); Zend_Registry::get('log')->info('Admin login from ' . $_SERVER['REMOTE_ADDR']); return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']); } $this->_dbauth->setIdentity($this->_data['email'])->setCredential($this->_data['code']); $dbresult = $this->_dbauth->authenticate(); if ($dbresult->isValid()) { $result['code'] = Zend_Auth_Result::SUCCESS; $user = $this->_dbauth->getResultRowObject(); $result['identity'] = new Reg2_Model_Identity($user->role, $user); Zend_Registry::get('log')->info(sprintf("Login with '%s' as '%s'(%d) from %s", $this->_data['email'], $user->role, $user->tid, $_SERVER['REMOTE_ADDR'])); } else { $result['code'] = $dbresult->getCode(); $result['messages'] = $dbresult->getMessages(); Zend_Registry::get('log')->info(sprintf("Login attempt: %d from %s", $dbresult->getCode(), $_SERVER['REMOTE_ADDR'])); } return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']); }
/** * Login function authentication system * @param Zend_Db_Table_Row $account * @return boolean */ function Login(Zend_Db_Table_Row $account) { $select = $this->select()->where('email=?', $account->email)->limit(1); $row = $this->fetchRow($select); // set up the auth adapter $db = Acl_Model_Account::getDefaultAdapter(); $authAdapter = new OS_Application_Adapter_Auth($account->email, $account->password); $authAdapter = new Zend_Auth_Adapter_DbTable($db); $authAdapter->setTableName($this->_name)->setIdentityColumn('email')->setCredentialColumn('password')->setCredentialTreatment('block = 0'); #->setCredentialTreatment('MD5(?) and block = 0'); $authAdapter->setIdentity($account->email); $authAdapter->setCredential(crypt($account->password, $row->password)); $result = $authAdapter->authenticate(); Zend_Session::regenerateId(); if ($result->isValid()) { $auth = Zend_Auth::getInstance(); $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(array('id', 'email', 'registerdate', 'lastvisitdate', 'role_id', 'fullname', 'email_alternative'))); $account = $this->find($authAdapter->getResultRowObject()->id)->current(); #$account = $this->createRow( $account->toArray() ); $account->lastvisitdate = Zend_Date::now()->toString('YYYY-MM-dd HH:mm:ss'); $account->save(); return true; } return false; }
public function login($email, $senha) { if ($this->validaLogin($email, $senha)) { $data = $this->auth->getResultRowObject(null); Zend_Auth::getInstance()->getStorage()->write($data); return 1; } else { return 0; } }
public function isValid($value, $context = null) { $value = (string) $value; $this->_setValue($value); $this->_authAdapter->setIdentity($context[$this->_identityElement]); $this->_authAdapter->setCredential($value); $result = Zend_Auth::getInstance()->authenticate($this->_authAdapter); if ($result->isValid()) { Zend_Auth::getInstance()->getStorage()->write($this->_authAdapter->getResultRowObject(null, 'pwd')); return true; } $this->_error(self::LOGIN_FAILS); return false; }
public function login() { if ($this->_router->isPostRequest()) { if ($_POST['login'] != '' && $_POST['passwd'] != '') { $db = Zend_Db_Table::getDefaultAdapter(); // tworzymy instancję adaptera autoryzacji $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'cms_user', 'user_login', 'user_passwd'); $authAdapter->setIdentity($_POST['login']); $authAdapter->setCredential(sha1($_POST['passwd'])); // sprawdzamy, czy użytkownik jest aktywny $authAdapter->setCredentialTreatment("? AND user_active = '1'"); // autoryzacja $result = $authAdapter->authenticate(); if ($result->isValid()) { $user_data = $authAdapter->getResultRowObject(); /* zapisanie roli zalogowanego uzytkownika */ $this->_roles = RolesModel::Instance(); $role = $this->_roles->getRoleData($user_data->role_id); $user_data->role_code = $role['role_code']; $this->_storage->write($user_data); // ustawienie ACL dla użytkownika $this->_engine->addHttpHeader("Location: /" . $this->_router->getUrl('cms', 'index')); } else { $this->_view->error = '1'; } } else { $this->_view->error = '1'; } } $this->_engine->setToRender('login.tpl'); }
/** * IS: Parameter username, password, remember terdeklarasi * FS: Mengirimkan ke viewer: fail, * Session berisi data userId dan username * Desc: Fungsi untuk login biasa */ public function indexAction() { $this->_helper->viewRenderer->setNoRender(true); // Jika request ajax //if ($this->_request->isXmlHttpRequest()) { // Tidak menggunakan layout dan view $this->_helper->layout()->disableLayout(); $loginForm = new Form_LoginForm(); if ($this->getRequest()->isPost() and $loginForm->isValid($this->getRequest()->getPost())) { // Param $username = $this->_getParam('username'); $password = $this->_getParam('password'); $remember = $this->_getParam('remember'); // Menggunakan auth adapter bawaan Zend $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, "user", 'username', 'password'); // Set username dan password $authAdapter->setIdentity($username); $authAdapter->setCredential(md5($password)); // Authentikasi $result = $authAdapter->authenticate(); // Jika ada if ($result->isValid()) { // Menggunakan auth adapter bawaan Zend $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, "user", 'username', 'password', 'activationkey'); // Set username dan password $authAdapter->setIdentity($username); $authAdapter->setCredential(md5($password)); // Authentikasi $result = $authAdapter->authenticate(); $auth = Zend_Auth::getInstance(); $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(array('user_id', 'username', 'activationkey'))); $identity = $auth->getIdentity(); if ($this->_hasParam('remember')) { $expire = time() + 1728000; // 20 hari expired $cookiePass = sha1(md5($password) . $identity->activationkey); setcookie('budpar_userId', $identity->user_id, $expire, '/'); setcookie('budpar_user', $identity->username, $expire, '/'); setcookie('budpar_pass', $cookiePass, $expire, '/'); } // Set Blacklist jika ada $this->_setBlacklist($identity->user_id); // Set nilai session $this->_sess->userId = $identity->user_id; $this->_sess->username = $identity->username; //echo 'success'; } else { echo 'fail'; $this->view->fail = true; $this->_sess->error = true; } } else { echo 'fail'; $this->view->fail = true; } $this->_redirector->gotoUrl($this->_sess->previousUri); }
public function loginAction() { $this->_helper->layout->disablelayout(); $authorization = Zend_Auth::getInstance(); $identity = $authorization->getIdentity(); if ($authorization->hasIdentity()) { $this->redirect("categories/list"); } if ($this->getRequest()->isPost()) { $data = $this->getRequest()->getParams(); $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'users', 'username', 'password'); $authAdapter->setIdentity($data['username']); $authAdapter->setCredential(md5($data['password'])); $result = $authAdapter->authenticate(); if ($result->isValid()) { $active = (new Application_Model_Users())->getUserByUsername($data['username'])[0]['active']; if ($active) { $auth = Zend_Auth::getInstance(); $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(array('f_name', 'username', 'id', 'user_type'))); $authorization = Zend_Auth::getInstance(); $identity = $authorization->getIdentity(); $this->view->identity = $identity; $this->redirect('categories/list'); } else { $this->view->user_msg = "The page not allowed for normal user."; $this->redirect("users/login"); } } } $form = new Application_Form_Login(); $this->view->form = $form; }
public function loginAction() { //Desabilita renderização da view $this->_helper->viewRenderer->setNoRender(); //Obter o objeto do adaptador para autenticar usando banco de dados $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); //Seta qual tabela e colunas procurar o usuário $authAdapter->setTableName('usuario')->setIdentityColumn('login')->setCredentialColumn('senha'); //Seta as credenciais com dados vindos do formulário de login $authAdapter->setIdentity($this->_getParam('login'))->setCredential($this->_getParam('senha'))->setCredentialTreatment('MD5(?)'); //Realiza autenticação $result = $authAdapter->authenticate(); //Verifica se a autenticação foi válida if ($result->isValid()) { //Obtém dados do usuário $usuario = $authAdapter->getResultRowObject(); //Armazena seus dados na sessão $storage = Zend_Auth::getInstance()->getStorage(); $storage->write($usuario); //Redireciona para o Index $this->_redirect('index'); } else { $this->_redirect('autenticacao/falha'); } }
public static function authenticate(array $values) { $email = isset($values['email']) ? $values['email'] : null; $senha = isset($values['senha']) ? $values['senha'] : null; if (!count($values)) { throw new Exception('Não foi passado valores para autenticar'); } // Pegar os dados da autenticacao e checa $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('usuario')->setIdentityColumn('email')->setCredentialColumn('senha'); $authAdapter->setIdentity($email)->setCredential($senha)->setCredentialTreatment('MD5(?)'); $select = $authAdapter->getDbSelect(); $select->join(array('g' => 'grupo'), 'g.id = usuario.grupo_id', array('grupo' => 'nome')); //Realiza autenticação $result = $authAdapter->authenticate(); //Verifica se a autenticação foi válida if ($result->isValid()) { //Obtém dados do usuário $usuario = $authAdapter->getResultRowObject(); //Armazena seus dados na sessão $storage = Zend_Auth::getInstance()->getStorage(); $storage->write($usuario); //Redireciona para o Index return true; } return false; }
public function indexAction() { $filter = new Zend_Filter_StripTags(); $login = trim($filter->filter($this->_request->getPost('login'))); $senha = trim($filter->filter($this->_request->getPost('senha'))); $uri = str_replace('kahina/', '', base64_decode($this->_request->getParam('u', base64_encode('painel/index')))); if (empty($login) || empty($senha)) { $this->view->message = 'Por favor, informe seu Usuário e Senha.'; return; } else { $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('login')->setIdentityColumn('login')->setCredentialColumn('senha'); $authAdapter->setIdentity($this->_getParam('login'))->setCredential($this->_getParam('senha'))->setCredentialTreatment('MD5(?)'); $result = $authAdapter->authenticate(); if ($result->isValid()) { $user = $authAdapter->getResultRowObject(); $storage = My_Auth::getInstance('Painel')->getStorage(); $storage->write($user); $this->_redirect($uri); } else { $this->view->error = 'Você deve informar Login e Senha.'; } } $this->render(); }
/** * */ public function logarAction() { $resposta = array(); $this->_helper->viewRenderer->setNoRender(true); $this->_helper->layout()->disableLayout(); $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('sca_usuario')->setIdentityColumn('login_usuario')->setCredentialColumn('password_usuario'); $authAdapter->setIdentity($this->getRequest()->getParam('login_usuario'))->setCredential($this->getRequest()->getParam('password_usuario'))->setCredentialTreatment('MD5(?) and st_usuario = 1'); //Realiza autenticacao $result = $authAdapter->authenticate(); //Verifica se a autenticacao foi validada if ($result->isValid()) { //obtem os dados do usuario $usuario = $authAdapter->getResultRowObject(); //Armazena seus dados na sessao $storage = Zend_Auth::getInstance()->getStorage(); $storage->write($usuario); //Redireciona para o Index $resposta['situacao'] = "sucess"; $resposta['msg'] = "Logando aguarde..."; } else { $resposta['situacao'] = "error"; $resposta['msg'] = "Usuário inativo ou senha incorreta, favor contate ao administrador."; } echo json_encode($resposta); }
public function loginAction() { $userForm = new Form_LoginForm(); $userForm->setAction('/auth/login'); if ($this->_request->isPost() && $userForm->isValid($_POST)) { $data = $userForm->getValues(); $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'utils', 'username', 'source'); $authAdapter->setIdentity($data['username']); $authAdapter->setCredential($data['password']); $result = $authAdapter->authenticate(); if ($result->isValid()) { $auth = Zend_Auth::getInstance(); $data1 = $authAdapter->getResultRowObject(null, 'source'); // $auth->getStorage()->write($data1); // $auth->getStorage()->write($data); $dom = $auth->getIdentity()->domainadmin; $host = $auth->getIdentity()->hostadmin; $mySession = SessionWrapper::getInstance(); $mySession->setSessVar('username', $formData['username']); date_default_timezone_set('Europe/Brussels'); echo 'valid'; } else { $this->view->loginMessage = "Sorry, your username or password was incorrect"; } } $this->view->form = $userForm; }
public function indexAction() { $form = new Application_Form_Login(); $form->setAction('/auth'); if ($this->_request->isPost()) { $formData = $this->_request->getPost(); if ($form->isValid($formData)) { $auth = Zend_Auth::getInstance(); $db = Zend_Registry::get('db'); $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'users', 'username', 'password'); $authAdapter->setIdentity($formData['username']); $authAdapter->setCredential($formData['password']); $result = $authAdapter->authenticate(); $session = Zend_Registry::get('session'); switch ($result->getCode()) { case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: $session->erro = 'senha'; $form->populate($formData); break; case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND: $session->erro = 'Usuario Inválido'; $form->populate($formData); break; case Zend_Auth_Result::SUCCESS: $data = $authAdapter->getResultRowObject(); $session->role = $data->role; $this->_redirect('/post/retrieve'); break; } } else { $form->populate($formData); } } $this->view->form = $form; }
public function logarAction() { $this->_helper->viewRenderer->setNoRender(true); $this->_helper->layout()->disableLayout(); $resposta = array(); $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('sca_usuario')->setIdentityColumn('login_usuario')->setCredentialColumn('password_usuario')->getDbSelect()->join(array('g' => 'sca_grupo'), 'g.id_grupo = sca_usuario.id_grupo', array('nm_grupo', 'is_root')); $authAdapter->setIdentity($this->getRequest()->getParam('login_usuario'))->setCredential($this->getRequest()->getParam('password_usuario'))->setCredentialTreatment('MD5(?) and st_usuario = 1'); //Realiza autenticacao $result = $authAdapter->authenticate(); //Verifica se a autenticacao foi validada if ($result->isValid()) { //obtem os dados do usuario $usuario = $authAdapter->getResultRowObject(); //Armazena seus dados na sessao $storage = Zend_Auth::getInstance()->getStorage(); $storage->write($usuario); // se não for para lembrar os dados expira a sessao em 30 minutos if (!$this->getRequest()->getParam('lembrar')) { $session = new Zend_Session_Namespace('Zend_Auth'); $session->setExpirationSeconds(1800); } //Redireciona para o Index $resposta['situacao'] = "success"; $resposta['msg'] = "Logando aguarde..."; } else { $resposta['situacao'] = "error"; $resposta['msg'] = "Usuário inativo ou senha incorreta."; } echo json_encode($resposta); }
/** * Ensure that ResultRowObject returns an object has specific omissions * */ public function testGetOmittedResultRow() { $this->_adapter->setIdentity('my_username'); $this->_adapter->setCredential('my_password'); $result = $this->_adapter->authenticate(); $resultRow = $this->_adapter->getResultRowObject(null, 'password'); $this->assertEquals('O:8:"stdClass":3:{s:2:"id";s:1:"1";s:8:"username";s:11:"my_username";s:9:"real_name";s:12:"My Real Name";}', serialize($resultRow)); }
public function getResultRowObject($returnColumns = null, $omitColumns = null) { if ($returnColumns || $omitColumns) { return parent::getResultRowObject($returnColumns, $omitColumns); } else { $omitColumns = array('password'); return parent::getResultRowObject($returnColumns, $omitColumns); } }
public function loginAction() { $auth = Zend_Auth::getInstance(); $this->_layout->setLayout('admin_login'); $this->view->message = $this->_flashMessenger->getMessages(); $form = new Admin_Form_LoginForm(); $form->setMethod('post')->setAction($this->view->rootUrl('/admin/index/login')); $this->view->form = $form; $flashMessenger = $this->_helper->getHelper('FlashMessenger'); if ($this->getRequest()->isPost()) { $username = $this->_getParam('username'); $password = md5($this->_getParam('password')); if (empty($username) || empty($password)) { $flashMessenger->addMessage('Field Cannot Empty'); } else { $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'admin_account', 'username', 'password'); $authAdapter->setIdentity($username); $authAdapter->setCredential($password); $result = $authAdapter->authenticate(); if ($result->isValid()) { $auth = Zend_Auth::getInstance(); $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(array('admin_id', 'username', 'email', 'role_id'))); $identity = $auth->getIdentity(); //set auth session expired $auth_sess = new Zend_Session_Namespace($auth->getStorage()->getNamespace()); $auth_sess->setExpirationSeconds(strtotime('30 day', 0)); //store user information on session Zend_Session::namespaceUnset('userInfo'); $userInfo = new Zend_Session_Namespace('userInfo'); $userInfo->id = $identity->admin_id; $userInfo->name = $identity->username; $userInfo->email = $identity->email; $userInfo->role_id = $identity->role_id; //set user allowed module list $table_adminAccount = new Model_DbTable_AdminAccount(); $module_list = $table_adminAccount->getUserInformation($identity->admin_id); $userInfo->module_list = explode(',', $module_list['allowed_module']); $userInfo->canApprove = in_array(47, $userInfo->module_list); //get module list from the database Zend_Session::namespaceUnset('moduleList'); $moduleList = new Zend_Session_Namespace('moduleList'); $table_module = new Model_DbTable_AdminModule(); $module = $table_module->getAllModuleId(); $moduleList->module = $module; //redirecting to the dashboard $this->_redirect($this->view->rootUrl('/admin/index')); } else { $flashMessenger->addMessage('Login Failed'); } } } }
/** * Authentication method * * @return Zend_Auth_Result * @todo Db Col in code, use something like Admin_Model_DbRow_User, but this needs * to be rewritten to be in the App_ namespace */ public function authenticate() { $user = $this->adapter->request->getParam('username'); $pass = $this->adapter->request->getParam('passwort'); $salt = Zend_Registry::get('password_salt'); $internalAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter(), 'user_users', 'uu_username', 'uu_passwort', 'MD5(CONCAT(?, "' . $salt . '"))'); $result = $internalAdapter->setIdentity($user)->setCredential($pass)->authenticate(); if ($result->isValid()) { $this->adapter->getUser()->update((array) $internalAdapter->getResultRowObject()); } return new Zend_Auth_Result($result->getCode(), $this->adapter->getUser(), $result->getMessages()); }
/** * Un membre est authentifiable via sa propre table * Elle comporte donc aussi des colonnes 'nom' et 'password' * * @var int $sessionDuration durée de vie de la persistance * @return Zend_Auth_Result */ public function authenticate($sessionDuration = 7200) { $dba = Zend_Registry::get('dba'); $auth = new Zend_Auth_Adapter_DbTable($dba, "MEMBRE", "LOGIN", "PASSWORD", "MD5(?)"); $auth->setIdentity($this->LOGIN)->setCredential($this->PASSWORD); $result = $auth->authenticate(); if ($result->isValid()) { $this->setFromArray((array) $auth->getResultRowObject()); $session = new Zend_Session_Namespace('Zend_Auth'); $session->setExpirationSeconds(abs((int) $sessionDuration)); Zend_Auth::getInstance()->getStorage()->write($this); } return $result; }
public function authentificateAction() { if (!$this->getRequest()->isPost()) { return $this->_forward('index'); } $form = $this->getForm(); if (!$form->isValid($_POST)) { $this->view->form = $form; return $this->render('index'); } else { $values = $form->getValues(); $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('database')); $authAdapter->setTableName('users'); $authAdapter->setIdentityColumn('Login'); $authAdapter->setCredentialColumn('Password'); $authAdapter->setIdentity($values['Login']); $authAdapter->setCredential($values['Password']); $select = $authAdapter->getDbSelect(); $select->where('Active = 1'); if ($authAdapter->authenticate()->getCode() == Zend_Auth_Result::SUCCESS) { $databaseTable = $authAdapter->getResultRowObject(); Zend_Registry::get('database')->query('UPDATE users SET LastConnection = NOW() WHERE Id = "' . $databaseTable->Id . '"'); $session = $this->session; if (isset($_COOKIE['PreviousCategory'])) { $table = new Categories(); $row = $table->find($_COOKIE['PreviousCategory'])->current(); if (isset($row->Id)) { $session->category = $row->Id; $session->categoryName = $row->Name; } } $session->access = true; $session->id = $databaseTable->Id; $session->lastName = $databaseTable->LastName; $session->firstName = $databaseTable->FirstName; $session->rights = new UsersRights($databaseTable->Status); $this->view->access = true; $this->_forward('home'); } else { $this->view->message = '<div class="error">Identification incorrect : mauvais nom d\'utilisateur et/ou mot de passe.</div>'; $this->view->form = $form; return $this->render('index'); } } }
/** * authenticates user against database * @param $username (string) username * @param $password (string) md5'd password string * @param $sessionName (string)session namespace identifier * @return User */ public function authUser($username, $password, $sessionName = 'userSessionName') { $auth = Zend_Auth::getInstance(); $auth->setStorage(new Zend_Auth_Storage_Session($sessionName)); $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter(), 'users', 'username', 'password'); $authAdapter->setTableName('users'); $authAdapter->setIdentityColumn('username'); $authAdapter->setCredentialColumn('password'); $authAdapter->setIdentity($username); $authAdapter->setCredential($password); $result = $authAdapter->authenticate(); if ($result->isValid()) { $userData = (array) $authAdapter->getResultRowObject(); } else { $userData = $this->find(1)->current()->toArray(); } $auth->getStorage()->write($userData); return $this->recreateUserSession($sessionName); }
public function processAction() { $request = $this->getRequest(); // Vérifie que nous avons bien à faire à une requête POST if (!$request->isPost()) { $this->_redirect('login/index'); } // Récupérons le formulaire et validons le $form = $this->getForm(); if (!$form->isValid($request->getPost())) { // Entrées invalides $this->view->form = $form; return $this->render('index'); // rechargeons le formulaire } $vals = $form->getValues(); $login = $vals['username']; $password = substr(crypt($vals['password'], '$6$$'), 4); // initialisation de la connection $dbAdapter = new Zend_Db_Adapter_Pdo_Sqlite(array('dbname' => 'logins')); // Configure une instance avec des méthodes de réglage $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('logins')->setIdentityColumn('login')->setCredentialColumn('password')->setIdentity($login)->setCredential($password); // check du login/password $authAuthenticate = $authAdapter->authenticate(); if ($authAuthenticate->isValid()) { $storage = Zend_Auth::getInstance()->getStorage(); $storage->write($authAdapter->getResultRowObject(null, 'password')); $auth = Zend_Auth::getInstance(); $auth->getIdentity()->username = $login; if ($login === "connexion_bdd") { $this->_redirect("bdd"); } $this->_redirect('livreor/suppression'); } else { // Identifiants invalides $form->setDescription('Le login ou le mot de passe est incorrect.'); $this->view->form = $form; return $this->render('index'); // rechargeons le formulaire } }
/** * Faz o login caso o email e senha estejam corretos * @param string $email * @param string $password * @return boolean */ public function login($email, $password) { $this->logout(); $db = Zend_Db_Table::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'usuario', 'email', 'senha', 'md5(?)'); //$email = $db->quote($email, 'string'); //$password = $db->quote($password, 'string'); $authAdapter->setIdentity($email)->setCredential($password); $result = $authAdapter->authenticate(); if ($result->isValid()) { $oIdentify = $authAdapter->getResultRowObject(null, 'senha'); // @FIXME Gravar registros em cache $codigoPerfil = Perfil::build()->find($oIdentify->perfil_id)->current()->codigo; $oIdentify->sRole = $codigoPerfil; $auth = Zend_Auth::getInstance(); $auth->getStorage()->write($oIdentify); return true; } return false; }
public function loggInn(AmfBruker $bruker) { $autentisering = new Zend_Auth_Adapter_DbTable($this->database); $autentisering->setTableName('ad_bruker')->setIdentityColumn('epost')->setCredentialColumn('passord'); $epost = htmlspecialchars($bruker->epost); $pass = sha1(htmlspecialchars($bruker->passord)); if ($epost == "") { return "FEIL_BRUKERNAVN_PASSORD"; } else { $autentisering->setIdentity($epost)->setCredential($pass); } $resultat = $autentisering->authenticate(); switch ($resultat->getCode()) { case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND: return "FEIL_BRUKERNAVN_PASSORD"; break; case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: return "FEIL_BRUKERNAVN_PASSORD"; break; case Zend_Auth_Result::FAILURE: return null; break; case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS: return null; break; case Zend_Auth_Result::FAILURE_UNCATEGORIZED: return null; break; case Zend_Auth_Result::SUCCESS: $r = $autentisering->getResultRowObject(); $bruker->epost = $r->epost; $bruker->fornavn = $r->fornavn; $bruker->etternavn = $r->etternavn; $bruker->superadmin = $r->superadmin; return $bruker; break; default: return "Noe skjedde feil! Hvis problemet vedvarer ta kontakt"; break; } }
/** * The default action - show the home page */ public function loginAction() { //debug(oi,1); /* Usa o layout proprio do sistenma quando o usuario estiver logado */ //$this->_helper->layout->setLayout('login'); $this->_helper->layout->DisableLayout(); /* Verifica se o formulario de login foi submetido */ if ($this->getRequest()->isPost()) { /* Preenche o array com o post e salva */ $arrDataForm = $this->getRequest()->getParam('arrDataForm'); //debug($arrDataForm,1); if (empty($arrDataForm['ds_login'])) { $this->_redirect("/auth/login"); } /* Configura o zend auth adapter dbtable para autenticacao */ $objAuthAdapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('db'), 'usuario', 'ds_login', 'ds_senha', 'md5(?)'); $objAuthAdapter->setIdentity($arrDataForm['ds_login'])->setCredential($arrDataForm['ds_senha']); $objResult = $objAuthAdapter->authenticate(); if ($objResult->isValid()) { $objAuth = Zend_Auth::getInstance(); $objUser = $objAuthAdapter->getResultRowObject(array('id_usuario', 'ds_login', 'ds_senha'), 'ds_senha'); $objAuth->getStorage()->write($objUser); //povoado sessao para a intranet $user = new Zend_Session_Namespace('user'); $user->id_usuario = $objAuth->getIdentity()->id_usuario; //povoado sessao para a intranet $usuario = new Zend_Session_Namespace('usuario'); $usuario->id = $objAuth->getIdentity()->id_usuario; $usuario->ds_login = $objAuth->getIdentity()->ds_login; //redireciono para a index //$this->_redirect( "/index" ); $this->_redirect("/gerenciador/listarmidia"); } else { $this->_redirect("/auth/login"); } } }
public function loginAction() { $formLogin = new Form_User(); $formLogin->removeElement('sex'); $formLogin->removeElement('email'); $formLogin->removeElement('password2'); $formLogin->removeElement('avatar'); $formLogin->removeElement('status'); $formLogin->removeElement('role'); $formLogin->removeElement('profile'); if ($this->getRequest()->isPost()) { if ($formLogin->isValid($_POST)) { $data = $formLogin->getValues(); //取得默认的数据库适配器 $db = Zend_Db_Table::getDefaultAdapter(); //实例化一个Auth适配器 $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'core_users', 'username', 'password'); //设置认证用户名和密码 $authAdapter->setIdentity($data['username']); $authAdapter->setCredential(md5($data['password'])); $result = $authAdapter->authenticate(); if ($result->isValid()) { $auth = Zend_Auth::getInstance(); //存储用户信息 $storage = $auth->getStorage(); $storage->write($authAdapter->getResultRowObject(array('id', 'username', 'role'))); $id = $auth->getIdentity()->id; $modelUser = new User(); $loginTime = $modelUser->loginTime($id); return $this->_redirect('/user/account/id/' . $id); } else { $this->view->loginMessage = '你的帐户名或密码不符'; } } } $this->view->formLogin = $formLogin; }
public function indexAction() { Zend_Loader::loadClass('Zend_Auth'); $authClass = Zend_Auth::getInstance(); $auth = $authClass->getStorage()->read(); if (!$authClass->hasIdentity()) { if ($this->_request->isPost()) { $data = $this->_request->getPost(); if ($data['usuario']) { $zendDb = Zend_Db_Table_Abstract::getDefaultAdapter(); $authAdapter = new Zend_Auth_Adapter_DbTable($zendDb, 'usuario', 'usuario', 'senha', 'MD5(?)'); $authAdapter->setIdentity($data['usuario']); $authAdapter->setCredential($data['senha']); $auth = $authAdapter->authenticate(); if ($auth->isValid()) { $authData = $authAdapter->getResultRowObject(); $authClass->getStorage()->write(array('usuario_id' => $authData->idusuario)); $user = $data['usuario']; $usuarioModel = new Application_Model_Usuario(); $row = $usuarioModel->fetchRow($usuarioModel->select()->where('usuario = ?', $user)); if ($row->tipo == 'administrador') { return $this->_helper->redirector('index', 'admin'); } else { if ($row->completo == 0) { return $this->_helper->redirector('index', 'cliente'); } else { return $this->_helper->redirector('index', 'index'); } } } else { $this->view->priorityMessenger('Login inválido!', 'Mensagem'); } } } } return $this->_helper->redirector('index', 'index'); }
/** * Implements {@link iPMS_Widget_Interface::widget()} * * @param Zend_Controller_Request_Http $request * @return Zend_Form|null A Zend_Form instance or null if user is already authenticated */ public function widget(Zend_Controller_Request_Http $request) { $auh = Zend_Auth::getInstance(); if (!$auh->hasIdentity()) { $form = $this->getForm('loginForm'); if ($request->isPost() && is_array($request->getPost('loginForm')) && $form->isValid($request->getPost('loginForm'))) { $authDbAdapter = new Zend_Auth_Adapter_DbTable(null, 'users', 'username', 'password', 'MD5(?) AND active = 1'); $authDbAdapter->setIdentity($form->getValue('username'))->setCredential($form->getValue('password')); $result = $authDbAdapter->authenticate(); if ($result->isValid()) { $auh->getStorage()->write($authDbAdapter->getResultRowObject(null, 'password')); Zend_Session::regenerateId(); // Protection against session's fixation attacks /** * @var $redirector Zend_Controller_Action_Helper_Redirector */ $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $redirector->gotoUrl('/'); } } return $form; } return null; }
/** * Logs an user in the application based on his * username and email * * @param string $username * @param string $password * @param boolean $remember * @access public * @return void */ public function login($username, $password, $remember = FALSE) { // adapter cfg $adapter = new Zend_Auth_Adapter_DbTable($this->_db); $adapter->setTableName($this->_name); $adapter->setIdentityColumn('username'); $adapter->setCredentialColumn('password'); // checking credentials $adapter->setIdentity($username); $adapter->setCredential(BaseUser::hashPassword($password)); try { $result = $adapter->authenticate(); } catch (Zend_Auth_Adapter_Exception $e) { App_Logger::log(sprintf("Exception catched while login: %s", $e->getMessage()), Zend_Log::ERR); return FALSE; } if ($result->isValid()) { // get the user row $loggedUser = $adapter->getResultRowObject(NULL, 'password'); //Check if the account has been closed if ($loggedUser->deleted) { return NULL; } // clear the existing data $auth = Zend_Auth::getInstance(); $auth->clearIdentity(); if (!empty($loggedUser->id)) { switch (CURRENT_MODULE) { case 'frontend': $userModel = new User(); $user = $userModel->findById($loggedUser->id); $user->get('group'); $session = new stdClass(); foreach (get_object_vars($loggedUser) as $k => $v) { $session->{$k} = $v; } $session->group->name = $user->get('group')->name; break; case 'backoffice': $userModel = new BackofficeUser(); $user = $userModel->findById($loggedUser->id); $user->groups = $user->findManyToManyRowset('Group', 'BackofficeUserGroup'); $user->group = $user->groups[0]; $session = new stdClass(); foreach (get_object_vars($loggedUser) as $k => $v) { $session->{$k} = $v; } $session->group->name = $user->group->name; break; } $auth->getStorage()->write($session); } $this->update(array('last_login' => new Zend_Db_Expr('NOW()')), $this->_db->quoteInto('id = ?', $user->id)); if ($rememberMe) { Zend_Session::rememberMe(App_DI_Container::get('ConfigObject')->session->remember_me->lifetime); } else { Zend_Session::forgetMe(); } return TRUE; } else { return FALSE; } }
public function loginAction() { //if the user is logged already redir to home $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $this->_redirect('/' . $this->lang . '/woeid/' . $this->location . '/give'); } $request = $this->getRequest(); $form = $this->_getUserLoginForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($request->getPost())) { $f = new Zend_Filter_StripTags(); $email = $f->filter($this->_request->getPost('email')); $password = $f->filter($this->_request->getPost('password')); //DDBB validation // setup Zend_Auth adapter for a database table $readConf = new Zend_Config_Ini(APPLICATION_PATH . '/config/nolotiro.ini', 'production'); $dbAdapter = Zend_Db::factory($readConf->resources->db); $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter); $authAdapter->setTableName('users'); $authAdapter->setIdentityColumn('email'); $authAdapter->setCredentialColumn('password'); // Set the input credential values to authenticate against $authAdapter->setIdentity($email); $authAdapter->setCredential(md5(trim($password))); //trim whitespaces from copy&pasting the pass from email // do the authentication $auth = Zend_Auth::getInstance(); //check first if the user is activated (by confirmed email) $select = $authAdapter->getDbSelect(); $select->where('active > 0'); //check if the user is not locked (spammers, bad users, etc) $select->where('locked = 0'); $result = $authAdapter->authenticate(); if ($result->isValid()) { // success: store database row to auth's storage // system. (Not the password though!) $data = $authAdapter->getResultRowObject(null, 'password'); $auth->getStorage()->write($data); $woeid = $this->_helper->CheckWoeidUser->checkUserLogged($auth->getIdentity()->id); $this->_helper->_flashMessenger->addMessage($this->view->translate('Welcome,') . ' ' . $auth->getIdentity()->username); Zend_Session::start(); //check if user wants to be remembered by 7 days $seconds = 60 * 60 * 24 * 7; if ($this->_request->getPost('rememberme') == "1") { Zend_Session::RememberMe($seconds); } else { Zend_Session::ForgetMe(); } //check the redir value if setted $aNamespace = new Zend_Session_Namespace('Nolotiro'); $redir = $aNamespace->redir; if ($redir !== null) { $aNamespace->redir = null; //reset redir value $this->_redirect($redir); } else { //if redir empty goto main home ads and set the welcome logged in message $this->_redirect('/' . $this->lang . '/woeid/' . $woeid . '/give'); } } else { // failure: wrong username $view = $this->initView(); $view->error = $this->view->translate('Wrong email or password, please try again'); } } } // assign the form to the view $this->view->form = $form; }