示例#1
0
 /**
  * 
  * @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']);
 }
示例#2
0
 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();
 }
示例#3
0
 /**
  * 
  */
 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);
 }
示例#4
0
 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;
 }
示例#5
0
 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;
 }
示例#6
0
 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;
 }
示例#7
0
 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);
 }
示例#8
0
 /**
  * Test to see same usernames with different passwords can authenticate when
  * a flag is set
  * 
  * @group   ZF-7289
  */
 public function testEqualUsernamesDifferentPasswordShouldAuthenticateWhenFlagIsSet()
 {
     $this->_db->insert('users', array (
         'username' => 'my_username',
         'password' => 'my_otherpass',
         'real_name' => 'Test user 2',
     ));
     
     // test if user 1 can authenticate
     $this->_adapter->setIdentity('my_username')
                    ->setCredential('my_password')
                    ->setAmbiguityIdentity(true);
     $result = $this->_adapter->authenticate();
     $this->assertFalse(in_array('More than one record matches the supplied identity.',
         $result->getMessages()));
     $this->assertTrue($result->isValid());
     $this->assertEquals('my_username', $result->getIdentity());
     
     $this->_adapter = null;
     $this->_setupAuthAdapter();
     
     // test if user 2 can authenticate
     $this->_adapter->setIdentity('my_username')
                    ->setCredential('my_otherpass')
                    ->setAmbiguityIdentity(true);
     $result2 = $this->_adapter->authenticate();
     $this->assertFalse(in_array('More than one record matches the supplied identity.',
         $result->getMessages()));
     $this->assertTrue($result->isValid());
     $this->assertEquals('my_username', $result->getIdentity());
 }
示例#9
0
 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);
 }
示例#11
0
 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 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');
     }
 }
示例#13
0
 /**
  * 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;
 }
示例#14
0
 public function indexAction()
 {
     $form = new Application_Form_Login();
     if ($this->getRequest()->isPost()) {
         $data = $this->getRequest()->getPost();
         if ($form->isValid($data)) {
             $login = $form->getValue('login');
             // <input name='login'>
             $pass = md5($form->getValue('pass'));
             $adaptateur = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
             $adaptateur->setTableName('membre')->setIdentityColumn('login')->setCredentialColumn('pass')->setIdentity($login)->setCredential($pass);
             if ($adaptateur->authenticate()->isValid()) {
                 // BRAVO
                 $storage = Zend_Auth::getInstance()->getStorage();
                 $mapper = new Application_Model_Mapper_Membre();
                 $membre = $mapper->getByLogin($login);
                 $storage->write($membre);
                 $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/auth.ini');
                 $controller = $config->auth->defaultController;
                 $action = $config->auth->defaultAction;
                 $this->_helper->getHelper('Redirector')->gotoSimple($action, $controller);
             } else {
                 $this->view->msgErreur = "Mauvais login/pass";
                 $form->populate($data);
             }
         } else {
             $form->populate($data);
             $form->buildBootstrapErrorDecorators();
             $this->view->msgErreur = "Veuillez vérifier votre formulaire !";
         }
     }
     $this->view->form = $form;
 }
示例#15
0
 public function authenticate()
 {
     // we first try if the user is the super user
     $rootLogin = Zend_Registry::get('config')->superuser->login;
     $rootPassword = Zend_Registry::get('config')->superuser->password;
     $rootToken = Piwik_UsersManager_API::getTokenAuth($rootLogin, $rootPassword);
     //		echo $rootToken;
     //		echo "<br>". $this->_credential;exit;
     if ($this->_identity == $rootLogin && $this->_credential == $rootToken) {
         return new Piwik_Auth_Result(Piwik_Auth::SUCCESS_SUPERUSER_AUTH_CODE, $this->_identity, array());
     }
     // we then look if the user is API authenticated
     // API authentication works without login name, but only with the token
     // TODO the logic (sql select) should be in the Login plugin, not here
     // this class should stay simple. Another Login plugin should only have to create an auth entry
     // of this class in the zend_registry and it should work
     if (is_null($this->_identity)) {
         $authenticated = false;
         if ($this->_credential === $rootToken) {
             return new Piwik_Auth_Result(Piwik_Auth::SUCCESS_SUPERUSER_AUTH_CODE, $rootLogin, array());
         }
         $login = Zend_Registry::get('db')->fetchOne('SELECT login FROM ' . Piwik::prefixTable('user') . ' WHERE token_auth = ?', array($this->_credential));
         if ($login !== false) {
             return new Piwik_Auth_Result(Zend_Auth_Result::SUCCESS, $login, array());
         } else {
             return new Piwik_Auth_Result(Zend_Auth_Result::FAILURE, $this->_identity, array());
         }
     }
     // if not then we return the result of the database authentification provided by zend
     return parent::authenticate();
 }
示例#16
0
 public static function identify($email, $password)
 {
     $adapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter(), 'users', 'user_name', 'password', 'SHA1(?)');
     $adapter->setIdentity($email);
     $adapter->setCredential($password);
     $authResult = $adapter->authenticate();
     return $authResult->getCode() == 1;
 }
示例#17
0
 /**
  * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
  * attempt an authentication.  Previous to this call, this adapter would have already
  * been configured with all necessary information to successfully connect to a database
  * table and attempt to find a record matching the provided identity.
  *
  * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     $authresult = parent::authenticate();
     if ($authresult->isValid()) {
         // TODO Check if password isn't too old
     }
     return $authresult;
 }
 /**
  * Ensures that getResultRow() works for successful authentication
  *
  * @return void
  */
 public function testGetResultRow()
 {
     $this->_adapter->setIdentity('my_username');
     $this->_adapter->setCredential('my_password');
     $result = $this->_adapter->authenticate();
     $resultRow = $this->_adapter->getResultRow();
     $this->assertEquals($resultRow['username'], 'my_username');
 }
示例#19
0
 public function authenticate()
 {
     $result = parent::authenticate();
     if ($result->isValid() && !$this->_resultRow['enabled']) {
         $this->_authenticateResultInfo = array('identity' => $this->_identity, 'code' => Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, 'messages' => array('Supplied credential is invalid.'));
         return $this->_authenticateCreateAuthResult();
     }
     return $result;
 }
示例#20
0
 /**
  *
  * @group ZF-3068
  */
 public function testDbTableAdapterUsesCaseFolding()
 {
     $this->tearDown();
     $this->_setupDbAdapter(array(\Zend_Db::CASE_FOLDING => \Zend_Db::CASE_UPPER));
     $this->_setupAuthAdapter();
     $this->_adapter->setIdentity('my_username');
     $this->_adapter->setCredential('my_password');
     $this->_db->foldCase(\Zend_Db::CASE_UPPER);
     $this->_adapter->authenticate();
 }
 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');
             }
         }
     }
 }
 /**
  * Ensure that exceptions are caught
  *
  */
 public function testCatchExceptionBadSql()
 {
     $this->_adapter->setTableName('bad_table_name');
     $this->_adapter->setIdentity('value');
     $this->_adapter->setCredential('value');
     try {
         $result = $this->_adapter->authenticate();
         $this->fail('Exception should have been thrown');
     } catch (Zend_Auth_Exception $e) {
         $this->assertEquals($e->getMessage(), 'The supplied parameters to Zend_Auth_Adapter_DbTable failed to produce a valid sql statement, please check table and column names for validity.');
     }
 }
示例#23
0
 /**
  * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
  * attempt an authentication.  Previous to this call, this adapter would have already
  * been configured with all necessary information to successfully connect to a database
  * table and attempt to find a record matching the provided identity.
  *
  * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     if ($user = Centurion_Db::getSingleton('auth/user')->findOneByUsername($this->_identity)) {
         $algorithm = $user['algorithm'];
         if (false !== ($pos = strpos($algorithm, '::'))) {
             $algorithm = array(substr($algorithm, 0, $pos), substr($algorithm, $pos + 2));
         }
         if (!is_callable($algorithm)) {
             throw new Zend_Auth_Adapter_Exception(sprintf('The algorithm callable "%s" is not callable.', $algorithm));
         }
         $this->setCredential(call_user_func_array($algorithm, array($user['salt'] . $this->_credential)));
     }
     return parent::authenticate();
 }
示例#24
0
 /**
  * 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;
 }
示例#25
0
    public function indexAction()
    {
        // action body
        require_once 'Zend/Session/Namespace.php';
        $result1 = 1;
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $loginForm = new Application_Form_Login($_POST);
        if ($this->getRequest()->isPost()) {
            $this->request = $this->getRequest();
            if (isset($_POST['submit']) && $loginForm->isValid($_POST)) {
                $adapter = new Zend_Auth_Adapter_DbTable($db, 'users', 'name', 'password');
                $adapter->setIdentity($loginForm->getValue('username'));
                $adapter->setCredential($loginForm->getValue('password'));
                $result = $adapter->authenticate($adapter);
                if ($result->isValid()) {
                    //new Zend_Session_Namespace();
                    //$this->_helper->FlashMessenger('Erfolgreich angemeldet');
                    //$db = Zend_Registry::get('dbc');
                    $db->query('SET NAMES utf8;');
                    $query = 'SELECT
		                                		user_id, userstate

		                      		FROM
		                                		USERS
					
		                     		WHERE 		name = "' . mysql_real_escape_string($loginForm->getValue('username')) . '";';
                    $stmt = $db->query($query);
                    $result1 = $stmt->fetch();
                    $session = new Zend_Session_Namespace('loggedin');
                    $session->loggedin = $result1['userstate'];
                    $session->loggedin_id = $result1['user_id'];
                    $session->loggedin_user = $loginForm->getValue('username');
                    echo "Anmeldung erfolgreich";
                    //$vision=1;
                    //$this->view->vision = $vision;
                    $loginForm = null;
                    //$this->view->loginForm = $loginForm;
                    $this->redirect('index');
                    //Zend_Session::start();
                    //new Zend_Session_Namespace();
                    //session_start();
                    return;
                } else {
                    echo "Wrong Username or Password";
                }
            }
        }
        $this->view->loginForm = $loginForm;
    }
示例#26
0
 /**
  * Test fallback to default database adapter
  *
  * @group ZF-7510
  */
 public function testAuthenticateWithDefaultDbAdapter()
 {
     require_once 'Zend/Db/Table/Abstract.php';
     // preserve default adapter between cases
     $tmp = Zend_Db_Table_Abstract::getDefaultAdapter();
     // make sure that default db adapter exists
     Zend_Db_Table_Abstract::setDefaultAdapter($this->_db);
     // check w/o passing adapter
     $this->_adapter = new Zend_Auth_Adapter_DbTable();
     $this->_adapter->setTableName('users')->setIdentityColumn('username')->setCredentialColumn('password')->setTableName('users')->setIdentity('my_username')->setCredential('my_password');
     $result = $this->_adapter->authenticate();
     $this->assertTrue($result->isValid());
     // restore adapter
     Zend_Db_Table_Abstract::setDefaultAdapter($tmp);
 }
示例#27
0
 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');
         }
     }
 }
示例#28
0
 public function indexAction()
 {
     if ($this->_request->isPost()) {
         $username = $this->_request->getParam("username");
         $password = $this->_request->getParam("password");
         $db = Zend_Db_Table::getDefaultAdapter();
         $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'student', 'username', 'password');
         $authAdapter->setIdentity($username);
         $authAdapter->setCredential(md5($password));
         $result = $authAdapter->authenticate();
         if ($result->isValid()) {
             //echo "if";
             $this->redirect('categories/list');
         } else {
             echo "else";
             //$this->render('index');
         }
     }
 }
示例#29
0
文件: Users.php 项目: neosin/reactor
 /**
  * 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);
 }
示例#30
0
 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
     }
 }