Commit 3899599d1e3b0e29f4626e77f35515c42ab000fb
1 parent
f0337155
Exists in
master
Implementado recuperação de senha do usuário / refatorado lógica de login, para evitar sql injection
Showing
11 changed files
with
1447 additions
and
288 deletions
Show diff stats
ieducar/intranet/include/clsControlador.inc.php
| 1 | -<?php | |
| 2 | - | |
| 3 | -/* | |
| 4 | - * i-Educar - Sistema de gestão escolar | |
| 5 | - * | |
| 6 | - * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | - * <ctima@itajai.sc.gov.br> | |
| 8 | - * | |
| 9 | - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | - * qualquer versão posterior. | |
| 13 | - * | |
| 14 | - * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | - * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | - * do GNU para mais detalhes. | |
| 18 | - * | |
| 19 | - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | - * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | - */ | |
| 23 | - | |
| 24 | -require_once 'include/clsBanco.inc.php'; | |
| 25 | - | |
| 26 | - | |
| 27 | -/** | |
| 28 | - * clsControlador class. | |
| 29 | - * | |
| 30 | - * @author Prefeitura Municipal de Itajaí <ctima@itajai.sc.gov.br> | |
| 31 | - * @license http://creativecommons.org/licenses/GPL/2.0/legalcode.pt CC GNU GPL | |
| 32 | - * @package Core | |
| 33 | - * @since Classe disponível desde a versão 1.0.0 | |
| 34 | - * @version $Id$ | |
| 35 | - */ | |
| 36 | -class clsControlador | |
| 37 | -{ | |
| 38 | - | |
| 39 | - /** | |
| 40 | - * @var boolean | |
| 41 | - */ | |
| 42 | - public $logado; | |
| 43 | - | |
| 44 | - /** | |
| 45 | - * @var string | |
| 46 | - */ | |
| 47 | - public $erroMsg; | |
| 48 | - | |
| 49 | - | |
| 50 | - /** | |
| 51 | - * Construtor. | |
| 52 | - */ | |
| 53 | - public function clsControlador() | |
| 54 | - { | |
| 55 | - @session_set_cookie_params(1200); | |
| 56 | - @session_start(); | |
| 57 | - | |
| 58 | - if ('logado' == $_SESSION['itj_controle']) { | |
| 59 | - $this->logado = TRUE; | |
| 60 | - } | |
| 61 | - else { | |
| 62 | - $this->logado = FALSE; | |
| 63 | - } | |
| 64 | - | |
| 65 | - // Controle dos menus | |
| 66 | - if (isset($_GET['mudamenu']) && isset($_GET['categoria']) && isset($_GET['acao'])) | |
| 67 | - { | |
| 68 | - if ($_GET['acao']) { | |
| 69 | - $_SESSION['menu_opt'][$_GET['categoria']] = 1; | |
| 70 | - $_SESSION['menu_atual'] = $_GET['categoria']; | |
| 71 | - } | |
| 72 | - else { | |
| 73 | - // Está apagando variável session com o índice dado por $_GET | |
| 74 | - unset($_SESSION['menu_opt'][$_GET['categoria']]); | |
| 75 | - if ($_SESSION['menu_atual'] == $_GET['categoria']) { | |
| 76 | - unset($_SESSION['menu_atual']); | |
| 77 | - } | |
| 78 | - } | |
| 79 | - | |
| 80 | - $db = new clsBanco(); | |
| 81 | - if (isset($_SESSION['id_pessoa'])) { | |
| 82 | - $db->Consulta("UPDATE funcionario SET opcao_menu = '" . serialize( $_SESSION['menu_opt'] ) . "' WHERE ref_cod_pessoa_fj = '" . $_SESSION['id_pessoa'] . "'"); | |
| 83 | - } | |
| 84 | - } | |
| 85 | - | |
| 86 | - session_write_close(); | |
| 87 | - } | |
| 88 | - | |
| 89 | - /** | |
| 90 | - * Retorna TRUE para usuário logado | |
| 91 | - * @return boolean | |
| 92 | - */ | |
| 93 | - public function Logado() | |
| 94 | - { | |
| 95 | - return $this->logado; | |
| 96 | - } | |
| 97 | - | |
| 98 | - /** | |
| 99 | - * Faz o login do usuário. | |
| 100 | - * @param mixed $acao | |
| 101 | - */ | |
| 102 | - public function Logar($acao) | |
| 103 | - { | |
| 104 | - if ($acao) | |
| 105 | - { | |
| 106 | - $login = @$_POST['login']; | |
| 107 | - $senha = md5(@$_POST['senha']); | |
| 108 | - $db = new clsBanco(); | |
| 109 | - | |
| 110 | - $db->Consulta("SELECT ref_cod_pessoa_fj FROM funcionario WHERE matricula = '{$login}'"); | |
| 111 | - if ($db->ProximoRegistro()) | |
| 112 | - { | |
| 113 | - list($idpes) = $db->Tupla(); | |
| 114 | - | |
| 115 | - // Padrão: meia hora atrás | |
| 116 | - $intervalo = date("Y-m-d H:i", time() - (60 * 1 )); | |
| 117 | - | |
| 118 | - // Se o último login bem sucedido foi em menos de meia hora, conta somente dali para a frente | |
| 119 | - $db->consulta("SELECT data_hora FROM acesso WHERE cod_pessoa = '{$idpes}' AND data_hora > '{$intervalo}' AND sucesso = 't' ORDER BY data_hora DESC LIMIT 1" ); | |
| 120 | - if ($db->Num_Linhas()) { | |
| 121 | - $db->ProximoRegistro(); | |
| 122 | - list($intervalo) = $db->Tupla(); | |
| 123 | - } | |
| 124 | - | |
| 125 | - // Trava usuário se tentar login mais de 5 vezes | |
| 126 | - $tentativas = $db->CampoUnico("SELECT COUNT(0) FROM acesso WHERE cod_pessoa = '{$idpes}' AND data_hora > '{$intervalo}' AND sucesso = 'f'" ); | |
| 127 | - if ($tentativas > 5) | |
| 128 | - { | |
| 129 | - $hora_ultima_tentativa = $db->CampoUnico("SELECT data_hora FROM acesso WHERE cod_pessoa = '{$idpes}' ORDER BY data_hora DESC LIMIT 1 OFFSET 4" ); | |
| 130 | - $hora_ultima_tentativa = explode(".",$hora_ultima_tentativa); | |
| 131 | - $hora_ultima_tentativa = $hora_ultima_tentativa[0]; | |
| 132 | - | |
| 133 | - $data_libera = date("d/m/Y H:i", | |
| 134 | - strtotime($hora_ultima_tentativa) + (60 * 30)); | |
| 135 | - | |
| 136 | - die("<html><body></body><script>alert('Houveram mais de 5 tentativas frustradas de acessar a sua conta na última meia hora.\\nPor segurança, sua conta ficará interditada até: {$data_libera}');document.location.href='/intranet';</script></html>"); | |
| 137 | - } | |
| 138 | - | |
| 139 | - $db->Consulta( "SELECT ref_cod_pessoa_fj, opcao_menu, ativo, tempo_expira_senha, tempo_expira_conta, data_troca_senha, data_reativa_conta, proibido, ref_cod_setor_new, tipo_menu FROM funcionario WHERE ref_cod_pessoa_fj = '{$idpes}' AND senha = '{$senha}'" ); | |
| 140 | - if ($db->ProximoRegistro()) | |
| 141 | - { | |
| 142 | - list($id_pessoa, $opcaomenu, $ativo, $tempo_senha, | |
| 143 | - $tempo_conta, $data_senha, $data_conta, $proibido, | |
| 144 | - $setor_new, $tipo_menu) = $db->Tupla(); | |
| 145 | - | |
| 146 | - if (!$proibido) | |
| 147 | - { | |
| 148 | - if ($ativo) | |
| 149 | - { | |
| 150 | - // Usuário ativo, verifica se a conta expirou | |
| 151 | - $expirada = FALSE; | |
| 152 | - if (!empty($tempo_conta) && !empty($data_conta)) | |
| 153 | - { | |
| 154 | - if (time() - strtotime($data_conta) > $tempo_conta * 60 * 60 * 24) { | |
| 155 | - // Conta expirada | |
| 156 | - $db->Consulta("UPDATE funcionario SET ativo='0' WHERE ref_cod_pessoa_fj = '$id_pessoa'"); | |
| 157 | - die("<html><body></body><script>alert( 'Sua conta na intranet expirou.\nContacte um administrador para reativa-la.' );document.location.href='/intranet';</script></html>"); | |
| 158 | - } | |
| 159 | - } | |
| 160 | - | |
| 161 | - // Vendo se a senha não expirou | |
| 162 | - if (!empty($tempo_senha) && ! empty($data_senha)) { | |
| 163 | - if (time() - strtotime($data_senha) > $tempo_senha * 60 * 60 * 24) { | |
| 164 | - // Senha expirada, pede que mude a senha | |
| 165 | - die("<html><body><form id='reenvio' name='reenvio' action='usuario_trocasenha.php' method='POST'><input type='hidden' name='cod_pessoa' value='{$id_pessoa}'></form></body><script>document.getElementById('reenvio').submit();</script></html>"); | |
| 166 | - } | |
| 167 | - } | |
| 168 | - | |
| 169 | - // Pega o endereço IP do host, primeiro com HTTP_X_FORWARDED_FOR (para pegar o IP real | |
| 170 | - // caso o host esteja atrás de um proxy) | |
| 171 | - if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') { | |
| 172 | - // No caso de múltiplos IPs, pega o último da lista | |
| 173 | - $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); | |
| 174 | - $ip_maquina = trim(array_pop($ip)); | |
| 175 | - } | |
| 176 | - else { | |
| 177 | - $ip_maquina = $_SERVER['REMOTE_ADDR']; | |
| 178 | - } | |
| 179 | - | |
| 180 | - $sql = "SELECT ip_logado, data_login FROM funcionario WHERE ref_cod_pessoa_fj = {$id_pessoa}"; | |
| 181 | - $db2 = new clsBanco(); | |
| 182 | - $db2->Consulta($sql); | |
| 183 | - while ($db2->ProximoRegistro()) | |
| 184 | - { | |
| 185 | - list($ip_banco, $data_login) = $db2->Tupla(); | |
| 186 | - if ($ip_banco) | |
| 187 | - { | |
| 188 | - if (abs(time() - strftime("now") - strtotime($data_login)) <= 10 * 60 | |
| 189 | - && $ip_banco != $ip_maquina) { | |
| 190 | - die("<html><body></body><script>alert('Conta já em uso.\\nTente novamente mais tarde');document.location.href='/intranet';</script></html>"); | |
| 191 | - } | |
| 192 | - else { | |
| 193 | - $sql = "UPDATE funcionario SET data_login = NOW() WHERE ref_cod_pessoa_fj = {$id_pessoa}"; | |
| 194 | - $db2->Consulta($sql); | |
| 195 | - } | |
| 196 | - } | |
| 197 | - else { | |
| 198 | - $sql = "UPDATE funcionario SET ip_logado = '{$ip_maquina}', data_login = NOW() WHERE ref_cod_pessoa_fj = {$id_pessoa}"; | |
| 199 | - $db2->Consulta($sql); | |
| 200 | - } | |
| 201 | - } | |
| 202 | - | |
| 203 | - // Login do usuário, grava dados na sessão | |
| 204 | - @session_start(); | |
| 205 | - $_SESSION = array(); | |
| 206 | - $_SESSION['itj_controle'] = 'logado'; | |
| 207 | - $_SESSION['id_pessoa'] = $id_pessoa; | |
| 208 | - $_SESSION['pessoa_setor'] = $setor_new; | |
| 209 | - $_SESSION['menu_opt'] = unserialize( $opcaomenu ); | |
| 210 | - $_SESSION['tipo_menu'] = $tipo_menu; | |
| 211 | - @session_write_close(); | |
| 212 | - | |
| 213 | - $this->logado = TRUE; | |
| 214 | - } | |
| 215 | - else | |
| 216 | - { | |
| 217 | - if (!empty($tempo_conta) && !empty($data_conta)) | |
| 218 | - { | |
| 219 | - if (time() - strtotime( $data_conta ) > $tempo_conta * 60 * 60 * 24) { | |
| 220 | - $this->erroMsg = "Sua conta expirou. Contacte o administrador para reativá-la."; | |
| 221 | - $expirada = 1; | |
| 222 | - } | |
| 223 | - else { | |
| 224 | - $this->erroMsg = "Sua conta não está ativa. Use a opção 'Nunca usei a intrenet'."; | |
| 225 | - $expirada = 0; | |
| 226 | - } | |
| 227 | - } | |
| 228 | - } | |
| 229 | - } | |
| 230 | - else | |
| 231 | - { | |
| 232 | - $this->erroMsg = "Impossível realizar login."; | |
| 233 | - $this->logado = FALSE; | |
| 234 | - } | |
| 235 | - } | |
| 236 | - else | |
| 237 | - { | |
| 238 | - if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') { | |
| 239 | - // No caso de múltiplos IPs, pega o último da lista | |
| 240 | - $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); | |
| 241 | - $ip_de_rede = trim(array_pop($ip)); | |
| 242 | - } | |
| 243 | - | |
| 244 | - $ip = empty($_SERVER['REMOTE_ADDR']) ? 'NULL' : $_SERVER['REMOTE_ADDR']; | |
| 245 | - $ip_de_rede = empty($ip_de_rede) ? 'NULL' : $ip_de_rede; | |
| 246 | - | |
| 247 | - $db->Consulta("INSERT INTO acesso (data_hora, ip_externo, ip_interno, cod_pessoa, sucesso) VALUES (now(), '{$ip}', '{$ip_de_rede}', {$idpes}, 'f')"); | |
| 248 | - | |
| 249 | - $this->erroMsg = 'Login ou Senha incorretos.'; | |
| 250 | - $this->logado = FALSE; | |
| 251 | - } | |
| 252 | - } | |
| 253 | - else { | |
| 254 | - $this->erroMsg = "Login ou Senha incorretos."; | |
| 255 | - $this->logado = FALSE; | |
| 256 | - } | |
| 257 | - } | |
| 258 | - else | |
| 259 | - { | |
| 260 | - $arquivo = 'templates/nvp_htmlloginintranet.tpl'; | |
| 261 | - $ptrTpl = fopen($arquivo, "r"); | |
| 262 | - $strArquivo = fread($ptrTpl, filesize($arquivo)); | |
| 263 | - | |
| 264 | - if ($this->erroMsg) { | |
| 265 | - $strArquivo = str_replace( "<!-- #&ERROLOGIN&# -->", $this->erroMsg, $strArquivo ); | |
| 266 | - } | |
| 267 | - | |
| 268 | - fclose($ptrTpl); | |
| 269 | - die($strArquivo); | |
| 270 | - // @todo | |
| 271 | - #throw new Exception($strArquivo); | |
| 272 | - } | |
| 273 | - } | |
| 274 | - | |
| 275 | - /** | |
| 276 | - * Executa o login do usuário. | |
| 277 | - */ | |
| 278 | - public function obriga_Login() | |
| 279 | - { | |
| 280 | - if ($_POST['login'] && $_POST['senha']) { | |
| 281 | - $this->logar(TRUE); | |
| 282 | - } | |
| 283 | - if (!$this->logado) { | |
| 284 | - $this->logar(FALSE); | |
| 285 | - } | |
| 286 | - } | |
| 287 | - | |
| 288 | -} | |
| 289 | 1 | \ No newline at end of file |
| 2 | +<?php | |
| 3 | + | |
| 4 | +/* | |
| 5 | + * i-Educar - Sistema de gestão escolar | |
| 6 | + * | |
| 7 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 8 | + * <ctima@itajai.sc.gov.br> | |
| 9 | + * | |
| 10 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 11 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 12 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 13 | + * qualquer versão posterior. | |
| 14 | + * | |
| 15 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 16 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 17 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 18 | + * do GNU para mais detalhes. | |
| 19 | + * | |
| 20 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 21 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 22 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 23 | + */ | |
| 24 | + | |
| 25 | +require_once 'include/clsBanco.inc.php'; | |
| 26 | +require_once 'Portabilis/Messenger.php'; | |
| 27 | +require_once 'Portabilis/Mailer.php'; | |
| 28 | +require_once 'Portabilis/Utils/User.php'; | |
| 29 | +require_once 'Portabilis/Utils/ReCaptcha.php'; | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * clsControlador class. | |
| 33 | + * | |
| 34 | + * @author Prefeitura Municipal de Itajaí <ctima@itajai.sc.gov.br> | |
| 35 | + * @license http://creativecommons.org/licenses/GPL/2.0/legalcode.pt CC GNU GPL | |
| 36 | + * @package Core | |
| 37 | + * @since Classe disponível desde a versão 1.0.0 | |
| 38 | + * @version $Id: /ieducar/branches/1.1.0-avaliacao/ieducar/intranet/include/clsControlador.inc.php 662 2009-11-17T18:28:48.404882Z eriksen $ | |
| 39 | + */ | |
| 40 | +class clsControlador | |
| 41 | +{ | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * @var boolean | |
| 45 | + */ | |
| 46 | + public $logado; | |
| 47 | + | |
| 48 | + /** | |
| 49 | + * @var string | |
| 50 | + */ | |
| 51 | + public $erroMsg; | |
| 52 | + | |
| 53 | + | |
| 54 | + /** | |
| 55 | + * Construtor. | |
| 56 | + */ | |
| 57 | + public function clsControlador() | |
| 58 | + { | |
| 59 | + | |
| 60 | + /* | |
| 61 | + Desabilitado esta linha para usar o valor setado no php.ini > session.cookie_lifetime | |
| 62 | + @session_set_cookie_params(200); | |
| 63 | + */ | |
| 64 | + | |
| 65 | + @session_start(); | |
| 66 | + | |
| 67 | + if ('logado' == $_SESSION['itj_controle']) { | |
| 68 | + $this->logado = TRUE; | |
| 69 | + } | |
| 70 | + else { | |
| 71 | + $this->logado = FALSE; | |
| 72 | + } | |
| 73 | + | |
| 74 | + // Controle dos menus | |
| 75 | + if (isset($_GET['mudamenu']) && isset($_GET['categoria']) && isset($_GET['acao'])) | |
| 76 | + { | |
| 77 | + if ($_GET['acao']) { | |
| 78 | + $_SESSION['menu_opt'][$_GET['categoria']] = 1; | |
| 79 | + $_SESSION['menu_atual'] = $_GET['categoria']; | |
| 80 | + } | |
| 81 | + else { | |
| 82 | + // Está apagando variável session com o índice dado por $_GET | |
| 83 | + unset($_SESSION['menu_opt'][$_GET['categoria']]); | |
| 84 | + if ($_SESSION['menu_atual'] == $_GET['categoria']) { | |
| 85 | + unset($_SESSION['menu_atual']); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + $db = new clsBanco(); | |
| 90 | + if (isset($_SESSION['id_pessoa'])) { | |
| 91 | + $db->Consulta("UPDATE funcionario SET opcao_menu = '" . serialize( $_SESSION['menu_opt'] ) . "' WHERE ref_cod_pessoa_fj = '" . $_SESSION['id_pessoa'] . "'"); | |
| 92 | + } | |
| 93 | + } | |
| 94 | + | |
| 95 | + session_write_close(); | |
| 96 | + | |
| 97 | + $this->_maximoTentativasFalhas = 7; | |
| 98 | + $this->messenger = new Portabilis_Messenger(); | |
| 99 | + } | |
| 100 | + | |
| 101 | + | |
| 102 | + /** | |
| 103 | + * Retorna TRUE para usuário logado | |
| 104 | + * @return boolean | |
| 105 | + */ | |
| 106 | + public function Logado() | |
| 107 | + { | |
| 108 | + return $this->logado; | |
| 109 | + } | |
| 110 | + | |
| 111 | + | |
| 112 | + /** | |
| 113 | + * Executa o login do usuário. | |
| 114 | + */ | |
| 115 | + public function obriga_Login() | |
| 116 | + { | |
| 117 | + if (! $this->logado) | |
| 118 | + $validateUserCredentials = false; | |
| 119 | + | |
| 120 | + elseif ($_POST['login'] && $_POST['senha']) | |
| 121 | + $validateUserCredentials = true; | |
| 122 | + | |
| 123 | + $this->logar($validateUserCredentials); | |
| 124 | + } | |
| 125 | + | |
| 126 | + | |
| 127 | + // novo metodo login, logica quebrada em metodos menores | |
| 128 | + public function Logar($validateUserCredentials) { | |
| 129 | + if ($validateUserCredentials) { | |
| 130 | + $user = $this->validateUserCredentials($username = @$_POST['login'], $password = md5(@$_POST['senha'])); | |
| 131 | + | |
| 132 | + if ($this->canStartLoginSession($user)) { | |
| 133 | + $this->startLoginSession($user); | |
| 134 | + return null; | |
| 135 | + } | |
| 136 | + } | |
| 137 | + | |
| 138 | + $this->renderLoginPage(); | |
| 139 | + } | |
| 140 | + | |
| 141 | + | |
| 142 | + // valida se o usuário e senha informados, existem no banco de dados. | |
| 143 | + protected function validateUserCredentials($username, $password) { | |
| 144 | + if (! $this->validateHumanAccess()) { | |
| 145 | + $msg = "Você errou a senha muitas vezes, por favor, preencha o campo de " . | |
| 146 | + "confirmação visual ou <a class='light decorated' href='/module/Usuario/Rede" . | |
| 147 | + "finirSenha'>redefina sua senha</a>."; | |
| 148 | + $this->messenger->append($msg, "error", false, "error"); | |
| 149 | + } | |
| 150 | + | |
| 151 | + else { | |
| 152 | + $user = Portabilis_Utils_User::loadUsingCredentials($username, $password); | |
| 153 | + | |
| 154 | + if (is_null($user)) { | |
| 155 | + $this->messenger->append("Usuário ou senha incorreta.", "error"); | |
| 156 | + $this->incrementTentativasLogin(); | |
| 157 | + } | |
| 158 | + else { | |
| 159 | + $this->unsetTentativasLogin(); | |
| 160 | + return $user; | |
| 161 | + } | |
| 162 | + } | |
| 163 | + | |
| 164 | + return false; | |
| 165 | + } | |
| 166 | + | |
| 167 | + | |
| 168 | + public function startLoginSession($user, $redirectTo = '') { | |
| 169 | + // unsetting login attempts here, because when the password is recovered the login attempts should be reseted. | |
| 170 | + $this->unsetTentativasLogin(); | |
| 171 | + | |
| 172 | + @session_start(); | |
| 173 | + $_SESSION = array(); | |
| 174 | + $_SESSION['itj_controle'] = 'logado'; | |
| 175 | + $_SESSION['id_pessoa'] = $user['id']; | |
| 176 | + $_SESSION['pessoa_setor'] = $user['ref_cod_setor_new']; | |
| 177 | + $_SESSION['menu_opt'] = unserialize($user['opcao_menu']); | |
| 178 | + $_SESSION['tipo_menu'] = $user['tipo_menu']; | |
| 179 | + @session_write_close(); | |
| 180 | + | |
| 181 | + Portabilis_Utils_User::logAccessFor($user['id']); | |
| 182 | + Portabilis_Utils_User::destroyStatusTokenFor($user['id'], 'redefinir_senha'); | |
| 183 | + | |
| 184 | + $this->logado = true; | |
| 185 | + $this->messenger->append("Usuário logado com sucesso.", "success"); | |
| 186 | + | |
| 187 | + // solicita email para recuperação de senha, caso usuário ainda não tenha informado. | |
| 188 | + if (! filter_var($user['email'], FILTER_VALIDATE_EMAIL)) | |
| 189 | + header("Location: /module/Usuario/AlterarEmail"); | |
| 190 | + | |
| 191 | + elseif($user['expired_password']) | |
| 192 | + header("Location: /module/Usuario/AlterarSenha"); | |
| 193 | + | |
| 194 | + elseif(! empty($redirectTo)) | |
| 195 | + header("Location: $redirectTo"); | |
| 196 | + } | |
| 197 | + | |
| 198 | + | |
| 199 | + public function canStartLoginSession($user) { | |
| 200 | + if (! $this->messenger->hasMsgWithType("error")) { | |
| 201 | + $this->checkForDisabledAccount($user); | |
| 202 | + $this->checkForBannedAccount($user); | |
| 203 | + $this->checkForExpiredAccount($user); | |
| 204 | + $this->checkForMultipleAccess($user); | |
| 205 | + // #TODO verificar se conta nunca usada (exibir "Sua conta não está ativa. Use a opção 'Nunca usei a intrenet'." ?) | |
| 206 | + } | |
| 207 | + | |
| 208 | + return ! $this->messenger->hasMsgWithType("error"); | |
| 209 | + } | |
| 210 | + | |
| 211 | + | |
| 212 | + // renderiza o template de login, com as mensagens adicionadas durante validações | |
| 213 | + protected function renderLoginPage() { | |
| 214 | + $this->destroyLoginSession(); | |
| 215 | + | |
| 216 | + $templateName = 'templates/nvp_htmlloginintranet.tpl'; | |
| 217 | + $templateFile = fopen($templateName, "r"); | |
| 218 | + $templateText = fread($templateFile, filesize($templateName)); | |
| 219 | + $templateText = str_replace( "<!-- #&ERROLOGIN&# -->", $this->messenger->toHtml('p'), $templateText); | |
| 220 | + $templateText = str_replace( "#&GOOGLE_ANALYTICS_DOMAIN_NAME&#", $_SERVER['HTTP_HOST'], $templateText); | |
| 221 | + | |
| 222 | + $requiresHumanAccessValidation = isset($_SESSION['tentativas_login_falhas']) && | |
| 223 | + is_numeric($_SESSION['tentativas_login_falhas']) && | |
| 224 | + $_SESSION['tentativas_login_falhas'] >= $this->_maximoTentativasFalhas; | |
| 225 | + | |
| 226 | + if ($requiresHumanAccessValidation) | |
| 227 | + $templateText = str_replace( "<!-- #&RECAPTCHA&# -->", Portabilis_Utils_ReCaptcha::getWidget(), $templateText); | |
| 228 | + | |
| 229 | + fclose($templateFile); | |
| 230 | + die($templateText); | |
| 231 | + } | |
| 232 | + | |
| 233 | + | |
| 234 | + protected function destroyLoginSession($addMsg = false) { | |
| 235 | + $tentativasLoginFalhas = $_SESSION['tentativas_login_falhas']; | |
| 236 | + | |
| 237 | + @session_start(); | |
| 238 | + $_SESSION = array(); | |
| 239 | + @session_destroy(); | |
| 240 | + | |
| 241 | + //mantem tentativas_login_falhas, até que senha senha informada corretamente | |
| 242 | + @session_start(); | |
| 243 | + $_SESSION['tentativas_login_falhas'] = $tentativasLoginFalhas; | |
| 244 | + @session_write_close(); | |
| 245 | + | |
| 246 | + if ($addMsg) | |
| 247 | + $this->messenger->append("Usuário deslogado com sucesso.", "success"); | |
| 248 | + } | |
| 249 | + | |
| 250 | + | |
| 251 | + protected function getClientIP() { | |
| 252 | + if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') { | |
| 253 | + // pega o (ultimo) IP real caso o host esteja atrás de um proxy | |
| 254 | + $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); | |
| 255 | + $ip = trim(array_pop($ip)); | |
| 256 | + } | |
| 257 | + else | |
| 258 | + $ip = $_SERVER['REMOTE_ADDR']; | |
| 259 | + return $ip; | |
| 260 | + } | |
| 261 | + | |
| 262 | + | |
| 263 | + protected function validateHumanAccess() { | |
| 264 | + $result = false; | |
| 265 | + | |
| 266 | + if (! $this->atingiuTentativasLogin()) | |
| 267 | + $result = true; | |
| 268 | + | |
| 269 | + elseif (Portabilis_Utils_ReCaptcha::getWidget()->validate()) { | |
| 270 | + $this->unsetTentativasLogin(); | |
| 271 | + $result = true; | |
| 272 | + } | |
| 273 | + | |
| 274 | + return $result; | |
| 275 | + } | |
| 276 | + | |
| 277 | + | |
| 278 | + protected function atingiuTentativasLogin() { | |
| 279 | + return isset($_SESSION['tentativas_login_falhas']) && | |
| 280 | + is_numeric($_SESSION['tentativas_login_falhas']) && | |
| 281 | + $_SESSION['tentativas_login_falhas'] >= $this->_maximoTentativasFalhas; | |
| 282 | + } | |
| 283 | + | |
| 284 | + | |
| 285 | + protected function incrementTentativasLogin() { | |
| 286 | + @session_start(); | |
| 287 | + if (! isset($_SESSION['tentativas_login_falhas']) or ! is_numeric($_SESSION['tentativas_login_falhas'])) | |
| 288 | + $_SESSION['tentativas_login_falhas'] = 1; | |
| 289 | + else | |
| 290 | + $_SESSION['tentativas_login_falhas'] += 1; | |
| 291 | + @session_write_close(); | |
| 292 | + } | |
| 293 | + | |
| 294 | + | |
| 295 | + protected function unsetTentativasLogin() { | |
| 296 | + @session_start(); | |
| 297 | + unset($_SESSION['tentativas_login_falhas']); | |
| 298 | + @session_write_close(); | |
| 299 | + } | |
| 300 | + | |
| 301 | + | |
| 302 | + protected function checkForDisabledAccount($user) { | |
| 303 | + if ($user['ativo'] != '1') { | |
| 304 | + $this->messenger->append("Sua conta de usuário foi desativada ou expirou, por favor, " . | |
| 305 | + "entre em contato com o responsável pelo sistema do seu município.", "error", false, "error"); | |
| 306 | + } | |
| 307 | + } | |
| 308 | + | |
| 309 | + | |
| 310 | + protected function checkForBannedAccount($user) { | |
| 311 | + if ($user['proibido'] != '0') { | |
| 312 | + $this->messenger->append("Sua conta de usuário não pode mais acessar o sistema, " . | |
| 313 | + "por favor, entre em contato com o responsável pelo sistema do seu município.", | |
| 314 | + "error", false, "error"); | |
| 315 | + } | |
| 316 | + } | |
| 317 | + | |
| 318 | + | |
| 319 | + protected function checkForExpiredAccount($user) { | |
| 320 | + if($user['expired_account']) { | |
| 321 | + | |
| 322 | + if ($user['ativo'] == 1) | |
| 323 | + Portabilis_Utils_User::disableAccount($user['id']); | |
| 324 | + | |
| 325 | + $this->messenger->append("Sua conta de usuário expirou, por favor, " . | |
| 326 | + "entre em contato com o responsável pelo sistema do seu município.", "error", false, "error"); | |
| 327 | + } | |
| 328 | + } | |
| 329 | + | |
| 330 | + | |
| 331 | + protected function checkForMultipleAccess($user) { | |
| 332 | + // considera como acesso multiplo, acesso em diferentes IPs em menos de $tempoMultiploAcesso minutos | |
| 333 | + $tempoMultiploAcesso = 10; | |
| 334 | + $tempoEmEspera = abs(time() - strftime("now") - strtotime($user['data_login'])) / 60; | |
| 335 | + | |
| 336 | + $multiploAcesso = $tempoEmEspera <= $tempoMultiploAcesso && | |
| 337 | + $user['ip_ultimo_acesso'] != $this->getClientIP(); | |
| 338 | + | |
| 339 | + if ($multiploAcesso and $user['super']) { | |
| 340 | + | |
| 341 | + // #TODO mover lógica email, para mailer especifico | |
| 342 | + | |
| 343 | + $subject = "Conta do super usuário {$_SERVER['HTTP_HOST']} acessada em mais de um local"; | |
| 344 | + | |
| 345 | + $message = ("Aparentemente a conta do super usuário {$user['matricula']} foi acessada em " . | |
| 346 | + "outro computador nos últimos $tempoMultiploAcesso " . | |
| 347 | + "minutos, caso não tenha sido você, por favor, altere sua senha.\n\n" . | |
| 348 | + "Endereço IP último acesso: {$user['ip_ultimo_acesso']}\n". | |
| 349 | + "Endereço IP acesso atual: {$this->getClientIP()}"); | |
| 350 | + | |
| 351 | + $mailer = new Portabilis_Mailer(); | |
| 352 | + $mailer->sendMail($user['email'], $subject, $message); | |
| 353 | + } | |
| 354 | + elseif ($multiploAcesso) { | |
| 355 | + $minutosEmEspera = round($tempoMultiploAcesso - $tempoEmEspera) + 1; | |
| 356 | + $this->messenger->append("Aparentemente sua conta foi acessada em outro computador nos últimos " . | |
| 357 | + "$tempoMultiploAcesso minutos, caso não tenha sido você, " . | |
| 358 | + "por favor, altere sua senha ou tente novamente em $minutosEmEspera minutos", | |
| 359 | + "error", false, "error"); | |
| 360 | + } | |
| 361 | + } | |
| 362 | + | |
| 363 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,73 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabiilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package CoreExt_Validate | |
| 27 | + * @since Arquivo disponível desde a versão 1.1.0 | |
| 28 | + * @version $Id$ | |
| 29 | + */ | |
| 30 | + | |
| 31 | +require_once 'CoreExt/Validate/Abstract.php'; | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * CoreExt_Validate_Numeric class. | |
| 35 | + * | |
| 36 | + * @author Eriksen Costa Paixão <eriksen.paixao_bs@cobra.com.br> | |
| 37 | + * @category i-Educar | |
| 38 | + * @license @@license@@ | |
| 39 | + * @package CoreExt_Validate | |
| 40 | + * @since Classe disponível desde a versão 1.1.0 | |
| 41 | + * @version @@package_version@@ | |
| 42 | + */ | |
| 43 | +class CoreExt_Validate_Email extends CoreExt_Validate_Abstract | |
| 44 | +{ | |
| 45 | + /** | |
| 46 | + * @see CoreExt_Validate_Abstract#_getDefaultOptions() | |
| 47 | + */ | |
| 48 | + protected function _getDefaultOptions() | |
| 49 | + { | |
| 50 | + return array( | |
| 51 | + 'invalid' => 'Email inválido.' | |
| 52 | + ); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * @see CoreExt_DataMapper#_getFindStatment($pkey) Sobre a conversão com floatval() | |
| 57 | + * @see CoreExt_Validate_Abstract#_validate($value) | |
| 58 | + */ | |
| 59 | + protected function _validate($value) | |
| 60 | + { | |
| 61 | + if (FALSE === filter_var($value, FILTER_VALIDATE_EMAIL)) { | |
| 62 | + throw new Exception($this->_getErrorMessage('invalid')); | |
| 63 | + } | |
| 64 | + | |
| 65 | + return TRUE; | |
| 66 | + } | |
| 67 | + | |
| 68 | + /** | |
| 69 | + * Mensagem padrão para erros de valor obrigatório. | |
| 70 | + * @var string | |
| 71 | + */ | |
| 72 | + protected $_requiredMessage = 'Informe um email válido.'; | |
| 73 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,59 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package Usuario | |
| 27 | + * @subpackage Modules | |
| 28 | + * @since Arquivo disponível desde a versão ? | |
| 29 | + * @version $Id$ | |
| 30 | + */ | |
| 31 | + | |
| 32 | +require_once 'lib/Portabilis/Mailer.php'; | |
| 33 | + | |
| 34 | +class UsuarioMailer extends Portabilis_Mailer | |
| 35 | +{ | |
| 36 | + | |
| 37 | + static function updatedPassword($user, $link) { | |
| 38 | + $to = $user->email; | |
| 39 | + | |
| 40 | + $subject = "Sua senha foi alterada - i-Educar - " . self::host(); | |
| 41 | + $message = "Olá!\n\n" . | |
| 42 | + "A senha da matrícula '{$user->matricula}' foi alterada recentemente.\n\n" . | |
| 43 | + "Caso você não tenha feito esta alteração, por favor, tente alterar sua senha acessando o link $link ou entre em contato com o administrador do sistema (solicitando mudança da sua senha), pois sua conta pode estar sendo usada por alguma pessoa não autorizada."; | |
| 44 | + | |
| 45 | + return self::mail($to, $subject, $message); | |
| 46 | + } | |
| 47 | + | |
| 48 | + static function passwordReset($user, $link) { | |
| 49 | + $to = $user->email; | |
| 50 | + | |
| 51 | + $subject = "Redefinição de senha - i-Educar - " . self::host(); | |
| 52 | + $message = "Olá!\n\n" . | |
| 53 | + "Recebemos uma solicitação de redefinição de senha para a matrícula {$user->matricula}.\n\n" . | |
| 54 | + "Para redefinir sua senha acesse o link: $link\n\n" . | |
| 55 | + "Caso você não tenha feito esta solicitação, por favor, ignore esta mensagem."; | |
| 56 | + | |
| 57 | + return self::mail($to, $subject, $message); | |
| 58 | + } | |
| 59 | +} | |
| 0 | 60 | \ No newline at end of file | ... | ... |
| ... | ... | @@ -0,0 +1,90 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +#error_reporting(E_ALL); | |
| 4 | +#ini_set("display_errors", 1); | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * i-Educar - Sistema de gestão escolar | |
| 8 | + * | |
| 9 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 10 | + * <ctima@itajai.sc.gov.br> | |
| 11 | + * | |
| 12 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 13 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 14 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 15 | + * qualquer versão posterior. | |
| 16 | + * | |
| 17 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 18 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 19 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 20 | + * do GNU para mais detalhes. | |
| 21 | + * | |
| 22 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 23 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 24 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 25 | + * | |
| 26 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 27 | + * @category i-Educar | |
| 28 | + * @license @@license@@ | |
| 29 | + * @package ComponenteCurricular | |
| 30 | + * @subpackage Modules | |
| 31 | + * @since Arquivo disponível desde a versão 1.1.0 | |
| 32 | + * @version $Id$ | |
| 33 | + */ | |
| 34 | + | |
| 35 | +require_once 'CoreExt/Entity.php'; | |
| 36 | +require_once 'App/Model/IedFinder.php'; | |
| 37 | +require_once 'CoreExt/Validate/Email.php'; | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * ComponenteCurricular_Model_Componente class. | |
| 41 | + * | |
| 42 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 43 | + * @category i-Educar | |
| 44 | + * @license @@license@@ | |
| 45 | + * @package ComponenteCurricular | |
| 46 | + * @subpackage Modules | |
| 47 | + * @since Classe disponível desde a versão 1.1.0 | |
| 48 | + * @version @@package_version@@ | |
| 49 | + */ | |
| 50 | +class Usuario_Model_Funcionario extends CoreExt_Entity | |
| 51 | +{ | |
| 52 | + protected $_data = array( | |
| 53 | + #'ref_cod_pessoa_fj' => NULL, | |
| 54 | + 'matricula' => NULL, | |
| 55 | + 'email' => NULL, | |
| 56 | + 'senha' => NULL, | |
| 57 | + 'data_troca_senha' => NULL, | |
| 58 | + 'status_token' => NULL | |
| 59 | + ); | |
| 60 | + | |
| 61 | + protected $_dataTypes = array( | |
| 62 | + 'matricula' => 'string' | |
| 63 | + ); | |
| 64 | + | |
| 65 | + protected $_references = array( | |
| 66 | + ); | |
| 67 | + | |
| 68 | + public function getDataMapper() | |
| 69 | + { | |
| 70 | + if (is_null($this->_dataMapper)) { | |
| 71 | + require_once 'Usuario/Model/FuncionarioDataMapper.php'; | |
| 72 | + $this->setDataMapper(new Usuario_Model_FuncionarioDataMapper()); | |
| 73 | + } | |
| 74 | + return parent::getDataMapper(); | |
| 75 | + } | |
| 76 | + | |
| 77 | + public function getDefaultValidatorCollection() | |
| 78 | + { | |
| 79 | + return array( | |
| 80 | + 'email' => new CoreExt_Validate_Email() | |
| 81 | + ); | |
| 82 | + } | |
| 83 | + | |
| 84 | + protected function _createIdentityField() | |
| 85 | + { | |
| 86 | + $id = array('ref_cod_pessoa_fj' => NULL); | |
| 87 | + $this->_data = array_merge($id, $this->_data); | |
| 88 | + return $this; | |
| 89 | + } | |
| 90 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,72 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package Usuario | |
| 27 | + * @subpackage Modules | |
| 28 | + * @since Arquivo disponível desde a versão 1.1.0 | |
| 29 | + * @version $Id$ | |
| 30 | + */ | |
| 31 | + | |
| 32 | +require_once 'CoreExt/DataMapper.php'; | |
| 33 | +require_once 'Usuario/Model/Funcionario.php'; | |
| 34 | + | |
| 35 | +/** | |
| 36 | + * Usuario_Model_FuncionarioDataMapper class. | |
| 37 | + * | |
| 38 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 39 | + * @category i-Educar | |
| 40 | + * @license @@license@@ | |
| 41 | + * @package Usuario | |
| 42 | + * @subpackage Modules | |
| 43 | + * @since Classe disponível desde a versão 1.1.0 | |
| 44 | + * @version @@package_version@@ | |
| 45 | + */ | |
| 46 | +class Usuario_Model_FuncionarioDataMapper extends CoreExt_DataMapper | |
| 47 | +{ | |
| 48 | + protected $_entityClass = 'Usuario_Model_Funcionario'; | |
| 49 | + protected $_tableName = 'funcionario'; | |
| 50 | + protected $_tableSchema = 'portal'; | |
| 51 | + | |
| 52 | + protected $_attributeMap = array( | |
| 53 | + #'ref_cod_pessoa_fj' => 'ref_cod_pessoa_fj', | |
| 54 | + #'matricula' => 'matricula', | |
| 55 | + #'email' => 'email', | |
| 56 | + #'data_troca_senha' => 'data_troca_senha' | |
| 57 | + ); | |
| 58 | + | |
| 59 | + protected $_notPersistable = array( | |
| 60 | + #'ippes' | |
| 61 | + ); | |
| 62 | + | |
| 63 | + protected $_primaryKey = array('ref_cod_pessoa_fj'); | |
| 64 | + | |
| 65 | + protected function _getFindStatment($pkey) | |
| 66 | + { | |
| 67 | + if (!is_array($pkey)) | |
| 68 | + $pkey = array("ref_cod_pessoa_fj" => $pkey); | |
| 69 | + | |
| 70 | + return parent::_getFindStatment($pkey); | |
| 71 | + } | |
| 72 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,91 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +#error_reporting(E_ALL); | |
| 4 | +#ini_set("display_errors", 1); | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * i-Educar - Sistema de gestão escolar | |
| 8 | + * | |
| 9 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 10 | + * <ctima@itajai.sc.gov.br> | |
| 11 | + * | |
| 12 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 13 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 14 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 15 | + * qualquer versão posterior. | |
| 16 | + * | |
| 17 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 18 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 19 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 20 | + * do GNU para mais detalhes. | |
| 21 | + * | |
| 22 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 23 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 24 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 25 | + * | |
| 26 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 27 | + * @category i-Educar | |
| 28 | + * @license @@license@@ | |
| 29 | + * @package ComponenteCurricular | |
| 30 | + * @subpackage Modules | |
| 31 | + * @since Arquivo disponível desde a versão 1.1.0 | |
| 32 | + * @version $Id$ | |
| 33 | + */ | |
| 34 | + | |
| 35 | +require_once 'CoreExt/Entity.php'; | |
| 36 | +require_once 'App/Model/IedFinder.php'; | |
| 37 | +require_once 'CoreExt/Validate/Email.php'; | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * ComponenteCurricular_Model_Componente class. | |
| 41 | + * | |
| 42 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 43 | + * @category i-Educar | |
| 44 | + * @license @@license@@ | |
| 45 | + * @package ComponenteCurricular | |
| 46 | + * @subpackage Modules | |
| 47 | + * @since Classe disponível desde a versão 1.1.0 | |
| 48 | + * @version @@package_version@@ | |
| 49 | + */ | |
| 50 | +class Usuario_Model_Usuario extends CoreExt_Entity | |
| 51 | +{ | |
| 52 | + protected $_data = array( | |
| 53 | + 'id' => NULL, | |
| 54 | + 'escolaId' => NULL, | |
| 55 | + 'instituicaoId' => NULL, | |
| 56 | + 'funcionarioCadId' => NULL, | |
| 57 | + 'funcionarioExcId' => NULL, | |
| 58 | + 'tipoUsuarioId' => NULL, | |
| 59 | + 'dataCadastro' => NULL, | |
| 60 | + 'dataExclusao' => NULL, | |
| 61 | + 'ativo' => NULL | |
| 62 | + ); | |
| 63 | + | |
| 64 | + /*protected $_dataTypes = array( | |
| 65 | + ); | |
| 66 | + | |
| 67 | + protected $_references = array( | |
| 68 | + );*/ | |
| 69 | + | |
| 70 | + public function getDataMapper() | |
| 71 | + { | |
| 72 | + if (is_null($this->_dataMapper)) { | |
| 73 | + require_once 'Usuario/Model/UsuarioDataMapper.php'; | |
| 74 | + $this->setDataMapper(new Usuario_Model_UsuarioDataMapper()); | |
| 75 | + } | |
| 76 | + return parent::getDataMapper(); | |
| 77 | + } | |
| 78 | + | |
| 79 | + public function getDefaultValidatorCollection() | |
| 80 | + { | |
| 81 | + return array(); | |
| 82 | + } | |
| 83 | + | |
| 84 | + // TODO remover metodo? já que foi usado $_attributeMap id | |
| 85 | + protected function _createIdentityField() | |
| 86 | + { | |
| 87 | + $id = array('id' => NULL); | |
| 88 | + $this->_data = array_merge($id, $this->_data); | |
| 89 | + return $this; | |
| 90 | + } | |
| 91 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,78 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package Usuario | |
| 27 | + * @subpackage Modules | |
| 28 | + * @since Arquivo disponível desde a versão 1.1.0 | |
| 29 | + * @version $Id$ | |
| 30 | + */ | |
| 31 | + | |
| 32 | +require_once 'CoreExt/DataMapper.php'; | |
| 33 | +require_once 'Usuario/Model/Usuario.php'; | |
| 34 | + | |
| 35 | +/** | |
| 36 | + * Usuario_Model_UsuarioDataMapper class. | |
| 37 | + * | |
| 38 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 39 | + * @category i-Educar | |
| 40 | + * @license @@license@@ | |
| 41 | + * @package Usuario | |
| 42 | + * @subpackage Modules | |
| 43 | + * @since Classe disponível desde a versão 1.1.0 | |
| 44 | + * @version @@package_version@@ | |
| 45 | + */ | |
| 46 | +class Usuario_Model_UsuarioDataMapper extends CoreExt_DataMapper | |
| 47 | +{ | |
| 48 | + protected $_entityClass = 'Usuario_Model_Usuario'; | |
| 49 | + protected $_tableName = 'usuario'; | |
| 50 | + protected $_tableSchema = 'pmieducar'; | |
| 51 | + | |
| 52 | + protected $_attributeMap = array( | |
| 53 | + 'id' => 'cod_usuario', | |
| 54 | + 'escolaId' => 'ref_cod_escola', | |
| 55 | + 'instituicaoId' => 'ref_cod_instituicao', | |
| 56 | + 'funcionarioCadId' => 'ref_funcionario_cad', | |
| 57 | + 'funcionarioExcId' => 'ref_funcionario_exc', | |
| 58 | + 'tipoUsuarioId' => 'ref_cod_tipo_usuario', | |
| 59 | + 'dataCadastro' => 'data_cadastro', | |
| 60 | + 'dataExclusao' => 'data_exclusao', | |
| 61 | + 'ativo' => 'ativo' | |
| 62 | + ); | |
| 63 | + | |
| 64 | + protected $_notPersistable = array( | |
| 65 | + ); | |
| 66 | + | |
| 67 | + // TODO remover? já que foi usado $_attributeMap id | |
| 68 | + protected $_primaryKey = array('id'); | |
| 69 | + | |
| 70 | + // TODO remover metodo? já que foi usado $_attributeMap id | |
| 71 | + protected function _getFindStatment($pkey) | |
| 72 | + { | |
| 73 | + if (!is_array($pkey)) | |
| 74 | + $pkey = array("id" => $pkey); | |
| 75 | + | |
| 76 | + return parent::_getFindStatment($pkey); | |
| 77 | + } | |
| 78 | +} | ... | ... |
| ... | ... | @@ -0,0 +1,61 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package Usuario | |
| 27 | + * @subpackage Modules | |
| 28 | + * @since Arquivo disponível desde a versão ? | |
| 29 | + * @version $Id$ | |
| 30 | + */ | |
| 31 | + | |
| 32 | +class UsuarioValidator | |
| 33 | +{ | |
| 34 | + static function validatePassword($messenger, | |
| 35 | + $oldPassword, | |
| 36 | + $newPassword, | |
| 37 | + $confirmation, | |
| 38 | + $encriptedPassword, | |
| 39 | + $matricula) | |
| 40 | + { | |
| 41 | + $newPassword = strtolower($newPassword); | |
| 42 | + $confirmation = strtolower($confirmation); | |
| 43 | + | |
| 44 | + if (empty($newPassword)) | |
| 45 | + $messenger->append('Por favor informe uma senha.', 'error'); | |
| 46 | + | |
| 47 | + elseif (strlen($newPassword) < 8) | |
| 48 | + $messenger->append('Por favor informe uma senha mais segura, com pelo menos 8 caracteres.', 'error'); | |
| 49 | + | |
| 50 | + elseif ($newPassword != $confirmation) | |
| 51 | + $messenger->append('A confirmação de senha não confere com a senha.', 'error'); | |
| 52 | + | |
| 53 | + elseif (strpos($newPassword, $matricula) != false) | |
| 54 | + $messenger->append('A senha informada é similar a sua matricula, informe outra senha.', 'error'); | |
| 55 | + | |
| 56 | + elseif ($encriptedPassword == $oldPassword) | |
| 57 | + $messenger->append('Informe uma senha diferente da atual.', 'error'); | |
| 58 | + | |
| 59 | + return ! $messenger->hasMsgWithType('error'); | |
| 60 | + } | |
| 61 | +} | |
| 0 | 62 | \ No newline at end of file | ... | ... |
ieducar/modules/Usuario/Views/AlterarEmailController.php
0 → 100644
| ... | ... | @@ -0,0 +1,98 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * i-Educar - Sistema de gestão escolar | |
| 5 | + * | |
| 6 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 7 | + * <ctima@itajai.sc.gov.br> | |
| 8 | + * | |
| 9 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 10 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 11 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 12 | + * qualquer versão posterior. | |
| 13 | + * | |
| 14 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 15 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 16 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 17 | + * do GNU para mais detalhes. | |
| 18 | + * | |
| 19 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 20 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 21 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 22 | + * | |
| 23 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 24 | + * @category i-Educar | |
| 25 | + * @license @@license@@ | |
| 26 | + * @package Avaliacao | |
| 27 | + * @subpackage Modules | |
| 28 | + * @since Arquivo disponível desde a versão ? | |
| 29 | + * @version $Id$ | |
| 30 | + */ | |
| 31 | + | |
| 32 | +require_once 'lib/Portabilis/Controller/Page/EditController.php'; | |
| 33 | +require_once 'Usuario/Model/FuncionarioDataMapper.php'; | |
| 34 | +require_once 'Usuario/Mailers/UsuarioMailer.php'; | |
| 35 | + | |
| 36 | +class AlterarEmailController extends Portabilis_Controller_Page_EditController | |
| 37 | +{ | |
| 38 | + protected $_dataMapper = 'Usuario_Model_FuncionarioDataMapper'; | |
| 39 | + protected $_titulo = 'Alterar e-mail'; | |
| 40 | + protected $_processoAp = 0; | |
| 41 | + | |
| 42 | + protected $backwardCompatibility = true; | |
| 43 | + | |
| 44 | + protected $_formMap = array( | |
| 45 | + 'matricula' => array( | |
| 46 | + 'label' => 'Matrícula', | |
| 47 | + 'help' => '', | |
| 48 | + ), | |
| 49 | + 'email' => array( | |
| 50 | + 'label' => 'E-mail', | |
| 51 | + 'help' => 'E-mail utilizado para recuperar sua senha.', | |
| 52 | + ), | |
| 53 | + ); | |
| 54 | + | |
| 55 | + | |
| 56 | + protected function _preConstruct() | |
| 57 | + { | |
| 58 | + $this->_options = $this->mergeOptions(array('edit_success' => 'intranet/index.php'), $this->_options); | |
| 59 | + } | |
| 60 | + | |
| 61 | + | |
| 62 | + // this controller always edit an existing resource | |
| 63 | + protected function _initNovo() { | |
| 64 | + return false; | |
| 65 | + } | |
| 66 | + | |
| 67 | + | |
| 68 | + protected function _initEditar() { | |
| 69 | + $this->setEntity($this->getDataMapper()->find($this->getOption('id_usuario'))); | |
| 70 | + return true; | |
| 71 | + } | |
| 72 | + | |
| 73 | + | |
| 74 | + public function Gerar() | |
| 75 | + { | |
| 76 | + $validEmail = filter_var($this->getEntity()->email, FILTER_VALIDATE_EMAIL) == true; | |
| 77 | + | |
| 78 | + if (empty($this->getRequest()->email) && ! $validEmail) | |
| 79 | + $this->messenger()->append("Por favor informe um e-mail válido, para ser usado caso você esqueça sua senha."); | |
| 80 | + | |
| 81 | + $this->campoRotulo('matricula', $this->_getLabel('matricula'), $this->getEntity()->matricula); | |
| 82 | + $this->campoTexto('email', $this->_getLabel('email'), $this->getEntity()->email, | |
| 83 | + 50, 50, TRUE, FALSE, FALSE, $this->_getHelp('email')); | |
| 84 | + | |
| 85 | + $this->url_cancelar = '/intranet/index.php'; | |
| 86 | + | |
| 87 | + if (! $validEmail) | |
| 88 | + $this->nome_url_cancelar = 'Deixar para depois'; | |
| 89 | + } | |
| 90 | + | |
| 91 | + | |
| 92 | + public function save() | |
| 93 | + { | |
| 94 | + $this->getEntity()->setOptions(array('email' => $_POST['email'])); | |
| 95 | + $this->getDataMapper()->save($this->getEntity()); | |
| 96 | + } | |
| 97 | +} | |
| 98 | +?> | ... | ... |
ieducar/modules/Usuario/Views/AlterarSenhaController.php
0 → 100644
| ... | ... | @@ -0,0 +1,109 @@ |
| 1 | + <?php | |
| 2 | + | |
| 3 | +#error_reporting(E_ALL); | |
| 4 | +#ini_set("display_errors", 1); | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * i-Educar - Sistema de gestão escolar | |
| 8 | + * | |
| 9 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 10 | + * <ctima@itajai.sc.gov.br> | |
| 11 | + * | |
| 12 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 13 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 14 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 15 | + * qualquer versão posterior. | |
| 16 | + * | |
| 17 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 18 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 19 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 20 | + * do GNU para mais detalhes. | |
| 21 | + * | |
| 22 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 23 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 24 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 25 | + * | |
| 26 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 27 | + * @category i-Educar | |
| 28 | + * @license @@license@@ | |
| 29 | + * @package Usuario | |
| 30 | + * @subpackage Modules | |
| 31 | + * @since Arquivo disponível desde a versão ? | |
| 32 | + * @version $Id$ | |
| 33 | + */ | |
| 34 | + | |
| 35 | +require_once 'lib/Portabilis/Controller/Page/EditController.php'; | |
| 36 | +require_once 'Usuario/Model/FuncionarioDataMapper.php'; | |
| 37 | +require_once 'Usuario/Mailers/UsuarioMailer.php'; | |
| 38 | +require_once 'Usuario/Validators/UsuarioValidator.php'; | |
| 39 | + | |
| 40 | +class AlterarSenhaController extends Portabilis_Controller_Page_EditController | |
| 41 | +{ | |
| 42 | + protected $_dataMapper = 'Usuario_Model_FuncionarioDataMapper'; | |
| 43 | + protected $_titulo = 'Alterar senha'; | |
| 44 | + protected $_processoAp = 0; | |
| 45 | + | |
| 46 | + protected $backwardCompatibility = true; | |
| 47 | + | |
| 48 | + protected $_formMap = array( | |
| 49 | + 'matricula' => array('label' => 'Matrícula', 'help' => ''), | |
| 50 | + 'nova_senha' => array('label' => 'Nova senha', 'help' => ''), | |
| 51 | + 'confirmacao_senha' => array('label' => 'Confirmação de senha', 'help' => ''), | |
| 52 | + ); | |
| 53 | + | |
| 54 | + | |
| 55 | + protected function _preConstruct() | |
| 56 | + { | |
| 57 | + $this->_options = $this->mergeOptions(array('edit_success' => 'intranet/index.php'), $this->_options); | |
| 58 | + } | |
| 59 | + | |
| 60 | + | |
| 61 | + // this controller always edit an existing resource | |
| 62 | + protected function _initNovo() { | |
| 63 | + return false; | |
| 64 | + } | |
| 65 | + | |
| 66 | + | |
| 67 | + protected function _initEditar() { | |
| 68 | + $this->setEntity($this->getDataMapper()->find($this->getOption('id_usuario'))); | |
| 69 | + return true; | |
| 70 | + } | |
| 71 | + | |
| 72 | + | |
| 73 | + public function Gerar() | |
| 74 | + { | |
| 75 | + if (! isset($_POST['password'])) | |
| 76 | + $this->messenger()->append('Para sua segurança mude sua senha periodicamente, por favor, informe uma nova senha.', 'info'); | |
| 77 | + | |
| 78 | + $this->campoRotulo('matricula', $this->_getLabel('matricula'), $this->getEntity()->matricula); | |
| 79 | + $this->campoSenha('password', $this->_getLabel('nova_senha'), @$_POST['password'], TRUE); | |
| 80 | + $this->campoSenha('password_confirmation', $this->_getLabel('confirmacao_senha'), @$_POST['password_confirmation'], TRUE); | |
| 81 | + | |
| 82 | + $this->nome_url_sucesso = 'Alterar'; | |
| 83 | + $this->nome_url_cancelar = 'Deixar para depois'; | |
| 84 | + | |
| 85 | + if ($GLOBALS['coreExt']['Config']->app->user_accounts->force_password_update != true) | |
| 86 | + $this->url_cancelar = '/intranet/index.php'; | |
| 87 | + } | |
| 88 | + | |
| 89 | + | |
| 90 | + protected function canSave() | |
| 91 | + { | |
| 92 | + return UsuarioValidator::validatePassword($this->messenger(), | |
| 93 | + $this->getEntity()->senha, | |
| 94 | + $_POST['password'], | |
| 95 | + $_POST['password_confirmation'], | |
| 96 | + md5($_POST['password']), | |
| 97 | + $this->getEntity()->matricula); | |
| 98 | + } | |
| 99 | + | |
| 100 | + protected function save() | |
| 101 | + { | |
| 102 | + $this->getEntity()->setOptions(array('senha' => md5($_POST['password']), 'data_troca_senha' => 'now()')); | |
| 103 | + $this->getDataMapper()->save($this->getEntity()); | |
| 104 | + | |
| 105 | + $linkToReset = $_SERVER['HTTP_HOST'] . $this->getRequest()->getBaseurl() . '/' . 'Usuario/AlterarSenha'; | |
| 106 | + UsuarioMailer::updatedPassword($user = $this->getEntity(), $linkToReset); | |
| 107 | + } | |
| 108 | +} | |
| 109 | +?> | ... | ... |
ieducar/modules/Usuario/Views/RedefinirSenhaController.php
0 → 100644
| ... | ... | @@ -0,0 +1,354 @@ |
| 1 | +<?php | |
| 2 | + | |
| 3 | +#error_reporting(E_ALL); | |
| 4 | +#ini_set("display_errors", 1); | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * i-Educar - Sistema de gestão escolar | |
| 8 | + * | |
| 9 | + * Copyright (C) 2006 Prefeitura Municipal de Itajaí | |
| 10 | + * <ctima@itajai.sc.gov.br> | |
| 11 | + * | |
| 12 | + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo | |
| 13 | + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free | |
| 14 | + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) | |
| 15 | + * qualquer versão posterior. | |
| 16 | + * | |
| 17 | + * Este programa é distribuído na expectativa de que seja útil, porém, SEM | |
| 18 | + * NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU | |
| 19 | + * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral | |
| 20 | + * do GNU para mais detalhes. | |
| 21 | + * | |
| 22 | + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto | |
| 23 | + * com este programa; se não, escreva para a Free Software Foundation, Inc., no | |
| 24 | + * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. | |
| 25 | + * | |
| 26 | + * @author Lucas D'Avila <lucasdavila@portabilis.com.br> | |
| 27 | + * @category i-Educar | |
| 28 | + * @license @@license@@ | |
| 29 | + * @package Usuario | |
| 30 | + * @subpackage Modules | |
| 31 | + * @since Arquivo disponível desde a versão ? | |
| 32 | + * @version $Id$ | |
| 33 | + */ | |
| 34 | + | |
| 35 | +require_once 'lib/Portabilis/Controller/Page/EditController.php'; | |
| 36 | +require_once 'Usuario/Model/FuncionarioDataMapper.php'; | |
| 37 | +require_once 'Usuario/Mailers/UsuarioMailer.php'; | |
| 38 | +require_once 'Portabilis/View/Helper/Application.php'; | |
| 39 | +require_once 'lib/Portabilis/Utils/ReCaptcha.php'; | |
| 40 | +require_once 'Usuario/Validators/UsuarioValidator.php'; | |
| 41 | + | |
| 42 | +require_once 'include/clsControlador.inc.php'; | |
| 43 | + | |
| 44 | +class RedefinirSenhaController extends Portabilis_Controller_Page_EditController | |
| 45 | +{ | |
| 46 | + protected $_dataMapper = 'Usuario_Model_FuncionarioDataMapper'; | |
| 47 | + protected $_titulo = 'Redefinir senha'; | |
| 48 | + protected $_processoAp = 0; | |
| 49 | + | |
| 50 | + protected $backwardCompatibility = true; | |
| 51 | + | |
| 52 | + protected $_formMap = array( | |
| 53 | + 'matricula' => array( | |
| 54 | + 'label' => 'Matrícula', | |
| 55 | + 'help' => '', | |
| 56 | + ), | |
| 57 | + 'nova_senha' => array( | |
| 58 | + 'label' => 'Nova senha', | |
| 59 | + 'help' => '', | |
| 60 | + ), | |
| 61 | + 'confirmacao_senha' => array( | |
| 62 | + 'label' => 'Confirmação de senha', | |
| 63 | + 'help' => '', | |
| 64 | + ), | |
| 65 | + ); | |
| 66 | + | |
| 67 | + | |
| 68 | + public function _preConstruct() { | |
| 69 | + $this->_options = $this->mergeOptions(array('edit_success' => 'intranet/index.php'), $this->_options); | |
| 70 | + } | |
| 71 | + | |
| 72 | + | |
| 73 | + /* overwrite Core/Controller/Page/Abstract.php para renderizar html | |
| 74 | + sem necessidade de usuário estar logado */ | |
| 75 | + public function generate(CoreExt_Controller_Page_Interface $instance) | |
| 76 | + { | |
| 77 | + require_once 'Core/View.php'; | |
| 78 | + $viewBase = new Core_View($instance); | |
| 79 | + $viewBase->titulo = 'i-Educar - Redefinição senha'; | |
| 80 | + $instance->titulo = 'Redefinição senha'; | |
| 81 | + $viewBase->addForm($instance); | |
| 82 | + //$viewBase->Formular(); | |
| 83 | + | |
| 84 | + $html = $viewBase->MakeHeadHtml(); | |
| 85 | + foreach ($viewBase->clsForm as $form) { | |
| 86 | + $html .= $form->RenderHTML(); | |
| 87 | + } | |
| 88 | + | |
| 89 | + $html .= $form->getAppendedOutput(); | |
| 90 | + $html .= $viewBase->MakeFootHtml(); | |
| 91 | + | |
| 92 | + echo $html; | |
| 93 | + } | |
| 94 | + | |
| 95 | + | |
| 96 | + // inicia um novo processo de redefinição de senha, quando nao recebe um token | |
| 97 | + protected function _initNovo() | |
| 98 | + { | |
| 99 | + return ! isset($_GET['token']); | |
| 100 | + } | |
| 101 | + | |
| 102 | + | |
| 103 | + // continua o processo de redefinição de senha, quando recebe o token | |
| 104 | + protected function _initEditar() | |
| 105 | + { | |
| 106 | + return isset($_GET['token']); | |
| 107 | + } | |
| 108 | + | |
| 109 | + | |
| 110 | + public function Gerar() | |
| 111 | + { | |
| 112 | + if (! isset($_GET['token'])) | |
| 113 | + $this->GerarNovo(); | |
| 114 | + else | |
| 115 | + $this->GerarEditar(); | |
| 116 | + | |
| 117 | + $this->url_cancelar = '/intranet/index.php'; | |
| 118 | + $this->nome_url_sucesso = 'Redefinir'; | |
| 119 | + } | |
| 120 | + | |
| 121 | + | |
| 122 | + protected function GerarNovo() { | |
| 123 | + $this->nome_url_cancelar = 'Entrar'; | |
| 124 | + $matricula = $_POST['matricula']; | |
| 125 | + | |
| 126 | + if (empty($matricula) && is_numeric($this->getOption('id_usuario'))) { | |
| 127 | + $user = Portabilis_Utils_User::load($id = $this->getOption('id_usuario')); | |
| 128 | + $matricula = $user['matricula']; | |
| 129 | + } | |
| 130 | + | |
| 131 | + $this->campoTexto('matricula', $this->_getLabel('matricula'), $matricula, | |
| 132 | + 50, 50, TRUE, FALSE, FALSE, $this->_getHelp('matricula')); | |
| 133 | + | |
| 134 | + echo Portabilis_Utils_ReCaptcha::getWidget(); | |
| 135 | + $this->reCaptchaFixup(); | |
| 136 | + } | |
| 137 | + | |
| 138 | + | |
| 139 | + protected function GerarEditar() | |
| 140 | + { | |
| 141 | + $this->loadUserByStatusToken('redefinir_senha-' . $_GET['token']); | |
| 142 | + | |
| 143 | + $this->campoRotulo('matricula', $this->_getLabel('matricula'), $this->getEntity()->matricula); | |
| 144 | + $this->campoSenha('password', $this->_getLabel('nova_senha'), @$_POST['password'], TRUE); | |
| 145 | + $this->campoSenha('password_confirmation', $this->_getLabel('confirmacao_senha'), @$_POST['password_confirmation'], TRUE); | |
| 146 | + } | |
| 147 | + | |
| 148 | + | |
| 149 | + public function Novo() | |
| 150 | + { | |
| 151 | + if (! $this->messenger()->hasMsgWithType('error')) { | |
| 152 | + if (! Portabilis_Utils_ReCaptcha::getWidget()->validate()) { | |
| 153 | + $this->messenger()->append('Por favor, informe a confirmação visual no respectivo campo.', 'error'); | |
| 154 | + } | |
| 155 | + elseif ($this->loadUserByMatricula($_POST['matricula'])) | |
| 156 | + $this->sendResetPasswordMail(); | |
| 157 | + } | |
| 158 | + | |
| 159 | + return ! $this->messenger()->hasMsgWithType('error'); | |
| 160 | + } | |
| 161 | + | |
| 162 | + | |
| 163 | + public function Editar() | |
| 164 | + { | |
| 165 | + if (! $this->messenger()->hasMsgWithType('error') && $this->loadUserByStatusToken('redefinir_senha-' . $_GET['token'])) | |
| 166 | + $this->updatePassword(); | |
| 167 | + | |
| 168 | + return ! $this->messenger()->hasMsgWithType('error'); | |
| 169 | + } | |
| 170 | + | |
| 171 | + | |
| 172 | + protected function updatePassword() { | |
| 173 | + $user = $this->getEntity(); | |
| 174 | + | |
| 175 | + try { | |
| 176 | + if ($this->canUpdate($user)) { | |
| 177 | + $user->setOptions(array('senha' => md5($_POST['password']), 'status_token' => '', 'data_troca_senha' => 'now()')); | |
| 178 | + $this->getDataMapper()->save($user); | |
| 179 | + | |
| 180 | + $linkToReset = $_SERVER['HTTP_HOST'] . $this->getRequest()->getBaseurl() . '/' . 'Usuario/RedefinirSenha'; | |
| 181 | + UsuarioMailer::updatedPassword($user = $this->getEntity(), $linkToReset); | |
| 182 | + | |
| 183 | + // #FIXME adicionar flash ao session, para persistr ao redirecionar ? | |
| 184 | + $this->messenger()->append('Senha alterada com sucesso.', 'success'); | |
| 185 | + | |
| 186 | + $this->logInUser(); | |
| 187 | + } | |
| 188 | + } | |
| 189 | + catch (Exception $e) { | |
| 190 | + $this->messenger()->append('Erro ao atualizar de senha.', 'error'); | |
| 191 | + error_log("Exception ocorrida ao atualizar senha, matricula: {$user->matricula}, erro: " . $e->getMessage()); | |
| 192 | + } | |
| 193 | + } | |
| 194 | + | |
| 195 | + | |
| 196 | + protected function canUpdate($user) | |
| 197 | + { | |
| 198 | + return UsuarioValidator::validatePassword($this->messenger(), | |
| 199 | + $user->senha, | |
| 200 | + $_POST['password'], | |
| 201 | + $_POST['password_confirmation'], | |
| 202 | + md5($_POST['password']), | |
| 203 | + $user->matricula); | |
| 204 | + } | |
| 205 | + | |
| 206 | + | |
| 207 | + protected function setTokenRedefinicaoSenha() { | |
| 208 | + $user = $this->getEntity(); | |
| 209 | + try { | |
| 210 | + $token = md5(uniqid($user->email)); | |
| 211 | + $statusToken = 'redefinir_senha-' . $token; | |
| 212 | + | |
| 213 | + $user->setOptions(array('status_token' => $statusToken)); | |
| 214 | + $this->getDataMapper()->save($user); | |
| 215 | + return $token; | |
| 216 | + } | |
| 217 | + catch (Exception $e) { | |
| 218 | + $this->messenger()->append('Erro ao setar token redefinição de senha.', 'error'); | |
| 219 | + error_log("Exception ocorrida ao setar token reset senha, matricula: {$user->matricula}, erro: " . $e->getMessage()); | |
| 220 | + return false; | |
| 221 | + } | |
| 222 | + } | |
| 223 | + | |
| 224 | + | |
| 225 | + protected function loadUserByStatusToken($statusToken) { | |
| 226 | + $result = false; | |
| 227 | + try { | |
| 228 | + if(empty($statusToken) && ! is_numeric($statusToken)) | |
| 229 | + $this->messenger()->append('Deve ser recebido um token.', 'error'); | |
| 230 | + else { | |
| 231 | + $user = $this->getDataMapper()->findAllUsingPreparedQuery(array(), | |
| 232 | + array('status_token' => '$1'), | |
| 233 | + array($statusToken), | |
| 234 | + array(), | |
| 235 | + false); | |
| 236 | + | |
| 237 | + if(! empty($user) && ! empty($user[0]->ref_cod_pessoa_fj)) { | |
| 238 | + $this->setEntity($user[0]); | |
| 239 | + $result = true; | |
| 240 | + } | |
| 241 | + else | |
| 242 | + $this->messenger()->append('Link inválido ou já utilizado, por favor, <a class="light decorated" href="RedefinirSenha">solicite a redefinição de senha novamente</a>.', 'error', false, 'error'); | |
| 243 | + } | |
| 244 | + } | |
| 245 | + catch (Exception $e) { | |
| 246 | + $this->messenger()->append('Ocorreu um erro inesperado ao recuperar o usuário, por favor, ' . | |
| 247 | + 'tente novamente.', 'error'); | |
| 248 | + | |
| 249 | + error_log("Exception ocorrida ao redefinir senha (loadUserByStatusToken), " . | |
| 250 | + "matricula: $matricula, erro: " . $e->getMessage()); | |
| 251 | + } | |
| 252 | + | |
| 253 | + return $result; | |
| 254 | + } | |
| 255 | + | |
| 256 | + | |
| 257 | + protected function loadUserByMatricula($matricula) { | |
| 258 | + $result = false; | |
| 259 | + $user = null; | |
| 260 | + | |
| 261 | + try { | |
| 262 | + if(empty($matricula) && ! is_numeric($matricula)) | |
| 263 | + $this->messenger()->append('Informe uma matrícula.', 'error'); | |
| 264 | + else { | |
| 265 | + $user = $this->getDataMapper()->findAllUsingPreparedQuery(array(), | |
| 266 | + array('matricula' => '$1'), | |
| 267 | + array($matricula), | |
| 268 | + array(), | |
| 269 | + false); | |
| 270 | + | |
| 271 | + if(! empty($user) && ! empty($user[0]->ref_cod_pessoa_fj)) { | |
| 272 | + $this->setEntity($user[0]); | |
| 273 | + $result = true; | |
| 274 | + } | |
| 275 | + else | |
| 276 | + $this->messenger()->append('Nenhum usuário encontrado com a matrícula informada.', | |
| 277 | + 'error', false, 'error'); | |
| 278 | + } | |
| 279 | + } | |
| 280 | + catch (Exception $e) { | |
| 281 | + $this->messenger()->append('Ocorreu um erro inesperado ao recuperar o usuário, por favor, ' . | |
| 282 | + 'verifique o valor informado e tente novamente.', 'error'); | |
| 283 | + | |
| 284 | + error_log("Exception ocorrida ao redefinir senha (loadUserByMatricula), " . | |
| 285 | + "matricula: $matricula, erro: " . $e->getMessage()); | |
| 286 | + } | |
| 287 | + | |
| 288 | + return $result; | |
| 289 | + } | |
| 290 | + | |
| 291 | + | |
| 292 | + protected function sendResetPasswordMail() { | |
| 293 | + $user = $this->getEntity(); | |
| 294 | + | |
| 295 | + if(empty($user->email)) { | |
| 296 | + $this->messenger()->append('Parece que seu usuário não possui um e-mail definido, por favor, '. | |
| 297 | + 'solicite ao administrador do sistema para definir seu e-mail (em DRH > Cadastro '. | |
| 298 | + 'de funcionários) e tente novamente.', 'error'); | |
| 299 | + } | |
| 300 | + else { | |
| 301 | + $token = $this->setTokenRedefinicaoSenha(); | |
| 302 | + | |
| 303 | + if ($token != false) { | |
| 304 | + $link = $_SERVER['HTTP_REFERER'] . "?token=$token"; | |
| 305 | + | |
| 306 | + if(UsuarioMailer::passwordReset($user, $link)) { | |
| 307 | + $successMsg = 'Enviamos um e-mail para você, por favor, clique no link recebido para redefinir sua senha.'; | |
| 308 | + $this->messenger()->append($successMsg, 'success'); | |
| 309 | + } | |
| 310 | + else { | |
| 311 | + $errorMsg = 'Não conseguimos enviar um e-mail para você, por favor, tente novamente mais tarde.'; | |
| 312 | + $this->messenger()->append($errorMsg, 'error'); | |
| 313 | + } | |
| 314 | + | |
| 315 | + } | |
| 316 | + } | |
| 317 | + } | |
| 318 | + | |
| 319 | + | |
| 320 | + public function logInUser() | |
| 321 | + { | |
| 322 | + $controlador = new clsControlador(); | |
| 323 | + | |
| 324 | + // #TODO migrar para Portabilis_Utils_User carregar usuário usando funcionario data mapper | |
| 325 | + // e então nesta classe usar $this->getEntity | |
| 326 | + $user = Portabilis_Utils_User::load($id = $this->getEntity()->ref_cod_pessoa_fj); | |
| 327 | + | |
| 328 | + if ($controlador->canStartLoginSession($user)) | |
| 329 | + $controlador->startLoginSession($user, '/intranet/index.php'); | |
| 330 | + | |
| 331 | + $this->messenger()->merge($controlador->messages); | |
| 332 | + } | |
| 333 | + | |
| 334 | + | |
| 335 | + // fixup para mover o widget para o local correto, necessário pois chrome não executa | |
| 336 | + // o script caso seja usado $this->campoRotulo('...', '...', '<script...>') | |
| 337 | + protected function reCaptchaFixup() { | |
| 338 | + $this->campoRotulo('replace_by_recaptcha_widget_wrapper', | |
| 339 | + 'Confirmação visual', | |
| 340 | + '<div id="replace_by_recaptcha_widget"></div>'); | |
| 341 | + | |
| 342 | + $js = "function replaceRecaptchaWidget() { | |
| 343 | + var emptyElement = document.getElementById('replace_by_recaptcha_widget'); | |
| 344 | + var originElement = document.getElementById('recaptcha_widget_div'); | |
| 345 | + emptyElement.parentNode.replaceChild(originElement, emptyElement); | |
| 346 | + } | |
| 347 | + | |
| 348 | + window.onload = replaceRecaptchaWidget;"; | |
| 349 | + | |
| 350 | + Portabilis_View_Helper_Application::embedJavascript($this, $js); | |
| 351 | + } | |
| 352 | + | |
| 353 | +} | |
| 354 | +?> | ... | ... |