Пример #1
0
 public function loginAction()
 {
     $messages = null;
     $form = new AuthForm();
     $form->get('submit')->setvalue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_name', 'usr_password', "MD5(CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
             // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
             // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
             $result = $auth->authenticate($authAdapter);
             //                echo '<pre>';
             //                print_r($result);
             //                echo '</pre>';
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                     //                                if ($data['rememberme']) {
                     //                                        $sessionManager = new \Zend\Session\SessionManager();
                     //                                        $sessionManager->rememberMe($time);
                     //                                }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         } else {
             echo '<h1> The form is NOT valid </h1>';
         }
     }
     //        echo '<pre>';
     //        print_r($_SESSION);
     //        echo '</pre>';
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
Пример #2
0
 public function authenticate(array $credentials)
 {
     $username = $credentials['username'];
     $password = $credentials['password'];
     $dbAdapter = $this->serviceManager->get('Zend\\Db\\Adapter\\Adapter');
     $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'users', 'username', 'password', 'MD5(?)');
     $dbTableAuthAdapter->setIdentity($username);
     $dbTableAuthAdapter->setCredential($password);
     $authService = new AuthenticationService();
     $authService->setAdapter($dbTableAuthAdapter);
     //$authService->setStorage($this->getServiceManager()->get('IdAuth\Storage'));
     $authResult = $authService->authenticate();
     $result = new ProviderResult();
     $result->setAuthCode($authResult->getCode());
     $result->setMessages($authResult->getMessages());
     $result->setValid($authResult->isValid());
     $result->setName('IdAuth\\Providers\\DbTable');
     $config = $this->serviceManager->get('Config');
     $options = $config['idAuth']['providerOptions']['DbTable'];
     $result->setOptions($options);
     if ($authResult->isValid()) {
         $result->setIdentity($this->queryIdentity($username));
     }
     return $result;
 }
Пример #3
0
    /**
     * Test to see same usernames with different passwords can authenticate when
     * a flag is set
     *
     * @group   ZF-7289
     */
    public function testEqualUsernamesDifferentPasswordShouldAuthenticateWhenFlagIsSet()
    {
        $sqlInsert = 'INSERT INTO users (username, password, real_name) '
                   . 'VALUES ("my_username", "my_otherpass", "Test user 2")';
        $this->_db->query($sqlInsert, DbAdapter::QUERY_MODE_EXECUTE);

        // 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($result2->isValid());
        $this->assertEquals('my_username', $result2->getIdentity());
    }
Пример #4
0
 public function authenticate()
 {
     $authAdapter = new AuthAdapter($this->adapter);
     $authAdapter->setTableName('administrators')->setIdentityColumn('username')->setCredentialColumn('password');
     $authAdapter->setIdentity($this->adapterUsername)->setCredential($this->adapterPassword);
     $authService = $this->authConnect->authenticate($authAdapter);
     if ($authService->isValid()) {
         $this->authConnect->getStorage()->write($authAdapter->getResultRowObject());
         return array('status' => 'success', 'code' => '200', 'msg' => $authService->getMessages());
     } else {
         return array('status' => 'failure', 'code' => '301', 'msg' => $authService->getMessages());
         /*
         switch ($authService->getCode()) 
         {
         	case Result::FAILURE_CREDENTIAL_INVALID:
         		break;
         		
         	case Result::FAILURE_IDENTITY_NOT_FOUND:
         		break;
         			
         	default:
         		break;
         }
         */
     }
 }
Пример #5
0
 public function authenticate()
 {
     // connection
     $dbAdapter = new DbAdapter(array('driverClass' => 'Doctrine\\DBAL\\Driver\\PDOMySql\\Driver', 'dbname' => 'RioVerdeShopping'));
     // set identification
     $authAdapter = new AuthAdapter($dbAdapter);
     $authAdapter->setTableName($this->entity)->setIdentityColumn($this->identidade)->setCredentialColumn($this->credencial);
     $authAdapter->setIdentity($this->login)->setCredential($this->senha);
     //authenticate
     $result = $authAdapter->authenticate();
     switch ($result->getCode()) {
         case Result::FAILURE_IDENTITY_NOT_FOUND:
             $msg = "Login inexistente!";
             break;
         case Result::FAILURE_CREDENTIAL_INVALID:
             $msg = "Senha inválida!";
             break;
         case Result::SUCCESS:
             $registro = $result->getIdentity();
             $msg = "Seja bem vindo(a) " . $registro['nome'];
             break;
         default:
             $msg = "Falha na tentativa de autenticação!";
             break;
     }
     return $msg;
 }
Пример #6
0
 public function getAdapter()
 {
     $adapter = new AuthAdapter($this->db, 'credentials_password', 'credentials_password.email', 'credentials_password.password');
     $adapter->getDbSelect()->join('accounts', 'accounts.id = credentials_password.account');
     $adapter->setIdentity($this->email);
     $adapter->setCredential($this->getHashedPassword());
     return $adapter;
 }
Пример #7
0
 public function indexAction()
 {
     $viewModel = new ViewModel();
     $request = $this->getRequest();
     if (!$request->isPost()) {
         $this->layout('layout/login');
         return $viewModel;
     }
     $user = $this->identity();
     $messages = null;
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $sm = $this->getServiceLocator();
         $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
         $authAdapter = new AuthAdapter($dbAdapter, 'users', 'username', 'password', 'MD5(?) AND block = 1');
         $authAdapter->setIdentity($request->getPost('username'))->setCredential($request->getPost('password'));
         if (trim($request->getPost('username')) == "" || trim($request->getPost('password')) == "") {
             return $this->redirect()->toRoute('auth');
         }
         // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
         // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
         // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
         $result = $auth->authenticate($authAdapter);
         switch ($result->getCode()) {
             case Result::FAILURE_IDENTITY_NOT_FOUND:
                 // do stuff for nonexistent identity
                 break;
             case Result::FAILURE_CREDENTIAL_INVALID:
                 // do stuff for invalid credential
                 break;
             case Result::SUCCESS:
                 $storage = $auth->getStorage();
                 $storage->write($authAdapter->getResultRowObject(null, 'password'));
                 $time = 28800;
                 // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                 //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                 if ($request->getPost('username')) {
                     $sessionManager = new \Zend\Session\SessionManager();
                     $sessionManager->rememberMe($time);
                 }
                 return $this->redirect()->toRoute('home');
                 break;
             default:
                 // do stuff for other failure
                 break;
         }
         foreach ($result->getMessages() as $message) {
             $messages .= "{$message}\n";
         }
     }
     $this->layout('layout/login');
     return $viewModel;
 }
Пример #8
0
 public function indexAction()
 {
     $this->dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter');
     $auth = $this->auth;
     $id = $this->params()->fromRoute('id', 0);
     $cod = $this->params()->fromRoute('validar', 0);
     if ($this->getRequest()->isPost()) {
         $usuario = $this->getRequest()->getPost();
         $id = $usuario['id'];
         $codigo = $usuario['codigo'];
         $busqueda = new Usuario($this->dbAdapter);
         $usuario1 = $busqueda->SearchValidarUsuario($id, $codigo);
         if (count($usuario1) == 1) {
             $usuarioupdate = array('us' => $usuario['username'], 'Nombre' => $usuario['nombre'], 'direccion' => $usuario['direccion'], 'verificado' => 'si');
             $busqueda->actualizar($usuarioupdate, $id);
             $authAdapter = new AuthAdapter($this->dbAdapter, 'usuario', 'us', 'contrasena');
             /* 
              Podemos hacer lo mismo de esta manera:
              $authAdapter = new AuthAdapter($dbAdapter);
              $authAdapter
                  ->setTableName('users')
                  ->setIdentityColumn('username')
                  ->setCredentialColumn('password');
             */
             /*
             En el caso de que la contraseña en la db este cifrada
             tenemos que utilizar el mismo algoritmo de cifrado
             */
             //Establecemos como datos a autenticar los que nos llegan del formulario
             $authAdapter->setIdentity($usuario['username'])->setCredential($usuario1[0]['contrasena']);
             //Le decimos al servicio de autenticación que el adaptador
             $auth->setAdapter($authAdapter);
             //Le decimos al servicio de autenticación que lleve a cabo la identificacion
             $result = $auth->authenticate();
             //Si el resultado del login es falso, es decir no son correctas las credenciales
             if ($authAdapter->getResultRowObject() == false) {
                 //Crea un mensaje flash y redirige
                 $mensaje = "Credenciales Incorrectas. ";
             } else {
                 // Le decimos al servicio que guarde en una sesión
                 // el resultado del login cuando es correcto
                 $auth->getStorage()->write($authAdapter->getResultRowObject());
                 //Nos redirige a una pagina interior
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/usuario/cpanel');
             }
         }
     } else {
         $busqueda = new Usuario($this->dbAdapter);
         $usuario = $busqueda->SearchValidarUsuario($id, $cod);
         $username = @$usuario[0]['us'];
         $verificado = @$usuario[0]['verificado'];
         $email = @$usuario[0]['email'];
     }
     $vista = new ViewModel(array('id' => @$usuario[0]['id_usuario'], 'codigo' => @$usuario[0]['cod'], 'verificado' => @$verificado, 'email' => @$email, 'mensaje' => @$mensaje, 'username' => @$username));
     $this->layout('layout/layout');
     return $vista;
 }
Пример #9
0
 public function loginAction()
 {
     $auth = $this->auth;
     $identi = $auth->getStorage()->read();
     if ($identi != false && $identi != null) {
         return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/clientes/clientes/listar');
     }
     //DbAdapter
     $this->dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter');
     //Creamos el formulario de login
     $form = new LoginForm("form");
     //Si nos llegan datos por post
     if ($this->getRequest()->isPost()) {
         /* Creamos la autenticación a la que le pasamos:
                1. La conexión a la base de datos
                2. La tabla de la base de datos
                3. El campo de la bd que hará de username
                4. El campo de la bd que hará de contraseña
            */
         $authAdapter = new AuthAdapter($this->dbAdapter, 'administrador', 'usuario', 'pass');
         /* 
          Podemos hacer lo mismo de esta manera:
          $authAdapter = new AuthAdapter($dbAdapter);
          $authAdapter
              ->setTableName('users')
              ->setIdentityColumn('username')
              ->setCredentialColumn('password');
         */
         /*
         En el caso de que la contraseña en la db este cifrada
         tenemos que utilizar el mismo algoritmo de cifrado
         */
         $pass = $this->request->getPost("password");
         $securePass = md5($pass);
         //Establecemos como datos a autenticar los que nos llegan del formulario
         $authAdapter->setIdentity($this->getRequest()->getPost("email"))->setCredential($securePass);
         //Le decimos al servicio de autenticación que el adaptador
         $auth->setAdapter($authAdapter);
         //Le decimos al servicio de autenticación que lleve a cabo la identificacion
         $result = $auth->authenticate();
         //Si el resultado del login es falso, es decir no son correctas las credenciales
         if ($authAdapter->getResultRowObject() == false) {
             //Crea un mensaje flash y redirige
             $this->flashMessenger()->addMessage("Credenciales incorrectas, intentalo de nuevo");
             return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/clientes/clientes/login');
         } else {
             // Le decimos al servicio que guarde en una sesión
             // el resultado del login cuando es correcto
             $auth->getStorage()->write($authAdapter->getResultRowObject());
             //Nos redirige a una pagina interior
             return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/clientes/clientes/listar');
         }
     }
     return new ViewModel(array("form" => $form));
 }
Пример #10
0
 public function loginAction()
 {
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     // process the form
     $form = new LoginForm();
     $request = $this->getRequest();
     if ($this->getRequest()->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             // check if the user exists
             $sm = $this->getServiceLocator();
             $mapper = $sm->get('User\\Model\\UserMapper');
             $params = array('where' => 'username = "******"');
             $users = $mapper->select($params);
             if ($users) {
                 $user = $users[0];
                 /**
                  * If the account is not active, prompt the user to activate
                  * the account
                  */
                 if (!$user->getActive()) {
                     return $this->redirect()->toRoute('registration', array('action' => 'confirm', 'id' => $user->getId()));
                 }
                 // authenticate the user
                 $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
                 $adapter = new AuthAdapter($dbAdapter, 'user', 'username', 'password_hash');
                 $adapter->setIdentity($data['credential']);
                 $adapter->setCredential(hash('sha256', $user->getPassword_salt() . $data['password']));
                 $result = $auth->authenticate($adapter);
                 if ($result->isValid()) {
                     // store session information in database
                     $mapper = $sm->get('User\\Model\\SessionMapper');
                     $session = new Session(array('user_id' => $user->getId(), 'ip_address' => $_SERVER['REMOTE_ADDR'], 'login_timestamp' => date('Y-m-d H:i:s')));
                     $mapper->save($session);
                     // store user information in session variable
                     $container = new Container('user');
                     $container->user = $user->get_array();
                     return $this->redirect()->toRoute('home');
                 } else {
                     foreach ($result->getMessages() as $message) {
                         print "{$message}\n";
                     }
                 }
             } else {
                 print "Invalid username/email";
             }
         }
     }
     return new ViewModel(array('form' => $form));
 }
 public function loginAction()
 {
     $user = $this->identity();
     $form = new LoginForm();
     $messages = null;
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter(new LoginFilter($this->getServiceLocator()));
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password', "MD5(?)");
             $authAdapter->setIdentity($data['email'])->setCredential($data['password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'password'));
                     $user = $auth->getIdentity();
                     switch ($user->role_id) {
                         case 1:
                             return $this->redirect()->toRoute('admin');
                             break;
                         case 2:
                             return $this->redirect()->toRoute('teacher');
                             break;
                         case 3:
                             return $this->redirect()->toRoute('student');
                             break;
                         default:
                             return $this->redirect()->toRoute('home');
                             break;
                     }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         }
     }
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
Пример #12
0
 public function loginAction()
 {
     $messages = null;
     $form = new AuthForm();
     $form->get('submit')->setValue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_name', 'usr_password', "MD5 (CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     /*$time = 1209600; // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                                                 if ($data['rememberme']) {
                                                         $sessionManager = new \Zend\Session\SessionManager();
                                                         $sessionManager->rememberMe($time);
                                                 }*/
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
             //echo '<pre>';
             //print_r($_SESSION);
             //echo '</pre>';
         } else {
             //echo 'Form is not valid!';
         }
     }
     return new viewModel(array('form' => $form, 'messages' => $messages));
 }
 public function awakeSignIn()
 {
     $this->auth = new AuthenticationService();
     $sm = $this->getApplicationServiceLocator();
     $sm->setAllowOverride(true);
     $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
     $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password');
     $authAdapter->setIdentity('*****@*****.**');
     $authAdapter->setCredential(md5('123'));
     $this->auth->authenticate($authAdapter);
     $this->assertTrue($this->auth->hasIdentity());
 }
Пример #14
0
 public function login(PasswordModel $password, $dbAdapter)
 {
     $authAdapter = new AuthAdapter($dbAdapter);
     $authAdapter->setTableName('password')->setIdentityColumn('staff_id')->setCredentialColumn('password');
     $authAdapter->setIdentity($password->staffId)->setCredential($password->password);
     $result = $this->auth->authenticate($authAdapter);
     if ($result->isValid()) {
         $storage = $this->auth->getStorage();
         $storage->write($authAdapter->getResultRowObject());
     } else {
         throw new \Exception('パスワードが間違いました。');
     }
 }
 public function testSigninWithWrongCredentials()
 {
     $auth = new AuthenticationService();
     $sm = $this->getApplicationServiceLocator();
     $sm->setAllowOverride(true);
     $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
     $messages = null;
     $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password');
     $authAdapter->setIdentity('*****@*****.**');
     $authAdapter->setCredential(md5('456'));
     $this->result = $auth->authenticate($authAdapter);
     foreach ($this->result->getMessages() as $message) {
         $messages .= "{$message}";
     }
     $this->assertEquals($messages, 'Supplied credential is invalid.');
 }
 /**
  * Metodo para validar acceso al portal
  * @return \Zend\View\Model\ViewModel
  */
 public function ingresoAction()
 {
     if ($this->getRequest()->isPost()) {
         $auth = new AuthenticationService();
         $validate = $this->getRequest()->getPost();
         $authAdapter = new AuthAdapter($this->adapter(), 'usuario', 'usuario_correo', 'usuario_password');
         $authAdapter->setIdentity($validate['correo']);
         $authAdapter->setCredential(md5($validate['password']));
         $resultado = $auth->authenticate($authAdapter);
         switch ($resultado->getCode()) {
             case Result::FAILURE_IDENTITY_NOT_FOUND:
                 $this->message = "Usuario y/o contraseña incorrectos";
                 $this->flashMessenger()->addMessage($this->message);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login');
             case Result::FAILURE_CREDENTIAL_INVALID:
                 $this->message = "Usuario y/o contraseña incorrectos";
                 $this->flashMessenger()->addMessage($this->message);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login');
             case Result::SUCCESS:
                 $this->flashMessenger()->clearMessages();
                 $store = $auth->getStorage();
                 $store->write($authAdapter->getResultRowObject(null, 'usuario_password'));
                 $sessionConfig = new StandardConfig();
                 $sessionConfig->setRememberMeSeconds(20)->setCookieLifetime(30)->setCookieSecure(true)->setGcMaxlifetime(60)->setGcDivisor(60);
                 $sesionMa = new SessionManager($sessionConfig);
                 $sesionMa->rememberMe(30);
                 $container = new Container('cbol');
                 $container->setExpirationSeconds(1800);
                 $sesionMa->start();
                 $container->idSession = $auth->getIdentity()->perfil_id;
                 $permisos = $this->getPermisos($auth->getIdentity()->usuario_id);
                 $container->permisosUser = $permisos;
                 $indexProfile = \Login\IndexAllProfile::listIndexAllProfiles($auth->getIdentity()->perfil_id);
                 if ($indexProfile == 'vias') {
                     $container->reportesVias = $this->getReportesViales();
                 }
                 if ($indexProfile == 'admin') {
                     $container->sugerencias = $this->getSugerenciasAction();
                 }
                 $container->setDefaultManager($sesionMa);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . "/{$indexProfile}");
             default:
                 echo 'Mensaje por defecto';
                 break;
         }
     }
 }
Пример #17
0
 public function loginAction()
 {
     $user = $this->identity();
     $form = new AuthForm();
     $form->get('submit')->setValue('Войти');
     $messages = null;
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_email', 'usr_password', "MD5(CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_email'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     if ($data['rememberme']) {
                         $sessionManager = new \Zend\Session\SessionManager();
                         $sessionManager->rememberMe($time);
                     }
                     break;
                 default:
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         }
     }
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
Пример #18
0
 public function loginAction()
 {
     $authStorage = new AuthenticationStorage(self::NAMESPACE_ZENDSTORE_FRONT);
     $authService = new AuthenticationService($authStorage);
     if ($authService->hasIdentity()) {
         echo 'You have logined';
         exit;
     }
     $form = new UserForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $user = new User();
         $form->setInputFilter($user->getInputFilter());
         $form->setData($request->post());
         if ($form->isValid()) {
             $data = $form->getData();
             // Authentication
             $sm = $this->getServiceLocator();
             $db = $sm->get('db-adapter');
             //$authAdapter = new AuthenticationAdapter($db, 'user', 'email', 'password', 'MD5(?)');
             $authAdapter = new AuthenticationAdapter($db, 'user', 'email', 'password', 'MD5(CONCAT(?, password_salt))');
             $authAdapter->setIdentity($data['email']);
             $authAdapter->setCredential($data['password']);
             $result = $authService->authenticate($authAdapter);
             if ($result->isValid()) {
                 return $this->redirect()->toRoute('user-front-user');
             } else {
                 var_dump($result->getMessages());
                 exit;
             }
         } else {
             echo '<h1>ERROR: Form data is invalid.</h1>';
             echo '<pre>';
             print_r($form->getMessages());
             exit;
         }
     }
     $viewVars = array('form' => $form);
     $viewModel = $this->getViewModel();
     $viewModel->setVariables($viewVars);
     return $viewModel;
 }
Пример #19
0
 public function indexAction()
 {
     $headTitle = $this->getServiceLocator()->get('viewHelperManager')->get('headTitle');
     $translator = $this->getServiceLocator()->get('translator');
     $headTitle->append($translator->translate('System Login'));
     $form = new LoginForm();
     $vars = array();
     $auth = new AuthenticationService();
     if (!$auth->hasIdentity()) {
         $vars['form'] = $form;
         $request = $this->getRequest();
         if ($request->isPost()) {
             $post_data = $request->getPost();
             $form->setData($post_data);
             // Validate the form
             if ($form->isValid()) {
                 // Authentication ...
                 $dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter');
                 // Configure the instance with constructor parameters...
                 $authAdapter = new AuthAdapter($dbAdapter, 'account', 'username', 'password', 'MD5(?)');
                 // Set the input credential values (e.g., from a login form)
                 $data = $form->getData();
                 $authAdapter->setIdentity($data['username'])->setCredential($data['password']);
                 $auth = new AuthenticationService();
                 $result = $auth->authenticate($authAdapter);
                 $vars['result'] = $result;
                 if (!$result->isValid()) {
                     // Authentication failed;
                 } else {
                     // Authentication succeeded; the identity ($username) is stored
                     // in the session
                     // $result->getIdentity() === $auth->getIdentity()
                     // $result->getIdentity() === $username
                     return $this->redirect()->toRoute('auth');
                 }
             }
         }
     }
     $view_page = new ViewModel($vars);
     return $view_page;
 }
Пример #20
0
 public function indexAction()
 {
     $this->layout('layout/login');
     $auth = new AuthenticationService();
     $viewmodel = new ViewModel();
     $form = new LoginForm();
     $request = $this->getRequest();
     $filters = new LoginFormFilter();
     $form->get('submit')->setValue('Login');
     $message = "";
     //Message
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('backend_index');
     }
     if ($request->isPost()) {
         $form->setInputFilter($filters);
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $authAdapter = new AuthAdapter($dbAdapter, 'user', 'username', 'password', 'sha1(?)');
             $authAdapter->setIdentity($data['username'])->setCredential($data['password']);
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'password'));
                     return $this->redirect()->toRoute('backend_index');
                     break;
                 default:
                     $message = "Usuario o clave incorrecto.";
                     break;
             }
         }
     }
     $viewmodel->form = $form;
     $viewmodel->message = $message;
     return $viewmodel;
 }
 public function loginAction()
 {
     $entityManager = $this->getEntityManager();
     $form = new LoginForm($entityManager);
     $error = null;
     $request = $this->getRequest();
     if ($request->isPost()) {
         $formInputFilter = new LoginFilter($entityManager);
         $form->setInputFilter($formInputFilter->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $formData = $form->getData();
             $authAdapter = new AuthAdapter($this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter'), 'users', 'login', 'password', "MD5(?)");
             $authAdapter->setIdentity($formData["loginutilisateur"])->setCredential($formData["passwordutilisateur"]);
             $authResultat = $authAdapter->authenticate();
             if ($authResultat->isValid()) {
                 $userData = $authAdapter->getResultRowObject();
                 if ($userData->acces == '4') {
                     $error = 'Votre compte a été supprimé';
                 } elseif ($userData->acces == '3') {
                     $authService = new AuthenticationService();
                     $authService->getStorage()->write($userData);
                     // TODO Redirections selon profil utilisateur
                     switch ($userData->type) {
                         default:
                             // $this->redirect()->toUrl($this->getBaseUrl());
                             $this->redirect()->toRoute("home");
                     }
                 } else {
                     $error = 'Votre compte est désactivé';
                 }
             } else {
                 $error = 'Identifiants incorrects';
             }
         } else {
             $error = 'Identifiants incorrects';
         }
     }
     return new ViewModel(array('form' => $form, 'alertmessages' => array('error' => $error)));
 }
Пример #22
0
 public function loginAction()
 {
     $auth = $this->getAuth();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('todo');
     }
     $form = new LoginForm();
     $form->get('submit')->setValue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $user = new User();
         $form->setInputFilter($user->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $authAdapter = new AuthAdapter($this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter'), 'user', 'email', 'password', 'MD5(?)');
             $authAdapter->setIdentity($data['email'])->setCredential($data['password']);
             $auth->authenticate($authAdapter);
             return $this->redirect()->toRoute('todo');
         } else {
         }
     }
     return array('form' => $form);
 }
Пример #23
0
 public function userLogin($useremail, $password, $remember_me = 0)
 {
     $authAdapter = new AuthAdapter($this->getAdapter(), 'userlist', 'useremail', 'password', 'CONCAT(?,salt_key) and is_active=1 and is_delete=0');
     $authAdapter->setIdentity(trim($useremail));
     $authAdapter->setCredential(base64_encode(trim($password)));
     $auth = new AuthenticationService();
     $result = $authAdapter->authenticate($authAdapter);
     if ($result->isValid()) {
         if ($remember_me == 1) {
             setcookie('discoveryCRMcookieEmail', $useremail, time() + 86400 * 365, "/");
             setcookie('discoveryCRMcookiePswd', $password, time() + 86400 * 365, "/");
         } else {
             setcookie('discoveryCRMcookieEmail', $useremail, time() - 86400, "/");
             setcookie('discoveryCRMcookiePswd', $password, time() - 86400, "/");
         }
         $data = $authAdapter->getResultRowObject();
         $auth->getStorage()->write($data);
         $identity = $auth->getIdentity();
         $this->getModel()->generateOTP();
         return 1;
     } else {
         return 0;
     }
 }
Пример #24
0
 function authenticate(Adapter $adapter)
 {
     /*
      * Criando o auth adapter:&nbsp; passando o primeiro parâmetro o
      * adaptador do banco de dados $zendDb segundo parâmetro a tabela de
      * usuarios terceiro parâmetro a coluna da tabela aonde está o login
      * quarto parâmetro a coluna da tabela aonde está a senha
      */
     $bcrypt = new Bcrypt();
     if ($bcrypt->verify($this->authPassword, $this->storedHash)) {
         $authAdapter = new DbTable($adapter, 'tb_user', 'email', 'password');
         /*
          * Seta o credential tratment:&nbsp; tratamento da senha para ser
          * criptografada em md5 passado um parâmetro status para logar o
          * usuario que esteja ativo no sistema no caso dos parâmetros você
          * pode passar quantos forem necessários usando o AND na sequência
          * seta o Identity que é o login e Credential que é a senha
          */
         $authAdapter->setCredentialTreatment('? AND status = 1');
         $authAdapter->setIdentity($this->authEmail);
         $authAdapter->setCredential($this->storedHash);
         // Instanciando o AutenticationService para fazer a altenticação com
         // os dados passados para o authAdapter
         $authService = new AuthenticationService();
         // Autenticando o passando para a variável result o resultado da
         // autenticação
         $result = $authService->authenticate($authAdapter);
         // Validando a autenticação
         if ($result->isValid()) {
             // Se validou damos um get nos dados autenticados usando o
             // $result->getIdentity()
             $identity = $result->getIdentity();
             /*
              * Imprimindo os dados na tela para confirmar os dados
              * autenticados pronto, se aparecer os dados isso quer dizer que
              * o usuario está autenticado no sistema
              */
             // var_dump ( $identity );
             return true;
         } else {
             /*
              * Caso falhe a autenticação, será gerado o log abaixo que será
              * impresso&nbsp; na tela do computador para você sabe do
              * problema ocorrido. os erros listados abaixo são os erros mais
              * comuns que podem ocorrer.
              */
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     //echo "O email não existe";
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     //echo "A senha não confere";
                     break;
                 default:
                     foreach ($result->getMessages() as $message) {
                         //echo $message;
                     }
             }
             return false;
         }
     } else {
         //echo "A senha não confere";
         return false;
     }
 }
Пример #25
0
 public function accountAction()
 {
     $session = new Container('user');
     $logged = $session->offsetGet('username');
     if ($logged === null) {
         $this->redirect()->toRoute('user', array('action' => 'signin'));
     }
     $id = (int) $this->params()->fromRoute('id', 0);
     if (!$id) {
         return $this->redirect()->toRoute('user');
     }
     $user = $this->getUserTable()->getUser($id);
     $form = new AccountForm();
     $form->bind($user);
     $form->get('submit')->setAttribute('value', 'Save changes');
     $form->get('password')->setAttribute('readonly', 'true');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter($user->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $username = $this->getUserTable()->getUserByName($user->username);
             if (!empty($username)) {
                 $this->redirect()->toRoute('user', array('action' => 'account', 'id' => $user->id));
                 echo '<div class="alert alert-error" id="change-alert">
                         <button type="button" class="close" data-dismiss="alert">&times;</button>
                         <h4>Warning!</h4>
                         User already exist!.
                       </div>';
             } else {
                 $this->getUserTable()->modifyAccount($user);
                 $sm = $this->getServiceLocator();
                 $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
                 $authAdapter = new AuthAdapter($dbAdapter);
                 $authAdapter->setTableName('user')->setIdentityColumn('username')->setCredentialColumn('password');
                 $authAdapter->setIdentity($user->username)->setCredential($user->password);
                 $authService = new AuthenticationService();
                 $authService->setAdapter($authAdapter);
                 $result = $authService->authenticate();
                 $this->redirect()->toRoute('user');
             }
         }
     }
     return array('id' => $id, 'user' => $user, 'form' => $form);
 }
Пример #26
0
 public function loginAction()
 {
     $userLogin = new AuthenticationService();
     if ($userLogin->hasIdentity()) {
         $identity = $userLogin->getIdentity();
         return $this->forward()->dispatch('Application\\Controller\\Index', array('action' => 'listar'));
     } else {
         $form = new Login();
         $form->get('submit')->setValue('Login');
         $messages = null;
         $request = $this->getRequest();
         if ($request->isPost()) {
             $loginFilters = new LoginValidator();
             $form->setInputFilter($loginFilters->getInputFilter());
             $form->setData($request->getPost());
             if ($form->isValid()) {
                 $data = $form->getData();
                 $sm = $this->getServiceLocator();
                 $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
                 $config = $this->getServiceLocator()->get('Config');
                 $indexAdapter = new IndexAdapter($dbAdapter, 'zml_admin', 'usr_name', 'usr_password');
                 $indexAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
                 $auth = new AuthenticationService();
                 // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
                 //$auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
                 // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
                 $result = $auth->authenticate($indexAdapter);
                 switch ($result->getCode()) {
                     case Result::FAILURE_IDENTITY_NOT_FOUND:
                         echo "prueba";
                         die;
                         break;
                     case Result::FAILURE_CREDENTIAL_INVALID:
                         echo "prueba";
                         die;
                         break;
                     case Result::SUCCESS:
                         $storage = $auth->getStorage();
                         $storage->write($indexAdapter->getResultRowObject(null, 'usr_password'));
                         $time = 1209600;
                         // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                         //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                         if ($data['rememberme']) {
                             $sessionManager = new \Zend\Session\SessionManager();
                             $sessionManager->rememberMe($time);
                         }
                         return $this->forward()->dispatch('Application\\Controller\\Index', array('action' => 'listar'));
                         break;
                     default:
                         echo "prueba";
                         die;
                         break;
                 }
                 foreach ($result->getMessages() as $message) {
                     $messages .= "{$message}\n";
                 }
             }
         }
         $viewModel = new ViewModel(array('form' => $form, 'messages' => $messages));
         $viewModel->setTerminal(true);
         return $viewModel;
     }
 }
Пример #27
0
 public function fauth($username, $pass, $table)
 {
     $sm = $this->getServiceLocator();
     $container = new Container('username');
     $dba = $sm->get($container->adapter);
     $sql = "Select Teacher_id from teacher where username='******'";
     $statement = $dba->query($sql, array(5));
     $resultSet = new ResultSet();
     $resultSet->initialize($statement);
     $tid = 0;
     foreach ($resultSet as $row) {
         $tid = $row['Teacher_id'];
     }
     $config = $this->getServiceLocator()->get('Config');
     $staticSalt = $config['static_salt'];
     if ($table == "teacher") {
         $authAdapter = new AuthAdapter($dba, $table, 'username', 'Teacher_pass', "MD5(CONCAT('{$staticSalt}', Teacher_salt))");
     } else {
         if ($table == "admin") {
             $authAdapter = new AuthAdapter($dba, $table, 'Admin_id', 'Admin_pass', "MD5(CONCAT('{$staticSalt}', Admin_salt))");
         }
     }
     $authAdapter->setIdentity($username)->setCredential($pass);
     $auth = new AuthenticationService();
     // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
     // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
     // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
     $result = $auth->authenticate($authAdapter);
     switch ($result->getCode()) {
         case Result::FAILURE_IDENTITY_NOT_FOUND:
             // do stuff for other failure
             break;
         case Result::FAILURE_CREDENTIAL_INVALID:
             // do stuff for other failure
             break;
         case Result::SUCCESS:
             if ($table == "teacher") {
                 $container->id = $tid;
                 $container->type = 1;
                 $storage = $auth->getStorage();
                 $storage->write($authAdapter->getResultRowObject(null, 'Teacher_pass'));
                 $time = 1209600;
                 // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                 //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                 $sessionManager = new \Zend\Session\SessionManager();
                 $sessionManager->rememberMe($time);
                 return $this->redirect()->toRoute('teacher', array('controller' => 'index', 'action' => 'index'));
             } else {
                 if ($table == "admin") {
                     $container->id = $username;
                     $container->type = 0;
                     $container->sub = "";
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'Admin_pass'));
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                     $sessionManager = new \Zend\Session\SessionManager();
                     $sessionManager->rememberMe($time);
                     return $this->redirect()->toRoute('admin', array('controller' => 'index', 'action' => 'index'));
                 }
             }
         default:
             // do stuff for other failure
             break;
     }
 }
Пример #28
0
 public function signinAction()
 {
     $user = $this->identity();
     $auth = new AuthenticationService();
     if (!$auth->hasIdentity()) {
         $messages = null;
         $form = new SigninForm();
         $request = $this->getRequest();
         if ($request->isPost()) {
             $signinFormFilter = new SigninUserModel();
             $form->setInputFilter($signinFormFilter->getInputFilter());
             $form->setData($request->getPost());
             if ($form->isValid()) {
                 $data = $form->getData();
                 $sm = $this->getServiceLocator();
                 $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
                 $config = $this->getServiceLocator()->get('Config');
                 $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password');
                 $authAdapter->setIdentity($data['email']);
                 $authAdapter->setCredential(md5($data['password']));
                 $result = $auth->authenticate($authAdapter);
                 switch ($result->getCode()) {
                     case Result::FAILURE_IDENTITY_NOT_FOUND:
                         break;
                     case Result::FAILURE_CREDENTIAL_INVALID:
                         break;
                     case Result::SUCCESS:
                         $storage = $auth->getStorage();
                         $storage->write($authAdapter->getResultRowObject(null, 'password'));
                         $time = 604800;
                         //7 days
                         if ($data['rememberme']) {
                             $sessionManager = new \Zend\Session\SessionManager();
                             $sessionManager->rememberMe($time);
                         }
                         return $this->redirect()->toRoute('user', array('action' => 'index'));
                     default:
                         break;
                 }
                 foreach ($result->getMessages() as $message) {
                     $messages .= "{$message}\n";
                 }
             }
         }
         return new ViewModel(array('form' => $form, 'messages' => $messages));
     } else {
         return $this->redirect()->toRoute('user', array('action' => 'index'));
     }
     //        $user_session = new \Zend\Session\Container('user');
     //        if ($user_session->email!=null) {
     //            return $this->redirect()->toRoute('user',array('action'=>'index'));
     //        }
     //        $form = new SigninForm();
     //        $item = new SigninUserModel();
     //        $request = $this->getRequest();
     //        if ($request->isPost()) {
     //            $form->setInputFilter($item->getInputFilter());
     //            $form->setData($request->getPost());
     //            if ($form->isValid()) {
     //                $item->email = $form->get('email')->getValue();
     //                $item->password = $form->get('password')->getValue();
     //                $success = $this->getTable()->signin($item);
     //                if ($success) {
     //                    $user_session = new \Zend\Session\Container('user');
     //                    $user_session->email=$success->email;
     //                    $user_session->role=$success->role;
     //                    return $this->redirect()->toRoute('user');
     //                } else {
     //                    $error='Wrong email or password';
     //                }
     //            }
     //        }
     //
     //        return array(
     //            'form'=>$form,
     //            'error'=>$error
     //        );
 }
Пример #29
0
 public function auth(User $user)
 {
     $auth = new AuthenticationService();
     $authAdapter = new DbTable($this->dbAdapter);
     $authAdapter->setTableName('user')->setIdentityColumn('username')->setCredentialColumn('upassword');
     $authAdapter->setIdentity($user->getUsername())->setCredential($user->getUpassword());
     $result = $auth->authenticate($authAdapter);
     if ($result->isValid()) {
         $storage = $auth->getStorage();
         $storage->write($authAdapter->getResultRowObject(array('userID', 'username', 'schoolID', 'type')));
         return true;
     } else {
         //             print_r($result->getMessages());
         return false;
     }
 }
 /**
  * This action is called when a user is to be authenticated by their username and password
  * 
  * @return \Zend\View\Model\ViewModel
  */
 public function authenticateAction()
 {
     $Logform = new LoginForm();
     //Gets the username
     $email = $this->request->getPost('email');
     //Get the password and encrypt it using md5
     $password = md5($this->request->getPost('password'));
     //Create a connection to the database
     $db = $this->getServiceLocator()->get('dbcon');
     if ($this->request->isPost()) {
         //Perform a check to see if username and password are not empty
         if ($email != null and $password != null) {
             //Create an instance of the Auth Adapter
             $auth = new AuthAdapter($db);
             //Set the user name
             $auth->setIdentity($email);
             //Set the password
             $auth->setCredential($password);
             //Set the Table name
             $auth->setTableName('users');
             //Set the user name colum
             $auth->setIdentityColumn('email');
             //Set the password column
             $auth->setCredentialColumn('password');
             //Authenticate the user
             $auth->authenticate();
             //If authentication is valid
             if ($auth->authenticate()->isValid()) {
                 //Convert the user credentials from an object  into an array
                 $array = get_object_vars($auth->getResultRowObject());
                 //Set the username and store it in session
                 $this->session->offsetSet('email', $array['email']);
                 $this->session->offsetSet('username', $array['username']);
                 //Set the user id and store in session
                 $this->session->offsetSet('id', $array['id']);
                 //Set the user full name and store in session
                 $this->session->offsetSet('fullname', $array['full_name']);
                 $this->AuthenticationLogger("user logged in successfully at " . date('y-m-d H:i:s'));
                 $this->ActivityLogs("user logged in successfully at " . date('Y-m-d H:i:s'));
                 //Redirect the user to the admin page
                 $this->getUrl('ekontact', 'Ekontact', 'dashboard');
             } else {
                 $msg = $this->flashMessenger()->addMessage(sprintf(" %s Invalid email or password %s", '<div class="error">', '</div>'));
                 return $this->redirect()->toRoute('authentication', array('controller' => 'Authentication', 'action' => 'login'));
             }
         } else {
             $msg = $this->flashMessenger()->addMessage(sprintf(" %s Please make sure both email and password fields are not empty %s", '<div class="error">', '</div>'));
             $this->getUrl('authentication', 'Authentication', 'login');
         }
     }
     $view = new ViewModel(array('form' => $Logform));
     $this->layout('layout/login_layout');
     return $view;
 }