public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array()) { parent::initialize($dispatcher, $storage, $options); $env = sfContext::getInstance()->getConfiguration()->getEnvironment(); if ($env != 'test') { $this->checkPermissions(); $this->resetPasswordCheck(); // here? $this->checkDatabase(); $this->checkHtaccess(); $this->performTests(); } $request = sfContext::getInstance()->getRequest(); if (!$this->isAuthenticated()) { if ($request->getPostParameter('password') == '' && $request->getCookie($this->cookie_name) != '' && $request->getMethod() != sfRequest::POST) { $params = array(); $params['password'] = $request->getCookie($this->cookie_name); $form = new LoginForm($this, true, array(), array(), false); // no csrf $form->bind($params); if ($form->isValid()) { $this->setAuthenticated(true); } } } }
/** * Login action, detect if is a valid or invalid user */ public function loginAction() { $form = new LoginForm(); if ($this->request->isPost()) { if ($form->isValid($this->request->getPost()) != false) { $password = $this->request->getPost('password'); //Find the username and check if this is active into the application $user = User::findFirst(array("username = :username: AND active = 1", 'bind' => array('username' => strtolower($this->request->getPost('username', 'striptags'))))); // successfully find if ($user && $this->security->checkHash($password, $user->password)) { //Sent the user to set into the application $this->auth->setAccess($user); //Remember me: If is diferent to false assign a token to the user if ($this->request->getPost('remember') != "false") { $user->assign(array('token' => $this->request->getPost('remember'))); if (!$user->save()) { $this->flash->error($user->getMessages()); } } return $this->response->redirect('dashboard'); } else { $form->addFormMessages('username', 'Username name is invalid or not has been activated'); $form->addFormMessages('password', 'information does not match'); } } } $this->view->form = $form; }
public function executeDologin(sfWebRequest $request) { $form = new LoginForm(); $form->bind($this->getRequestParameter('credentials')); if ($form->isValid()) { $credentials = $request->getParameter('credentials'); $login = $credentials['login']; $user = UserTable::getUserFromLogin($login); ## Store array of allowed sectionIds that can be accessed! $sectionIdsArray = Doctrine_Core::getTable('Program')->getProgramsByDepartmentId($user->getDepartmentId()); // set the session correctly $this->getUser()->setAuthenticated(true); $this->getUser()->setAttribute('userId', $user->getId()); $this->getUser()->setAttribute('departmentId', $user->getDepartmentId()); $this->getUser()->setAttribute('departmentName', $user->getDepartment()); $this->getUser()->setAttribute('sectionIds', array_keys($sectionIdsArray)); $this->getUser()->setAttribute('credential', $user->getPrivilege()); ##Do Logging!! $newLog = new AuditLog(); $action = 'User has logged into Student Record Management System'; $newLog->addNewLogInfo($this->getUser()->getAttribute('userId'), $action); $this->getUser()->setFlash('notice', 'Welcome' . ' ' . $user->getFirstName()); //$this->redirect('filter/show?id='.$user->getId()); $this->redirect('programsection/index'); } else { // give the form again $this->form = $form; $this->setTemplate('login'); } }
public function loginAction() { $form = new LoginForm(); $request = $this->getRequest(); if ($request->isPost() && $request->getPost('login') == 'Login') { $post = $request->getPost(); if ($form->isValid($post)) { $result = $this->_user->login($post['user'], $post['password']); //print_r($result); switch ($result) { case User::OK: $this->view->loginMsg = self::LOG_OK; $this->_redirect('/'); break; case User::BAD: $this->view->loginMsg = self::LOG_BAD; break; case User::BLOCK: $this->view->loginMsg = self::LOG_BLOCK; break; } } } $this->view->form = $form; }
public function actionIndex() { require_once __DIR__ . '/../models/LoginForm.php'; $form = new LoginForm(); if (isset($_POST) && sizeof($_POST) > 0 && $form->isValid($_POST)) { $this->redirect($form->getRedirect()); } $this->render('index', array('form' => $form->render())); }
/** * Enter description here... * * @param Zend_Controller_Request_Abstract $request */ public function preDispatch(Zend_Controller_Request_Abstract $request) { // ziskame instanci redirector helperu, ktery ma starosti presmerovani $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector'); $auth = Zend_Auth::getInstance(); // Stav o autentifikaci uzivatele (prihlaseni) se musi nekde udrzovat, vychozi zpusob je session // u session lze nastavit namespace, vychozi je Zend_Auth //$auth->setStorage(new Zend_Auth_Storage_Session('My_Auth')); if ($request->getParam('logout')) { // detekovano odhlaseni $auth->clearIdentity(); // kvuli bezpecnosti provedeme presmerovani $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController); } if ($request->getPost('login')) { $db = Zend_Db_Table::getDefaultAdapter(); // Vytvarime instance adapteru pro autentifikaci // nastavime parametry podle naseho nazvu tabulky a sloupcu // treatment obsahuje pripadne pouzitou hashovaci funkci pro heslo, napr. SHA1 $adapter = new Zend_Auth_Adapter_DbTable($db, $this->tableName, $this->identityColumn, $this->credentialColumn, $this->treatment); $form = new LoginForm(); // validace se nezdari, napr. prazdny formular if (!$form->isValid($request->getPost())) { // FlashMessenger slouzi k uchovani zprav v session $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flash->clearMessages(); $flash->addMessage('Please fill the login form'); $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController, null, array('login-failed' => 1)); } $username = $form->getValue($this->loginField); $password = $form->getValue($this->passwordField); // přidáme salt $password = "******" . $password; // jmeno a heslo predame adapteru $adapter->setIdentity($username); $adapter->setCredential($password); // obecny proces autentifikace s libovolnym adapterem $result = $auth->authenticate($adapter); if ($auth->hasIdentity()) { // Uzivatel byl uspesne overen a je prihlasen // identity obsahuje v nasem pripade ID uzivatele z databaze $identity = $auth->getIdentity(); // presmerujeme $redirector->gotoSimpleAndExit($this->successAction, $this->successController); } else { // autentifikace byla neuspesna // FlashMessenger slouzi k uchovani zprav v session $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); // vlozime do session rovnou chybove hlasky, ktere pak predame do view foreach ($result->getMessages() as $msg) { $flash->addMessage($msg); } $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController, null, array('login-failed' => 1)); } } }
public function loginAction() { $request = $this->getRequest(); $config = Zend_Registry::get('config'); // Check if we have a POST request if (!$request->isPost()) { $this->_helper->redirector('index', 'index'); } $lang = $this->getRequest()->getPost('lang'); if (isset($lang) && $lang != null) { $langNamespace = new Zend_Session_Namespace('Lang'); $langNamespace->lang = $lang; } // Get our form and validate it $form = new LoginForm(); if (!$form->isValid($request->getPost())) { // Invalid entries $this->_flashMessenger->addMessage('Email or Password is required and its length should between 6 and 20'); $this->view->form = $form; $this->_helper->redirector('loginfailed', 'index'); } // Get our authentication adapter and check credentials $adapter = new LoginAuthAdapter($form->getValue('email'), $form->getValue('password')); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if ($result->isValid()) { // We're authenticated! Redirect to the home page $db = Zend_Registry::get('db'); $consumer_id = $db->fetchOne("SELECT id FROM consumer WHERE email = :temp or login_phone = :temp and state='ACTIVE'", array('temp' => $form->getValue('email'))); $consumerModel = new Consumer(); $consumer = $consumerModel->find($consumer_id)->current(); $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = $consumer; $authNamespace->role = 'consumer'; //log $logModel = new Log(); $logId = $logModel->insert(array('consumer_id' => $consumer->id, 'date' => date("Y-m-d H:i:s"), 'event' => 'LOGIN')); $url = $form->getValue('url'); if (isset($url) && !empty($url)) { $this->_redirector = $this->_helper->getHelper('Redirector'); $this->_redirector->gotoUrl($url); } else { $this->_helper->redirector('index', 'home'); } } else { // Invalid credentials $this->_flashMessenger->addMessage('Invalid credentials provided'); $this->view->form = $form; $this->_helper->redirector('loginfailed', 'index'); } }
/** * * @param sfWebRequest $request * @param LoginForm $form */ protected function processLogin(sfWebRequest $request, LoginForm $form) { $form->bind($request->getParameter('signin')); if ($form->isValid()) { $values = $form->getValues(); $this->getUser()->signIn($values['user'], array_key_exists('remember', $values) ? $values['remember'] : false); // Set the tow previous referer to the same value for: // 1) redirect to previous user's location // 2) avoid redirect loop in signin $this->getUser()->setReferer($this->getUser()->getReferer()); // Redirect to referer return $this->redirect($this->getUser()->getReferer()); } }
public function formAction() { $form = new LoginForm('/auth/form/'); $this->view->formResponse = 'Some response'; if ($this->_request->isPost()) { if ($form->isValid($this->_request->getParams())) { $authAdapter = $form->login->getValidator('Authorise')->getAuthAdapter(); $data = $authAdapter->getResultRowObject(null, 'password'); $auth = Zend_Auth::getInstance(); $auth->getStorage()->write($data); $this->_redirect($this->_redirectUrl); } else { $this->view->formResponse = 'Some problem: '; } } $this->view->form = $form; }
public function loginAction() { $request = $this->getRequest(); // Check if we have a POST request if (!$request->isPost()) { $this->_helper->redirector('index', 'admin'); } // Get our form and validate it $form = new LoginForm(); if (!$form->isValid($request->getPost())) { // Invalid entries $this->view->form = $form; $this->_helper->redirector('index', 'admin'); // re-render the login form } // Get our authentication adapter and check credentials $adapter = $this->getAuthAdapter($form->getValues()); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if (!$result->isValid()) { // Invalid credentials $form->setDescription('Invalid credentials provided'); $this->view->form = $form; $this->_helper->redirector('index', 'admin'); // re-render the login form } $db = Zend_Registry::get('db'); $admin_id = $db->fetchOne("SELECT id FROM admin WHERE email = :temp", array('temp' => $auth->getIdentity())); $adminModel = new Admin(); $admin = $adminModel->find($admin_id)->current(); $authNamespace = new Zend_Session_Namespace('Zend_Auth'); //2011-04-08 ham.bao separate the sessions with admin //$authNamespace->user = $admin; $authNamespace->admin = $admin; //2011-04-08 ham.bao separate the sessions with admin $authNamespace->role = 'administrator'; // We're authenticated! Redirect to the home page $url = $form->getValue('url'); if (isset($url) && !empty($url)) { $this->_redirector = $this->_helper->getHelper('Redirector'); $this->_redirector->gotoUrl($url); } else { $this->_helper->redirector('adminindex', 'campaign'); } }
public function executeDologin(sfWebRequest $request) { $form = new LoginForm(); $form->bind($this->getRequestParameter('credentials')); if ($form->isValid()) { $login = $request->getParameter('credentials[login]'); $user = UserPeer::getUserFromLogin($login); // set the session correctly $this->getUser()->setAuthenticated(true); $this->getUser()->setAttribute('user_id', $user->getId()); $this->getUser()->setFlash('notice', 'Welcome' . ' ' . $user->getLogin()); $this->redirect('user/show?id=' . $user->getId()); } else { // give the form again $this->form = $form; $this->setTemplate('login'); } }
public function loginAction() { //First check if the form is valid... $_form = new LoginForm(); if (!$_form->isValid($_POST)) { $this->_redirect(APPLICATION_BASEURL . "/user/index/error/2"); } $_auth = Zend_Auth::getInstance(); $_authAdapter = new Zend_Auth_Adapter_DbTable(); $_authAdapter->setTableName('users')->setIdentityColumn('username')->setCredentialColumn('password'); $_authAdapter->setIdentity($_form->getUsername())->setCredential(sha1($_form->getPassword())); //That's the actual authentication operation $_result = $_auth->authenticate($_authAdapter); if ($_result->isValid()) { $this->view->loggedIn = true; } else { $this->_redirect(APPLICATION_BASEURL . "/user/index/error/1"); } }
/** * Log into the application. */ function loginAction() { // Set the title for this action. $this->view->title = "Login"; // Wrap the whole thing in a try/catch. try { // Get a login form. $form = new LoginForm(); // Check to see if this is an invalid form submission. if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) { $this->view->loginForm = $form; return; } // Get the form values. $values = $form->getValues(); // Get a new authentication adapter. $adapter = new AppAuthAdapter($values['login'], $values['password']); // Perform the authentication using the adapter. $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); // Save the identity in the session. $session = new Zend_Session_Namespace('Web'); $session->employee = $auth->getIdentity(); // Make sure the result is valid. if (!$result->isValid()) { // Authentication failed. $this->view->failedAuthentication = true; $this->view->loginForm = $form; } else { // Authentication succeeded. Determine where to go. $this->_helper->redirector('index', 'timesheet', 'user'); // Save the employee to the view. $this->view->employee = $session->employee; } } catch (Zend_Exception $ex) { // Log the error. Logger::getLogger()->debug($ex->getMessage()); // Authentication failed. $this->view->failedAuthentication = true; $this->view->loginForm = $form; } }
/** Creation of the login page * @access public * @return void */ public function indexAction() { if (null === $this->_auth->getIdentity()) { $form = new LoginForm(); $this->view->form = $form; if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) { $authAdapter = $form->username->getValidator('Authorise')->getAuthAdapter(); $data = $authAdapter->getResultRowObject(NULL, 'password'); $this->_auth->getStorage()->write($data); $this->redirect($this->_helper->loginRedirect()); } else { $this->_auth->clearIdentity(); // $this->getFlash()->addMessage('Sorry, there was a // problem with your submission. Please check and try again'); $form->populate($this->_request->getPost()); } } else { $this->redirect(self::REDIRECT); } }
/** * @Route("/", methods={"POST","GET"}, name="loginindex") */ public function indexAction() { $form = new FormLogin(); $username = $this->request->getPost('username', array('striptags', 'trim')); $password = $this->request->getPost('password', array('striptags', 'trim')); //si es una petición post if ($this->request->isPost()) { $token = $this->request->getPost("randomsting"); if (trim($token) == trim($this->security->getSessionToken())) { //paso validacion CSRF //si el formulario no pasa la validación que le hemos impuesto if ($form->isValid($this->request->getPost()) == false) { //mostramos los mensajes con la clase error que hemos personalizado en los mensajes flash foreach ($form->getMessages() as $message) { $this->flash->error($message); } } else { //obtenemos al usuario por su email $user = User::findFirstByUsername($username); //si existe el usuario buscado por email if ($user) { //si el password que hay en la base de datos coincide con el que ha //ingresado encriptado, le damos luz verde, los datos son correctos if ($this->security->checkHash($password, $user->password)) { //creamos la sesión del usuario con su email $this->session->set("userid", $user->id); $this->session->set("username", $user->username); return $this->response->redirect('index/home'); } else { $this->flash->error("Usuario o contraseña inválida"); } } else { $this->flash->error("Usuario o contraseña inválida"); } } } else { $this->flash->error("Se ha encontrado un problema en la autenticación"); } } $this->view->form = new FormLogin(); }
public function loginAction() { if (null !== $this->_participant) { throw new Exception("You have already passed the checkpoint. What else do you want? If you want to get in again, I don't know why, then say your goodbyes first."); } $this->view->title = "First Checkpoint"; //First check if the form is valid... $_form = new LoginForm(); if (!$_form->isValid($_POST)) { $this->_redirect(APPLICATION_BASEURL_INDEX . "/participant/index/error/2"); } $_auth = Zend_Auth::getInstance(); $_authAdapter = Participant::getAuthAdapter(); $_authAdapter->setIdentity($_form->getUsername())->setCredential(sha1($_form->getPassword())); //That's the actual authentication operation $_result = $_auth->authenticate($_authAdapter); if ($_result->isValid()) { $this->view->loggedIn = true; $this->_redirect(APPLICATION_BASEURL_INDEX . "/index"); } else { $this->_redirect(APPLICATION_BASEURL_INDEX . "/participant/index/error/1"); } }
public function loginAction(Request $request) { if (Session::has('user')) { header('Location: /'); } $form = new LoginForm($request); if ($request->isPost()) { if ($form->isValid()) { $password = new Password($form->password); $model = new securityModel(); try { $user = $model->getUser($form->nickname, $password); Session::set('user', $user); header('Location: /?route=cabinet/index'); } catch (Exception $e) { Session::setFlash($e->getMessage()); } } else { Session::setFlash('Fill the fields'); } } $args = array('form' => $form); return $this->render('login', $args); }
/** On success action * @access public * @return void */ public function successAction() { if (null === $this->_auth->getIdentity()) { $this->view->headTitle('Login to the system'); $form = new LoginForm(); $this->view->form = $form; if ($this->_request->isPost()) { $formData = $this->_request->getPost(); if ($form->isValid($formData)) { $authAdapter = $form->username->getValidator('Authorise')->getAuthAdapter(); $data = $authAdapter->getResultRowObject(null, 'password'); $this->_auth->getStorage()->write($data); $this->redirect($this->_helper->loginRedirect()); } else { $this->_auth->clearIdentity(); $this->getFlash()->addMessage('Sorry, there was a problem with your submission. Please check and try again'); $form->populate($formData); } } } else { $this->redirect('/users/'); } }
return $this; } /** * Method to allow non-MVC usage of Zend_Form so the * elements actually render correctly * * @param Zend_View_Interface $view */ public function setView(Zend_View_Interface $view = null) { parent::setView($view); foreach ($this->getElements() as $item) { $item->setView($view); } return $this; } } // create a view $view = new Zend_View(); $view->doctype('XHTML1_TRANSITIONAL'); $form = new LoginForm(); $form->setView($view); // if the form is submitted if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') { if ($form->isValid($_POST)) { echo "Successful attempt!"; die; } echo "There was an error with the form<br /><br />"; } echo $form->render();
public function executeLogin($request) { $form = new LoginForm(); $form->bind(array('name' => $request->getParameter('name'), 'password' => $request->getParameter('password'))); if ($form->isValid()) { $values = $form->getValues(); $user = User::getByPassword($values['name'], $values['password']); if ($user) { $output = '<rsp stat="ok">' . $user->getXML(false, true) . '</rsp>'; } } else { $output = '<rsp stat="fail"><err code="1" msg="' . $form->getErrorSchema() . '" /></rsp>'; } $this->output = $output; $this->setTemplate('index'); }
<?php include_once './common/base.php'; $title = "login"; include_once './common/header.php'; include_once './forms/form.login.php'; $login_form = new LoginForm(); if ($login_form->read()) { //login form is submitted if ($login_form->isValid()) { //do some session setting here $data = $login_form->getArray(); //username and password include_once './models/class.users.php'; $user = new UserClass(); $user->loadByData($data); //load by username and password $_SESSION['loggedin'] = 'true'; $data2 = $user->getArray(); $_SESSION['userid'] = $data2['id']; echo "Congratulations, you are logged in"; } else { //invalid form submitted, do sth here $login_form->display(); } } else { //form is not submitted at all. $login_form->display(); } $footer = "copyright © 2012 reserved to rajan prasad upadhyay."; include_once "./common/footer.php";
/** * Allows users to log into the application * * @access public * @return void */ public function loginAction() { $this->title = 'Login'; // use the login layout $this->_helper->layout()->setLayout('login'); $form = new LoginForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost())) { $userModel = new BackofficeUser(); if ($userModel->login($form->getValue('username'), $form->getValue('password'))) { $session = new Zend_Session_Namespace('App.Backoffice.Controller'); $request = unserialize($session->request); if (!empty($request)) { $previousUri = $request->getRequestUri(); $this->_redirect($previousUri); } else { $this->_redirect('/profile/'); } } } $this->view->error = TRUE; } $this->view->form = $form; }
/** * login action, Allow the User to connect * @author EL GUENNUNI Sohaib s.elguennuni@gmail.com * @param <empty> * @return <empty> */ public function loginAction() { if (BaseUser::isLogged()) { $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'wall', 'action' => 'index'), 'default', true)); } $this->title = 'Login'; $form = new LoginForm(); if ($this->getRequest()->isPost()) { if ($registration = $this->getRequest()->getParam('inscription', false)) { $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'user', 'action' => 'add'), 'default', true)); } if ($form->isValid($this->getRequest()->getPost())) { if ($this->_userModel->login($form->getValue('username'), $form->getValue('password'))) { $member = App_Utilities::setMember_Registry(); if ($member->validate == 1) { $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'wall', 'action' => 'index'), 'default', true)); } else { Zend_Auth::getInstance()->clearIdentity(); Zend_Session::destroy(); $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'user', 'action' => 'login'), 'default', true)); } } } else { $this->_authentification->addFailedLogin(); } $this->view->error = TRUE; } $this->view->form = $form; }
/** * Enter description here... * * @param Zend_Controller_Request_Abstract $request */ public function preDispatch(Zend_Controller_Request_Abstract $request) { // ziskame instanci redirector helperu, ktery ma starosti presmerovani $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector'); $auth = Zend_Auth::getInstance(); // Stav o autentifikaci uzivatele (prihlaseni) se musi nekde udrzovat, vychozi zpusob je session // u session lze nastavit namespace, vychozi je Zend_Auth //$auth->setStorage(new Zend_Auth_Storage_Session('My_Auth')); if ($request->getParam('logout')) { // detekovano odhlaseni $auth->clearIdentity(); // kvuli bezpecnosti provedeme presmerovani $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController); } if ($request->getPost('login')) { $db = Zend_Db_Table::getDefaultAdapter(); // Vytvarime instance adapteru pro autentifikaci // nastavime parametry podle naseho nazvu tabulky a sloupcu // treatment obsahuje pripadne pouzitou hashovaci funkci pro heslo, napr. SHA1 $adapter = new Zend_Auth_Adapter_DbTable($db, $this->tableName, $this->identityColumn, $this->credentialColumn, $this->treatment); $form = new LoginForm(); // validace se nezdari, napr. prazdny formular if (!$form->isValid($request->getPost())) { // FlashMessenger slouzi k uchovani zprav v session $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flash->clearMessages(); $flash->setNamespace("error")->addMessage("Please fill the login form!"); $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController, null, array('login-failed' => 1)); } $username = $form->getValue($this->loginField); $password = $form->getValue($this->passwordField); // jmeno a heslo predame adapteru $adapter->setIdentity($username); $user = My_Model::get('Users')->fetchRow(array("username = ?" => $username)); if ($user == null) { $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController, null, array('login-failed' => 1)); } $salt = $user->getSalt(); $adapter->setCredential($password . $salt); // obecny proces autentifikace s libovolnym adapterem $result = $auth->authenticate($adapter); if ($auth->hasIdentity()) { // Uzivatel byl uspesne overen a je prihlasen $identity = $auth->getIdentity(); // identity obsahuje v nasem pripade ID uzivatele z databaze // muzeme napr. ulozit IP adresu, cas posledniho prihlaseni atd. $db->update($this->tableName, array('lognum' => new Zend_Db_Expr('lognum + 1'), 'ip' => $request->getServer('REMOTE_ADDR'), 'last_login' => new Zend_Db_Expr('NOW()'), 'browser' => $request->getServer('HTTP_USER_AGENT')), $this->identityColumn . " = '{$identity}'"); $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flash->clearMessages(); $flash->setNamespace("success")->addMessage("Success! You are logged in!"); // presmerujeme $redirector->gotoSimpleAndExit($this->successAction, $this->successController); } else { // autentifikace byla neuspesna // FlashMessenger slouzi k uchovani zprav v session $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flash->clearMessages(); // vlozime do session rovnou chybove hlasky, ktere pak predame do view foreach ($result->getMessages() as $msg) { $flash->setNamespace("error")->addMessage("Login failed, please try again!"); } /* // nicmene muzeme je nastavit podle konkretniho chyboveho kodu if ($result == Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID) { // neplatne heslo } else if ($result == Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS) { // nalezeno vice uzivatelskych identit } else if ($result == Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND) { // identita uzivatele nenalezena } * */ $redirector->gotoSimpleAndExit($this->failedAction, $this->failedController, null, array('login-failed' => 1)); } } }
/** * Login process */ public function executeLogin(sfWebRequest $r) { // If we've posted the form if ($r->isMethod('post')) { // Launching form $login = new LoginForm(); // Binding fields to validators $login->bind($r->getParameter($login->getName())); // Doing a little sleep to prevent automatic bruteforce sleep(1); // If form is valid if ($login->isValid()) { // Fetching account for this user $q = Doctrine::getTable("Users")->findOneByUsername($login->getValue("username")); // Setting cookies for auto-login $this->getResponse()->setCookie("uid", $q->getId(), time() + 365 * 3600 * 24); $this->getResponse()->setCookie("pwd", $q->getCookiesHash(), time() + 365 * 3600 * 24); // Informing user $this->getUser()->setFlash("notice", $this->getContext()->getI18N()->__("Happy to see you %s% !", array("%s%" => $q->getUsername()))); if ($r->isXmlHttpRequest()) { $this->getResponse()->setStatusCode(202); return $this->renderText(""); } } else { $c = (string) $login->getErrorSchema(); preg_match_all('#(.+) \\[(.+)\\]#U', $c, $m); $m[1] = array_map('trim', $m[1]); die(json_encode($m, JSON_FORCE_OBJECT)); } } // Redirect to homepage $this->redirect("@homepage"); }
public function loginAction() { $request = $this->getRequest(); // Check if we have a POST request if (!$request->isPost()) { $this->_helper->redirector('index', 'client'); } // Get our form and validate it $form = new LoginForm(); if (!$form->isValid($request->getPost())) { // Invalid entries $this->view->form = $form; $this->_flashMessenger->addMessage("Email or password is incorrect."); $this->_helper->redirector('index', 'client'); // re-render the login form } // Get our authentication adapter and check credentials $adapter = $this->getAuthAdapter($form->getValues()); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if (!$result->isValid()) { // Invalid credentials $form->setDescription('Invalid credentials provided'); $this->view->form = $form; $this->_flashMessenger->addMessage("Email or password is incorrect."); $this->_helper->redirector('index', 'client'); // re-render the login form } $db = Zend_Registry::get('db'); $client_id = $db->fetchOne("SELECT id FROM client WHERE email = :temp", array('temp' => $auth->getIdentity())); $clientModel = new Client(); $client = $clientModel->find($client_id)->current(); $authNamespace = new Zend_Session_Namespace('Zend_Auth'); //2011-04-08 ham.bao separate the sessions with client $authNamespace->client = $client; // get accessible campaign list $clientCampaginSelect = $db->select(); $clientCampaginSelect->from('client_campaign', 'campaign_id')->join('campaign', 'client_campaign.campaign_id = campaign.id', array('name'))->where('client_campaign.client_id = ?', $client_id)->order('campaign.id desc'); $clientCampaign = $db->fetchAll($clientCampaginSelect); $campaignlist = array(); foreach ($clientCampaign as $temp) { $campaignlist[$temp['campaign_id']] = array($temp['campaign_id'], $temp['name']); } $clientCampaignListNamespace = new Zend_Session_Namespace('ClientCampaignList'); if ($clientCampaignListNamespace->list == null) { $clientCampaignListNamespace->list = $campaignlist; } // We're authenticated! Redirect to the home page $url = $form->getValue('url'); //get unviewed message count save it to session $clientMessageNamespace = new Zend_Session_Namespace('ClientMessage'); //$db = Zend_Registry::get('db'); $messageCount = $db->fetchOne("SELECT count(*) FROM client_message cm WHERE cm.to_type='Client' and cm.to=:clientId and state='NEW'", array('clientId' => $client_id)); if ($messageCount > 0) { $attrName = "count_" . $client_id; $clientMessageNamespace->{$attrName} = $messageCount; } if (isset($url) && !empty($url)) { $this->_redirector = $this->_helper->getHelper('Redirector'); $this->_redirector->gotoUrl($url); } else { $campaignIdArray = array_keys($campaignlist); $this->_helper->redirector('clientcloudtag', 'dashboard', null, array('id' => $campaignIdArray[0])); } }