Exemplo n.º 1
0
    public function fetchByFb($id, Application_Model_Usuario $data, $attr = null) {
        $select = $this->getDbTable()->select();
        if ($attr != null) {
            $select->from($this->getDbTable(), $attr);
        } else {
            $select->from($this->getDbTable());
        }
        $select->where("FB_UID = ?", $id);
        $select->limit(1,0);
        $resultSet = $this->getDbTable()->fetchAll($select);
        if (0 == count($resultSet)) {
            return false;
        }
        foreach ($resultSet as $row) {
            if ($attr == null) {
                $data->setIdUsuario($row->ID_USUARIO);
//                $data->setIdTipoMoneda($row->ID_TIPO_MONEDA);
            } else {
                foreach($attr as $a) {
                    $ta = strtolower($a);
                    $ta = split("_", $ta);
                    $method = "set";
                    foreach($ta as $pa) {
                        $method .= ucfirst($pa);
                    }
                    $data->$method($row->$a);
                }
            }
        }
    }
 public function indexAction()
 {
     Zend_Loader::loadClass('Zend_Auth');
     $authClass = Zend_Auth::getInstance();
     if ($authClass->hasIdentity()) {
         $auth = $authClass->getStorage()->read();
         $id = $auth['usuario_id'];
         require_once APPLICATION_PATH . '/forms/AlterarDados.php';
         $this->view->form = $form = new Application_Form_AlterarDados();
         $usuarioModel = new Application_Model_Usuario();
         if ($this->_request->isPost()) {
             $this->view->form->setDefaults($this->_request->getPost());
             $data = $this->view->form->getValues();
             if ($this->view->form->isValid($data)) {
                 if ($data['senha'] != '') {
                     $data['senha'] = md5($data['senha']);
                 } else {
                     unset($data['senha']);
                 }
                 unset($data['repita_senha']);
                 $usuarioModel->update($data, 'idusuario = ' . $id);
                 return $this->_helper->redirector('index');
             }
         }
         $usuario = $usuarioModel->find($id)->current();
         $this->view->form->setDefaults($usuario->toArray());
     }
 }
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     $resource = $request->getActionName();
     $privilegio = $request->getControllerName();
     $modulo = $request->getModuleName();
     $privilegio = $modulo . ':' . $privilegio;
     $storageObj = $this->_authEngine->getStorage()->read();
     $role = 'visitante';
     if ($this->_authEngine->hasIdentity()) {
         $auth = $this->_authEngine->getStorage()->read();
         $id = $auth['usuario_id'];
         $usuarioModel = new Application_Model_Usuario();
         $usuario = $usuarioModel->find($id)->current();
         $role = $usuario['tipo'];
     }
     try {
         if (!$this->_acl->has($privilegio)) {
             throw new Zend_Exception('Recurso não encontrado: ' . $privilegio);
         }
         if (!$this->_acl->isAllowed($role, $privilegio, $resource)) {
             $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
             $redirector->gotoUrlAndExit('/error/errorpermission');
         }
     } catch (Zend_Exception $e) {
         // echo $e->getMessage();
     } catch (Zend_Acl_Exception $e) {
         //  echo $e->getMessage();
     }
 }
Exemplo n.º 4
0
 public function authenticate(Zend_Auth_Adapter_Interface $adapter)
 {
     $usuarioModel = new Application_Model_Usuario();
     $contrasenia = $usuarioModel->obtenerPasswordUsuario($usuario);
     $entityUsuario = new Application_Entity_Usuario();
     $credencial = $entityUsuario->setearContrasenia($contrasenia);
     parent::setCredential($credential);
 }
 public function enderecoAction()
 {
     $busca = $this->_request->getParam('id');
     $usuarioModel = new Application_Model_Usuario();
     $user = $usuarioModel->fetchAll($usuarioModel->select()->from($usuarioModel->info(Zend_Db_Table_Abstract::NAME))->columns(array('usuario'))->where('idusuario = ?', $busca));
     $enderecoModel = new Application_Model_Endereco();
     $dados = $enderecoModel->fetchAll($enderecoModel->select()->where('usuario = ?', $user[0]['usuario']));
     $this->view->dados = $dados;
 }
function userExists($user)
{
    $usuarioModel = new Application_Model_Usuario();
    $exists = $usuarioModel->fetchRow($usuarioModel->select()->where('usuario = :usuario')->bind(array('usuario' => $user)));
    if ($exists != null) {
        return false;
    }
    return true;
}
 public static function getLoggetUser()
 {
     if (Misc::isLogged()) {
         $id = Misc::getLoggetUserId();
         $usuarioModel = new Application_Model_Usuario();
         $usuario = $usuarioModel->find($id)->current();
         return $usuario;
     }
     return null;
 }
 public function verificarInactividad()
 {
     $usuario = new Application_Model_Usuario();
     if ($usuario->getInactivo()) {
         $usuario->logout();
         return $this->_redirect('/');
     } else {
         $this->redireccionar();
     }
 }
 protected function validaPost()
 {
     $error = array();
     $usuModel = new Application_Model_Usuario($this->getRequest()->getParams());
     if (!$usuModel->getLogin()) {
         $error['login'] = '******';
     }
     if (!$usuModel->getPassword()) {
         $error['password'] = '******';
     }
     return $error;
 }
Exemplo n.º 10
0
 public function registrarAction()
 {
     $this->_helper->layout->setLayout('layout_login');
     $form = new Application_Form_Registrar();
     if ($this->_request->isPost() && $form->isValid($this->_request->getParams())) {
         $_usuario = new Application_Model_Usuario();
         $usuario = array('login' => $form->getValue('login'), 'pwd' => md5($form->getValue('pwd')), 'nombre' => $form->getValue('nombre'), 'activo' => 1);
         $_usuario->insert($usuario);
         $this->_helper->FlashMessenger('Usuario registrado');
         $this->_redirect('/index/login');
     }
     $this->view->form = $form;
 }
Exemplo n.º 11
0
    public function saveAction() {
        $this->_helper->layout->disableLayout();
        $this->me = $this->fb->api('/me','GET');
        if($this->me) {
            $authNamespace = new Zend_Session_Namespace('Zend_Auth');
            $authNamespace->id = $this->me["id"];
            $authNamespace->name = $this->me["name"];
            $data = new Application_Model_Usuario();
            $data->setNomUsuario($this->me["first_name"]);
            $data->setApeUsuario($this->me["last_name"]);
            $data->setEmaUsuario($this->me["email"]);
            $data->setFbAccessToken($this->fb->getAccessToken());
            $data->setFbSecret($this->fb->getApiSecret());
            $data->setFbUid($this->me["id"]);
            $MP = new Application_Model_UsuarioMP();
            $nuevo = $MP->save($data);
            $this->me["id_usuario"] = $nuevo->ID_USUARIO;
            $authNamespace->id_usuario = $nuevo->ID_USUARIO;
            Zend_Registry::getInstance()->set('me', $this->me);
//            print_r($this->me);
            if($nuevo->NUEVO) {
                $proy = new Application_Model_Proyecto();
                $proy->setNomProyecto("Principal");
                $proy->setDescProyecto("Proyecto principal");
                $proy->setIdTipoMoneda(1);
                $proy->setEstadoProyecto(0);
                $MPProy = new Application_Model_ProyectoMP();
                $idPro = $MPProy->save($proy);
                
                $usPro = new Application_Model_UsuarioProyecto();
                $usPro->setIdUsuario($nuevo->ID_USUARIO);
                $usPro->setIdProyecto($idPro);
                $usPro->setIdNivelAcceso(1);
                $MPUsPro = new Application_Model_UsuarioProyectoMP();
                $MPUsPro->save($usPro);
                
                $usCat = new Application_Model_Categoria();
                $usCat->setCategoria("Sin categoria");
                $usCat->setIdProyecto($idPro);
                $MPCat = new Application_Model_CategoriaMP();
                $MPCat->save($usCat);
                
                try {
                    $this->fb->api('/me/feed', 'POST', array(
                        'link' => 'www.melogaste.com',
                        'message' => 'Estoy usando Me lo Gaste! para registrar mis finanzas, tu puedes usarlo tambien, es gratis!',
                        'icon' => 'http://www.melogaste.com/img/money_bag_ico.png',
                        'picture' => 'http://www.melogaste.com/img/money_bag.png'
                    ));
                } catch(FacebookApiException $e) {}
            }
            $this->_redirect("/Index");
        } else {
            $this->_redirect("/Log");
        }
    }
Exemplo n.º 12
0
 public function validaCpfAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     header('Cache-Control: no-cache');
     header('Content-type: application/xml; charset="utf-8"', true);
     $db = Zend_Registry::get("db");
     $cpf = $_POST["cpf"];
     $cpf = str_replace(".", "", $cpf);
     $cpf = str_replace("-", "", $cpf);
     $user_data = new Application_Model_Usuario();
     $cons = $db->fetchAll($user_data->select()->where('cpf_cnpj = ?', $cpf));
     if ($cons) {
         $validcpf = 0;
     } else {
         $validcpf = 1;
     }
     echo $this->view->json($validcpf);
 }
Exemplo n.º 13
0
 public function redefinirAction()
 {
     $token = $this->_getParam('token');
     $modelAlteracaoSenha = new Application_Model_AlteracaoSenha();
     $alteracaoSenha = $modelAlteracaoSenha->find($token);
     if ($alteracaoSenha) {
         $alteracaoSenha = $alteracaoSenha[0];
         if ($alteracaoSenha['tas_dataalteracao']) {
             $this->view->mensagem = "Solicitação já atendida.";
         } else {
             $modelUsuario = new Application_Model_Usuario();
             $usuario = $modelUsuario->find($alteracaoSenha['tu_id']);
             $this->view->login = $usuario['tl_login'];
             $this->view->token = $token;
         }
     } else {
         $this->view->mensagem = "Token não cadastrado.";
     }
 }
Exemplo n.º 14
0
 function autentificateUser($usuario, $password)
 {
     $entityUsuario = new Application_Entity_Usuario();
     $auth = Zend_Auth::getInstance();
     $adapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('db'), 'usuario', 'Login', 'Password');
     $adapter->setIdentity($usuario);
     $usuarioModel = new Application_Model_Usuario();
     $contrasenia = $usuarioModel->obtenerPasswordUsuario($usuario);
     $valueSegurity = $entityUsuario->obtenerValorSeguridadContrasenia($contrasenia);
     $password = $valueSegurity . $entityUsuario->setearContrasenia($entityUsuario->encriptaContrasenia($password));
     $adapter->setCredential($password);
     $result = $auth->authenticate($adapter);
     if ($result->isValid()) {
         $data = $adapter->getResultRowObject(null, 'Password');
         $auth->getStorage()->write($data);
         return TRUE;
     } else {
         return FALSE;
     }
 }
Exemplo n.º 15
0
 /**
  * @param $nombre   Nombre del usuario
  * @param $nombre   Nombre del usuario
  * @param $nombre   Nombre del usuario
  * @return          lnsdlk
  */
 public function validarLoginAction()
 {
     if ($this->_request->isPost()) {
         $_usuario = new Application_Model_Usuario();
         //            $form = new Application_Form_Registrar();
         //            $elementLogin = $form->getElement('login');
         //            if ($elementLogin->isValid($this->_getParam('login'))){
         //            }
         $login = $this->_getParam('login');
         if ($_usuario->disponibleLogin2($login)) {
             $msg = 'OK';
         } else {
             $msg = 'ERROR';
         }
     } else {
         $msg = 'ERROR';
         $login = '';
     }
     $datos = array('msg' => $msg, 'login' => $login);
     $json = Zend_Json::encode($datos);
     $this->getResponse()->appendBody($json);
 }
 public function indexAction()
 {
     Zend_Loader::loadClass('Zend_Auth');
     $authClass = Zend_Auth::getInstance();
     $auth = $authClass->getStorage()->read();
     if (!$authClass->hasIdentity()) {
         if ($this->_request->isPost()) {
             $data = $this->_request->getPost();
             if ($data['usuario']) {
                 $zendDb = Zend_Db_Table_Abstract::getDefaultAdapter();
                 $authAdapter = new Zend_Auth_Adapter_DbTable($zendDb, 'usuario', 'usuario', 'senha', 'MD5(?)');
                 $authAdapter->setIdentity($data['usuario']);
                 $authAdapter->setCredential($data['senha']);
                 $auth = $authAdapter->authenticate();
                 if ($auth->isValid()) {
                     $authData = $authAdapter->getResultRowObject();
                     $authClass->getStorage()->write(array('usuario_id' => $authData->idusuario));
                     $user = $data['usuario'];
                     $usuarioModel = new Application_Model_Usuario();
                     $row = $usuarioModel->fetchRow($usuarioModel->select()->where('usuario = ?', $user));
                     if ($row->tipo == 'administrador') {
                         return $this->_helper->redirector('index', 'admin');
                     } else {
                         if ($row->completo == 0) {
                             return $this->_helper->redirector('index', 'cliente');
                         } else {
                             return $this->_helper->redirector('index', 'index');
                         }
                     }
                 } else {
                     $this->view->priorityMessenger('Login inválido!', 'Mensagem');
                 }
             }
         }
     }
     return $this->_helper->redirector('index', 'index');
 }
Exemplo n.º 17
0
 public function resetAction()
 {
     // insertando el dump inicial:
     $_conf = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini');
     $env = APPLICATION_ENV;
     $db_name = $_conf->{$env}->resources->db->params->dbname;
     $sql_file = APPLICATION_PATH . '/../docs/' . $db_name . '.sql';
     $sql_string = file_get_contents($sql_file);
     $db = Zend_Db_Table::getDefaultAdapter();
     $db->query('DROP DATABASE IF EXISTS ' . $db_name);
     $db->query($sql_string);
     //Ubigeos
     $db->query(file_get_contents(APPLICATION_PATH . '/../docs/ubigeos_peru.sql'));
     // insertando usuarios
     $_u = new Application_Model_Usuario();
     $pwd = md5('1234');
     foreach (range(1, rand(150, 250)) as $i) {
         $username = '******' . substr(md5(rand(100, 10000)), 24);
         $u = array('login' => $username, 'pwd' => $pwd, 'nombre' => $username, 'activo' => rand(0, 1));
         $_u->insert($u);
     }
     $this->_helper->FlashMessenger('DB restaurada');
     $this->_redirect('/');
 }
Exemplo n.º 18
0
 public static function login($login, $senha)
 {
     $dbAdapter = Zend_Db_Table::getDefaultAdapter();
     //Inicia o adaptador Zend_Auth para banco de dados
     $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
     $authAdapter->setTableName('TB_OPERADOR')->setIdentityColumn('DS_LOGIN')->setCredentialColumn('DS_SENHA')->setCredentialTreatment('SHA1(?)');
     Zend_Registry::get('logger')->log("authh", Zend_Log::INFO);
     //Define os dados para processar o login
     $authAdapter->setIdentity($login)->setCredential($senha);
     //Faz inner join dos dados do perfil no SELECT do Auth_Adapter
     $select = $authAdapter->getDbSelect();
     $select->join(array('p' => 'perfil'), 'p.id_perfil = TB_OPERADOR.FK_PERFIL', array('nome_perfil' => 'nome'))->joinLeft(array('a' => 'arquivo'), 'a.id_arquivo = TB_OPERADOR.FK_ARQUIVO', array('nome_imagem' => 'nome'));
     //Efetua o login
     $auth = Zend_Auth::getInstance();
     //Zend_Registry::get('logger')->log($select, Zend_Log::INFO);
     $result = $auth->authenticate($authAdapter);
     //Zend_Registry::get('logger')->log($result, Zend_Log::INFO);
     Zend_Registry::get('logger')->log("antes if login isValid", Zend_Log::INFO);
     //Verifica se o login foi efetuado com sucesso
     if ($result->isValid()) {
         //Recupera o objeto do usuário, sem a senha
         $info = $authAdapter->getResultRowObject(null, 'DS_SENHA');
         $usuario = new Application_Model_Usuario();
         //$usuario->setFullName( $info->nome_completo );
         $usuario->setUserName($info->DS_LOGIN);
         $usuario->setFKPerfil($info->FK_PERFIL);
         $usuario->setId($info->ID_OPERADOR);
         $usuario->setRoleId($info->nome_perfil);
         $usuario->setImagem($info->nome_imagem);
         //Zend_Registry::get('logger')->log("papel", Zend_Log::INFO);
         //Zend_Registry::get('logger')->log($usuario, Zend_Log::INFO);
         $storage = $auth->getStorage();
         $storage->write($usuario);
         return true;
     }
     throw new Exception('Usuário ou senha incorreto');
 }
Exemplo n.º 19
0
 public function buscardniusuarioAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     $usunombre = $this->getRequest()->getParam('usudni');
     $usuario = new Application_Model_Usuario();
     $result = $usuario->buscardniusuario($usunombre);
     if ($result == true) {
         echo "existe";
     } else {
         echo "";
     }
 }
 public function logoutAction()
 {
     $usuario = new Application_Model_Usuario();
     $usuario->logout();
     return $this->_redirect('/');
 }
    public function finalizarAction()
    {
        Zend_Loader::loadClass('Zend_Auth');
        $authClass = Zend_Auth::getInstance();
        if ($authClass->hasIdentity()) {
            $auth = $authClass->getStorage()->read();
            $idx = $auth['usuario_id'];
            $usuarioModel = new Application_Model_Usuario();
            $dados = 0;
            $dadosUsuario = $usuarioModel->fetchAll($usuarioModel->select()->from($usuarioModel->info(Zend_Db_Table_Abstract::NAME))->columns(array('usuario'))->where('idusuario = ?', $idx));
            $dados = $dadosUsuario[0]['usuario'];
            $contatoModel = new Application_Model_Contato();
            $dadosContato = $contatoModel->fetchAll($contatoModel->select()->from($contatoModel->info(Zend_Db_Table_Abstract::NAME))->columns(array('completo'))->where('usuario = ?', $dados));
            $this->view->dadosContato = $dadosContato;
        }
        $categoriaModel = new Application_Model_Categoria();
        $nome_categorias = $categoriaModel->fetchAll($categoriaModel->select()->from($categoriaModel->info(Zend_Db_Table_Abstract::NAME))->columns(array('nome_categoria')));
        $this->view->categorias = $nome_categorias;
        $confirmar = $this->_request->getParam('confirmar');
        if (isset($confirmar)) {
            if ($confirmar == 1) {
                $sessao = new Zend_Session_Namespace('SESSAO_CARRINHO');
                Zend_Loader::loadClass('Zend_Auth');
                $authClass = Zend_Auth::getInstance();
                if ($authClass->hasIdentity()) {
                    $auth = $authClass->getStorage()->read();
                    $id = $auth['usuario_id'];
                }
                /// function to generate random number ///////////////
                function random_generator($digits)
                {
                    srand((double) microtime() * 10000000);
                    //Array of alphabets
                    $input = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                    $random_generator = "";
                    // Initialize the string to store random numbers
                    for ($i = 1; $i < $digits + 1; $i++) {
                        // Loop the number of times of required digits
                        if (rand(1, 2) == 1) {
                            // to decide the digit should be numeric or alphabet
                            // Add one random alphabet
                            $rand_index = array_rand($input);
                            $random_generator .= $input[$rand_index];
                            // One char is added
                        } else {
                            // Add one numeric digit between 1 and 10
                            $random_generator .= rand(1, 10);
                            // one number is added
                        }
                        // end of if else
                    }
                    // end of for loop
                    return $random_generator;
                }
                // end of function
                $key = random_generator(10);
                $key = md5($key);
                $date = date_create();
                $pedido = array();
                $pedido['cliente'] = $auth['usuario_id'];
                $pedido['data'] = date_format($date, 'c');
                $pedido['secure'] = $key;
                $pedido['valor'] = str_replace(array(',', '.'), '', $sessao->total);
                $pedidoModel = new Application_Model_Pedido();
                $id = $pedidoModel->insert($pedido);
                $pedido_id = $pedidoModel->fetchAll($pedidoModel->select()->where('secure = ?', $key));
                $pedido_xid = $pedido_id[0]['id_pedido'];
                $prodpedModel = new Application_Model_ProdutoPedido();
                $addModel = new Application_Model_Adicionais();
                if (isset($sessao->produtos)) {
                    foreach ($sessao->produtos as $posicao => $id) {
                        $chave = random_generator(10);
                        $chave = md5($chave);
                        $prod = array();
                        $prod['id_pedido'] = $pedido_xid;
                        $prod['id_produto'] = $id;
                        $prod['id_adicionais'] = $chave;
                        $id = $prodpedModel->insert($prod);
                        if (isset($sessao->quantidades[$posicao])) {
                            foreach ($sessao->quantidades[$posicao] as $ingred => $quanti) {
                                $adi = array();
                                $adi['id_adicionais'] = $chave;
                                $adi['id_adicional'] = $ingred;
                                $adi['quantidade'] = $quanti;
                                $id = $addModel->insert($adi);
                            }
                        }
                    }
                }
                $sessao->produtos = null;
                $sessao->quantidades = null;
                $sessao->total = null;
                $sessao->ingred = null;
                $email = $dadosContato[0]['email'];
                $data = '<html><body><table>
					<tr><td>Online Thru informa: Pedido recebido, valor R$ ' . number_format($pedido['valor'] / 100, 2, ',', '.') . '</td></tr>
					</table></body></html>';
                // Using the ini_set()
                ini_set("SMTP", "localhost");
                ini_set("sendmail_from", "*****@*****.**");
                ini_set("smtp_port", "587");
                $mail = new Zend_Mail('UTF-8', 'ISO-8859-8');
                $mail->setBodyHtml($data)->setFrom('*****@*****.**', 'Online Thru')->addTo($email, 'Online Thru')->setSubject('Online Thru - Pedido')->send();
                $this->view->aviso = "Pedido enviado com sucesso!";
            }
        } else {
            $sessao = new Zend_Session_Namespace('SESSAO_CARRINHO');
            $this->view->produtos = $sessao->produtos;
            if (!isset($sessao->ingred)) {
                $sessao->ingred = array();
            }
            if ($this->_request->isPost()) {
                $sessao->ingred = $this->_request->getPost();
                foreach ($sessao->ingred as $key => $value) {
                    $mystring = $key;
                    $findme = 'q';
                    $pos = strpos($mystring, $findme);
                    if ($pos === false) {
                        $mystring = $key;
                        $find = '-';
                        $posi = strpos($mystring, $find);
                        $chave = substr($key, 0, $posi);
                        $ingr = substr($key, $posi + 1, strlen($key));
                        $sessao->ingredientes[$chave][$ingr] = $value;
                    } else {
                        $key = str_replace('q-', '', $key);
                        $mystring = $key;
                        $find = '-';
                        $posi = strpos($mystring, $find);
                        $chave = substr($key, 0, $posi);
                        $ingr = substr($key, $posi + 1, strlen($key));
                        $sessao->quantidades[$chave][$ingr] = $value;
                    }
                    $idp = $sessao->produtos[$chave]['id_produto'];
                    $ingredModel = new Application_Model_Relacionamentos();
                    $nome_ingred = $ingredModel->fetchAll($ingredModel->select()->from($ingredModel->info(Zend_Db_Table_Abstract::NAME))->columns(array('qtd_padrao'))->where('id_produto = ?', $idp)->where('id_ingrediente = ?', $ingr));
                    if (isset($nome_ingred[0]['qtd_padrao'])) {
                        $padrao[$idp][$ingr] = $nome_ingred[0]['qtd_padrao'];
                    }
                }
            }
            if (isset($sessao->produtos) && sizeof($sessao->produtos) > 0) {
                if (isset($padrao)) {
                    $this->view->padrao = $padrao;
                }
                if (isset($sessao->quantidades)) {
                    $this->view->quantidades = $sessao->quantidades;
                }
                if (isset($sessao->ingredientes)) {
                    $this->view->ingredientes = $sessao->ingredientes;
                }
                if (isset($sessao->ingred)) {
                    $this->view->data = $sessao->ingred;
                }
            }
        }
    }
Exemplo n.º 22
0
 public static function login($login, $senha)
 {
     $dbAdapter = Zend_Db_Table::getDefaultAdapter();
     //Inicia o adaptador Zend_Auth para banco de dados
     $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
     $authAdapter->setTableName('usuario_login')->setIdentityColumn('login')->setCredentialColumn('senha')->setCredentialTreatment('SHA1(?)');
     //Define os dados para processar o login
     $authAdapter->setIdentity($login)->setCredential($senha);
     //Faz inner join dos dados do perfil no SELECT do Auth_Adapter
     $select = $authAdapter->getDbSelect();
     $select->join(array('u' => 'usuario'), 'u.id_usuario = usuario_login.id_usuario', array('nome' => 'CONCAT(u.nome," ",u.sobrenome )', 'u.tipo'));
     //Efetua o login
     $auth = Zend_Auth::getInstance();
     $result = $auth->authenticate($authAdapter);
     //Verifica se o login foi efetuado com sucesso
     if ($result->isValid()) {
         //Recupera o objeto do usu�rio, sem a senha
         $info = $authAdapter->getResultRowObject(null, 'senha');
         $usuario = new Application_Model_Usuario();
         $usuario->setId($info->id_usuario);
         $usuario->setFullName($info->nome);
         $usuario->setUserName($info->login);
         $usuario->setEmail($info->email);
         $usuario->setTipo($info->tipo);
         switch ($info->tipo) {
             case '0':
                 $usuario->setRoleId("admin");
                 break;
             case '1':
                 $usuario->setRoleId("user");
                 break;
             case '2':
                 $usuario->setRoleId("user");
                 break;
         }
         $storage = $auth->getStorage();
         $storage->write($usuario);
         $authNamespace = new Zend_Session_Namespace('Zend_Auth');
         $authNamespace->user = $usuario;
         return true;
     } else {
         $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
         $authAdapter->setTableName('usuario_login')->setIdentityColumn('email')->setCredentialColumn('senha')->setCredentialTreatment('SHA1(?)');
         //Define os dados para processar o login
         $authAdapter->setIdentity($login)->setCredential($senha);
         //Faz inner join dos dados do perfil no SELECT do Auth_Adapter
         $select = $authAdapter->getDbSelect();
         $select->join(array('u' => 'usuario'), 'u.id_usuario = usuario_login.id_usuario', array('nome' => 'CONCAT(u.nome," ",u.sobrenome )', 'u.tipo'));
         //Efetua o login
         $auth = Zend_Auth::getInstance();
         $result = $auth->authenticate($authAdapter);
         //Verifica se o login foi efetuado com sucesso
         if ($result->isValid()) {
             //Recupera o objeto do usu�rio, sem a senha
             $info = $authAdapter->getResultRowObject(null, 'senha');
             $usuario = new Application_Model_Usuario();
             $usuario->setFullName($info->nome);
             $usuario->setUserName($info->login);
             $usuario->setEmail($info->email);
             $usuario->setTipo($info->tipo);
             switch ($info->tipo) {
                 case '0':
                     $usuario->setRoleId("admin");
                     break;
                 case '1':
                     $usuario->setRoleId("user");
                     break;
                 case '2':
                     $usuario->setRoleId("user");
                     break;
             }
             $storage = $auth->getStorage();
             $storage->write($usuario);
             $authNamespace = new Zend_Session_Namespace('Zend_Auth');
             $authNamespace->user = $usuario;
             return true;
         }
     }
     throw new Exception('<div id="erroLogin">Nome de usuário ou senha inválida</div>');
 }
 public function editarAction()
 {
     Zend_Loader::loadClass('Zend_Auth');
     $authClass = Zend_Auth::getInstance();
     if ($authClass->hasIdentity()) {
         $auth = $authClass->getStorage()->read();
         $id = $auth['usuario_id'];
         $usuarioModel = new Application_Model_Usuario();
         $usuario = $usuarioModel->find($id)->current();
     }
     if (isset($usuario)) {
         //$user = $usuario['usuario'];
         $user = $auth['usuario_id'];
         $enderecoModel = new Application_Model_Endereco();
         $row = $enderecoModel->fetchRow($enderecoModel->select()->where('usuario = ?', $user));
         if ($row->completo = '0') {
             $this->view->endereco = '1';
         } else {
             $this->view->endereco = '0';
         }
         $contatoModel = new Application_Model_Contato();
         $rowdois = $contatoModel->fetchRow($contatoModel->select()->where('usuario = ?', $user));
         if ($rowdois->completo = '0') {
             $this->view->contato = '1';
         } else {
             $this->view->contato = '0';
         }
     }
 }