public function index() { $classe = strtolower(__CLASS__); $function = strtolower(__FUNCTION__); $data['classe'] = $classe; $data['function'] = $function; $data['action'] = base_url() . $classe . '/' . $function; $this->form_validation->set_rules($this->validate); $this->form_validation->set_message('required', 'O campo "{field}" é obrigatório'); $this->form_validation->set_message('valid_email', 'O campo {"field}" deve ser um E-mail válido'); $this->form_validation->set_message('is_unique', '"{field}" inválido'); $this->form_validation->set_message('max_length', 'O campo "{field}" não pode exceder o tamanho de "{param}" caracteres'); $this->form_validation->set_message('integer', 'O campo "{field}" deve ser um número'); if ($this->form_validation->run()) { $post = $this->_post(); $post['password'] = Bcrypt::hash($post['password']); $post['date_create'] = date('Y-m-d'); $id = $this->users_model->insert($post); $data['info']['error'] = $id ? 0 : 1; $data['info']['message'] = $id ? 'Dados salvos com sucesso.' : 'Ocorreu um erro ao salvar os dados. Por favor tente novamente mais tarde.'; $this->layout->set_title('Faz, Que Falta - Cadastro')->set_keywords('Faz, Que Falta - Cadastro')->set_description('Faça o seu cadastro na plataforma do Faz, Que Falta e veja a diferença no seu bairro.')->set_view('site/register/index', $data); } else { $this->layout->set_title('Faz, Que Falta - Cadastro')->set_keywords('Faz, Que Falta - Cadastro')->set_description('Faça o seu cadastro na plataforma do Faz, Que Falta e veja a diferença no seu bairro.')->set_includes('js/mask/jquery.mask.js')->set_includes('js/register.js')->set_view('site/register/index', $data); } }
public function doPostAction() { if ($this->Setting->getSuperAdminUserName()) { if ($this->isUserLoggedIn()) { $this->sendMainPage(); } else { $this->sendLoginPage(); } } else { if ($_POST['password'] === $_POST['password_verification']) { try { $this->dbSource->startTransaction(); $this->Setting->insertSiteTitle($_POST['siteTitle']); $bcrypt = new Bcrypt(15); $superuser = array('username' => $_POST['username'], 'password' => $bcrypt->hash($_POST['password'])); $this->User->insert($superuser); $this->Setting->insertSuperAdminUserName($superuser['username']); $rootAncestor = array('uuid' => uniqid(), 'name' => $_POST['rootAncestorName'], 'gender' => $_POST['rootAncestorGender'], 'person_type' => 'R'); $this->Person->insert($rootAncestor); $this->Setting->insertRootAncestorUuid($rootAncestor['uuid']); $this->dbSource->commit(); $_SESSION['username'] = $superuser['username']; $this->setMessage('Instalasi berhasil.'); $this->sendMainPage(); } catch (Exception $e) { $this->dbSource->rollback(); $this->setMessage('Instalasi gagal: ' . $e->getMessage()); } } else { $this->setView('admin/install'); $this->setSiteTitle($this->Setting->getSiteTitle() . ' - Install'); $this->setMessage('Password yang Anda masukkan tidak cocok!'); } } }
function testDontNeedRehash() { // create hash using default cost $password = new Bcrypt(); $hash = $password->hash('test'); $this->assertEquals(true, $password->verify('test', $hash)); $this->assertEquals(false, $password->needsRehash($hash, $password->getCost())); }
public function doPostAction() { $bcrypt = new Bcrypt(15); $this->setView('admin/change_password'); try { $username = $this->Setting->getSuperAdminUserName(); if ($bcrypt->verify($_POST['old_password'], $this->User->getUserPassword($username)) && $_POST['new_password'] === $_POST['new_password_verification']) { $superuser = array('username' => $username, 'password' => $bcrypt->hash($_POST['new_password'])); $this->User->updateRecord($superuser); $this->setMessage('Password berhasil diganti.'); } else { $this->setMessage('Password yang Anda masukkan tidak sama!'); } } catch (Exception $e) { $this->setMessage('Password gagal diganti: ' . $e->getMessage()); } }
public function updateHashAcesso(usuariosModel $usuariosModel) { $this->db->clear(); $this->db->setTabela('sys_usuarios_acessos'); $data = array('id_usuario' => $usuariosModel->getId(), 'data_acesso' => date('Y-m-d'), 'hora_acesso' => date('H:i:s'), 'ip_acesso' => $this->getIp()); $this->db->insert($data); //cria o token de segurança para verificação do login $hash = Bcrypt::hash(date('YmdHis')); $dataValue = array('hash_acesso' => $hash); $this->db->clear(); $this->db->setTabela('sys_usuarios'); $this->db->setCondicao('id_usuario = ? '); $this->db->setParameter(1, $usuariosModel->getId()); if ($this->db->update($dataValue)) { return $hash; } else { return null; } }
/** * Check behaviour of `Bcrypt::check()`. * * @return void */ public function testCheck() { // hashes used for one time only, well, two times :) $hash1 = Bcrypt::hash('test123'); $hash2 = Bcrypt::hash('password123'); // test using already generated hashes $this->assertTrue(Bcrypt::check('test123', $hash1)); $this->assertTrue(Bcrypt::check('password123', $hash2)); $this->assertFalse(Bcrypt::check('test123', $hash2)); $this->assertFalse(Bcrypt::check('password123', $hash1)); // generate new hash each time $this->assertTrue(Bcrypt::check('test123', Bcrypt::hash('test123'))); $this->assertTrue(Bcrypt::check('password123', Bcrypt::hash('password123'))); $this->assertFalse(Bcrypt::check('test123', Bcrypt::hash('password123'))); $this->assertFalse(Bcrypt::check('password123', Bcrypt::hash('test123'))); // what happens if the hash is wrong? $this->assertFalse(Bcrypt::check('test123', 'WrongHash')); $this->assertFalse(Bcrypt::check('password123', 'AnotherWrongHash')); }
public function hash_password($plaintextpwd) { $bcrypt = new Bcrypt(15); $hash = $bcrypt->hash($plaintextpwd); $isGood = $bcrypt->verify($plaintextpwd, $hash); if ($isGood) { return $hash; } else { return false; } }
/** * Given a cleartext password, generate a hash that can later * be used to verify the content of the password used to create it. * @param String cleartext password * @return String a hash of the password */ public static function hashPassword($cleartext) { $bcrypt = new Bcrypt(12); return $bcrypt->hash($cleartext . config('auth.salt')); }
<?php include "{$CONFIG['SITE_DIR']}inc/classes/Bcrypt.php"; if ($_POST['pass1'] != $_POST['pass2']) { error("Your passwords do not match."); die; } $username = $mysqli->real_escape_string($_POST['username']); $password = $mysqli->real_escape_string($_POST['pass1']); $time = time(); $check = $mysqli->query("SELECT COUNT(*) FROM users WHERE username = '******'"); $checked = $check->fetch_assoc(); if ($checked['COUNT(*)'] > 0) { error("That username is already being used."); die; } $hash = Bcrypt::hash($password); $mysqli->query("INSERT INTO users (`username`,`password`,`datestamp`) VALUES ('{$username}','{$hash}',{$time})"); header("Location: {$_SERVER['HTTP_REFERER']}");
public function editar($codigo = '', $ok = FALSE) { if (isset($codigo) && $codigo) { $dados = $this->users_model->get_item('ctp_users.id = ' . $codigo); $this->form_validation->set_rules($this->validate); $this->form_validation->set_message('required', 'O campo "{field}" é obrigatório'); $this->form_validation->set_message('valid_email', 'O campo "{field}" deve ser um E-mail válido'); $this->form_validation->set_message('is_unique', 'O campo "{field}" deve ser unico'); $this->form_validation->set_message('max_length', 'O campo "{field}" não pode exceder o tamanho de "{param}" caracteres'); $this->form_validation->set_message('min_length', 'O campo "{field}" dever ter no minimo "{param}" caracteres'); $this->form_validation->set_message('integer', 'O campo "{field}" dever ser numérico'); if ($this->form_validation->run()) { $data = $this->_post(); if (isset($data['password']) && !empty($data['password'])) { $data['password'] = Bcrypt::hash($data['password']); } else { unset($data['password']); } $data['filtro'] = 'ctp_users.id = ' . $codigo; $data_neighborhood['id_city'] = $data['id_city']; $data_neighborhood['description'] = $data['neighborhood']; $data_neighborhood['filtro'] = 'ctp_neighborhood.id = ' . $dados->id_neighborhood; $data_address['zip_code'] = $data['zip_code']; $data_address['street'] = $data['street']; $data_address['number'] = $data['number']; $data_address['complement'] = $data['complement']; $data_address['filtro'] = 'ctp_address.id = ' . $dados->id_address; $data = $this->_unset_fields($data); $this->_update($data_neighborhood, $data_address, $data); if ($this->session->userdata['id'] == $codigo) { $session = array('nome' => $data['name'], 'tipo' => $data['id_type_user']); } $this->session->set_userdata($session); redirect('admin/usuarios/editar/' . $codigo . '/1'); } else { $classe = strtolower(__CLASS__); $function = strtolower(__FUNCTION__); $data['classe'] = $classe; $data['function'] = $function; $data['action'] = base_url() . 'admin/' . $classe . '/' . $function . '/' . $codigo; $data['states'] = $this->get_state(); $data['types_user'] = $this->get_type_user(); $data['item'] = $dados; $data['ok'] = isset($ok) && $ok ? TRUE : FALSE; $this->layout->set_title('Admin - Usuários - Editar')->set_description('')->set_keywords('')->set_includes('js/mask/jquery.mask.js')->set_includes('js/users.js')->set_breadcrumbs('Painel', 'admin/painel/', 0)->set_breadcrumbs('Usuarios', 'admin/usuarios/', 0)->set_breadcrumbs('Editar', 'admin/usuarios/editar', 1)->set_view('admin/users/add_users', $data, 'template/admin/'); } } else { redirect('painel'); } }
<?php echo '<meta charset=UTF-8>'; include_once 'conexao/conecta.inc'; include_once 'funcoesUteis/funcoes.inc'; include_once 'classes/Bcrypt.class.php'; $email = $_REQUEST['login']; // email digitado no formulário $senhaProvisoria = gerarSenhaAleatoria(); echo 'Senha Provisória ' . $senhaProvisoria; // Agora temos que criptografar a senha provisória antes de atualizar as informações no banco de dados // utilizando a classe Bcrypt $senhaProvisoriaEncriptada = Bcrypt::hash($senhaProvisoria); //Fazer o select no banco e "confirmar de fato que o email existe" "Segunda vez só para garantir caso alguém altere // o código front-end (ajax)" $sqlConsulta = "SELECT EMAIL_USUARIO FROM USUARIO WHERE EMAIL_USUARIO = '{$email}'"; $resultConsulta = mysql_query($sqlConsulta); //$linhas = mysql_num_rows($resultConsulta); //echo 'Linhas '. $linhas; if (mysql_num_rows($resultConsulta) == 1) { $result = mysql_fetch_array($resultConsulta); $emailBanco = $result['EMAIL_USUARIO']; $sqlAtualizar = "UPDATE USUARIO SET SENHA_USUARIO = '{$senhaProvisoriaEncriptada}' WHERE EMAIL_USUARIO = '{$emailBanco}'"; if (mysql_query($sqlAtualizar)) { echo '<script>alert("Senha Atualizada !")</script>'; } else { echo '<script>alert("Não foi possível a atualização !")</script>'; } } else { echo 'Usuário não encontrado!'; }
/** * Função que verifica o email do usuario no banco, e se existir * criptografa uma nova senha, edita no banco e manda por email a nova senha do usuario. * Retorna TRUE se ocorrer tudo certo, False caso o email não seja aceito para entrega, ou * NULL caso ocorra erro de validação * * @param array $data * @return NULL|boolean */ public function recover_pass() { $this->form_validation->set_rules($this->validate_recover_pass); $this->form_validation->set_message('required', 'O campo "{field}" é obrigatório'); $this->form_validation->set_message('valid_email', 'O campo "{field}" deve ser um E-mail válido'); $this->form_validation->set_message('max_length', 'O campo "{field}" não pode exceder o tamanho de "{param}" caracteres'); if ($this->form_validation->run()) { $data = $this->_post(); $qtde = $this->users_model->get_password_by_email('ctp_users.email = "' . $data['email'] . '"'); if ($qtde > 0) { $password['password'] = Bcrypt::hash($data['email']); $update = $this->users_model->update('ctp_users.email = "' . $data['email'] . '"', $password); if ($update) { $email['from'] = '*****@*****.**'; $email['to'] = $data['email']; $email['subject'] = 'Recuperação de senha'; $email['message'] = 'Você solicitou a recuperação de senha.<br>'; $email['message'] .= 'Segue a nova senha de acesso ao Painel de Controle:<br>'; $email['message'] .= $password; $data['info'] = $this->send_email($email) ? 'Nova senha encaminhada ao e-mail informado.' : 'Erro ao tentar recuperar senha. Tente novamente mais tarde.'; } } } $class = strtolower(__CLASS__); $function = strtolower(__FUNCTION__); $data['action'] = base_url() . $class . '/' . $function; $data['action_back'] = base_url() . $class; $this->layout->set_title('Faz, Que Falta - Recuperar Senha')->set_view('site/login/add_password_recover', $data); }
$getPass = $mysqli->query("SELECT users.id,users.password FROM users WHERE users.username = '******' LIMIT 1"); $pass = $getPass->fetch_assoc(); function tryLogin($entered, $savedHash) { try { Bcrypt::check($entered, $savedHash); } catch (Exception $e) { return false; } return true; } if (tryLogin($_POST['password'], $pass['password'])) { $random = rand(100000, 999999); $_SESSION['id'] = $pass['id']; $_SESSION['secret'] = $random; $secret = Bcrypt::hash($_SESSION['secret']); $mysqli->query("UPDATE users SET users.secret = '{$secret}' WHERE users.id = {$pass['id']}"); header("Location: {$_SERVER['HTTP_REFERER']}"); } else { error("Incorrect login."); die; } } else { ?> <div id="login-form"> <h2 class="align-center" style="margin-top:0">Login</h2> <hr><br> <form action="<?php echo $CONFIG['SITE_URL']; ?>
public function editar($codigo = '', $ok = FALSE) { if (isset($codigo) && $codigo) { $dados = $this->model->get_item('nome_da_tabela.id = ' . $codigo); $this->form_validation->set_rules($this->valida); $this->form_validation->set_message('required', 'O campo %s é obrigatório'); $this->form_validation->set_message('valid_email', 'O campo %s deve ser um E-mail válido'); $this->form_validation->set_message('max_length', 'O campo %s não pode exceder o tamanho de %s caracteres'); if ($this->form_validation->run()) { $data = $this->_post(); if (isset($data['campo']) && !empty($data['campo'])) { $data['campo'] = Bcrypt::hash($data['campo']); } $id = $this->model->editar($data, 'nome_da_tabela.id = ' . $codigo); if ($this->session->userdata['id'] == $codigo) { $session = array('nome' => $data['nome'], 'tipo' => $data['tipo']); } $this->session->set_userdata($session); redirect('controller/editar/' . $codigo . '/1'); } else { $classe = strtolower(__CLASS__); $function = strtolower(__FUNCTION__); $data['classe'] = $classe; $data['function'] = $function; $data['action'] = base_url() . $classe . '/' . $function . '/' . $codigo; $data['item'] = $dados; $data['ok'] = isset($ok) && $ok ? TRUE : FALSE; $this->layout->set_breadcrumbs('Breadscrumbs', 'breadscrumbs/', 0)->set_breadcrumbs('Breadscrumbs', 'breadscrumbs/listar', 0)->set_breadcrumbs('Breadscrumbs', 'breadscrumbs/', 1)->set_view('add_views', $data); } } else { redirect('controller'); } }
/** * Cambia la clave del usuario a la clave pasada por parametro. * * @param string $clave clave nueva * @return boolean flag de exito */ public function cambiarClave($clave) { $bcrypt = new Bcrypt(self::BCRYPT_ROUNDS); $hash = $bcrypt->hash($clave); if ($hash === false) { return false; } else { $this['pass'] = $hash; return true; } }
public function create_or_update($user) { // creates or updates a user based on the parameters passed in $user and this object's attributes. // returns False if failure, or the ID of the user if success. // filter some parameters out first and replace them with their corresponding db fields. if (isset($user['password']) && $user['password'] != '') { $bcrypt = new Bcrypt(); $user['password_hash'] = $bcrypt->hash($user['password']); } unset($user['password']); unset($user['password_confirmation']); if (isset($user['usermask']) && intval(@array_sum($user['usermask'])) != 0) { $user['usermask'] = intval(@array_sum($user['usermask'])); } else { unset($user['usermask']); } $params = array(); foreach ($user as $parameter => $value) { if (!is_array($value)) { $params[] = "`" . $this->dbConn->real_escape_string($parameter) . "` = " . $this->dbConn->quoteSmart($value); } } //go ahead and register or update this user. if ($this->id != 0) { //update this user. $updateUser = $this->dbConn->stdQuery("UPDATE `users` SET " . implode(", ", $params) . " WHERE `id` = " . intval($this->id) . " LIMIT 1"); if (!$updateUser) { return False; } return intval($this->id); } else { // add this facility. $insertUser = $this->dbConn->stdQuery("INSERT INTO `users` SET " . implode(",", $params)); if (!$insertUser) { return False; } else { return intval($this->dbConn->insert_id); } } }
public function actionPass() { $bcrypt = new Bcrypt(12); $passes = array('xaby', 'marina', 'arturo', 'dani', 'pedro', 'manu', 'rober', 'marcos', 'alex', 'samu'); $result = array(); foreach ($passes as $pass) { $hash = $bcrypt->hash($pass); $check = $bcrypt->verify($pass, $hash); echo '<pre>'; print_r(array('pass' => $pass, 'hash' => $hash, 'check' => $check)); echo '</pre>'; } }
} while (1); return $output; } } $bcrypt = new Bcrypt(); function password_hash($password) { $bcrypt->hash($password); } function password_verify($password, $hash) { $bcrypt->verify($password, $hash); } if (isset($_GET['debug'])) { $debug = 1; $hash = $bcrypt->hash($_GET['debug']); } else { $debug = 0; } if ($debug) { echo "<fieldset><legend>Should return 1</legend>"; echo $hash . "<br>"; $isGood = $bcrypt->verify($_GET['debug'], $hash); echo "→ " . $isGood; echo "</fieldset>"; echo "<fieldset><legend>Should return 0</legend>"; echo $hash . "<br>"; $hash = "sdfsdf"; $isGood = $bcrypt->verify($_GET['debug'], $hash); echo "→ " . $isGood; echo "</fieldset>";
/** * Devuelve el hash del valor en el parámetro $value * @param $value * @return string */ public static function hash($value) { $algo = self::config()->hash; if ($algo == 'bcrypt') { return Bcrypt::hash($value); } else { return hash($algo, $value); } }
$la .= $form->ExitForm("submit"); $page->titulo = "Edit User"; $page->conteudo = $janela . $la . "</div></div>"; print $page->display_page(); } break; case "ActionEditUser": test_csrf(); $idedituser = sanitize(htmlentities($_POST['idedituser'])); $loginedit = sanitize(htmlentities($_POST['loginedit'])); $mailedit = sanitize(htmlentities($_POST['mailedit'])); $passedit = sanitize(htmlentities($_POST['passedit'])); $owneredit = sanitize(htmlentities($_POST['owneredit'])); $secret = $frase . $passedit; $gen = new Bcrypt(12); $bcrypt_hashedit = $gen->hash($secret); $crud->dbUpdate('userronin', 'login', $loginedit, 'id', $idedituser); $crud->dbUpdate('userronin', 'pass', $bcrypt_hashedit, 'id', $idedituser); $crud->dbUpdate('userronin', 'mail', $mailedit, 'id', $idedituser); $crud->dbUpdate('userronin', 'owner', $owneredit, 'id', $idedituser); $page->titulo = "Data edit of user"; $page->conteudo = '<br><br> <p class="message message-success message-closable">User edited OK !</p><br<br>'; print $page->display_page(); break; case "ListarUser": $janela .= '<div class="portlet portlet-closable x12"> <div class="portlet-header"> <h4>Users List</h4> </div> <!-- .portlet-header --> <div class="portlet-content">
<?php $bcrypt = new Bcrypt(15); $hash = $bcrypt->hash('password'); $isGood = $bcrypt->verify('password', $hash); class Bcrypt { private $_ci; public function __construct($_ci = 12) { if (CRYPT_BLOWFISH != 1) { throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt"); } $this->_ci =& get_instance(); $this->rounds = $_ci; } public function hash($input) { $hash = crypt($input, $this->_ci->getSalt()); if (strlen($hash) > 13) { return $hash; } return false; } public function verify($input, $existingHash) { $hash = crypt($input, $existingHash); return $hash === $existingHash; } private function getSalt() {
exit("<center><h3>Error: Turn that damned register globals off!</h3></center>"); } define('CAN_INCLUDE', true); require 'include/common.php'; error_reporting(E_ALL); ini_set('display_errors', '1'); if (file_exists('password.php')) { echo 'to assign a new password, first delete the password.php file.'; exit; } if (isset($_POST['password'])) { if ($_POST['password'] !== '') { require ROOT . 'include/func_crypt_random.php'; require ROOT . 'include/class_bcrypt.php'; $bcrypt = new Bcrypt(12); $hash = $bcrypt->hash($_POST['password']); } else { $hash = ''; } $output = "<?php\nif(ini_get('register_globals')) exit('<center><h3>Error: Turn that damned register globals off!</h3></center>');\nif(!defined('CAN_INCLUDE')) exit('<center><h3>Error: Direct access denied!</h3></center>');\n\n\$hash='{$hash}';\n\n?>"; echo '<textarea onclick="this.select();" style="vertical-align: top; width: 95%" rows=7>', htmlspecialchars($output, ENT_QUOTES, 'UTF-8'), '</textarea>'; echo '<br><br>Just put the above in a file named password.php'; file_put_contents('password0.php', $output); echo '<br>or<br>Rename password0.php to password.php'; require ROOT . 'include/home_link.php'; exit; } ?> <form action='' method=post> Enter empty password for no password.<br><br> Password: <input type=text name=password autocomplete="off"><input type=submit value=submit>
<?php echo '<meta charset=UTF-8>'; include_once 'conexao/conecta.inc'; include_once 'classes/Bcrypt.class.php'; $email = $_POST['login']; $senha = $_POST['senha']; $tipoUsuarioBanco = 'RES'; $statusUsuarioBanco = '1'; $senhaEncriptada = Bcrypt::hash($senha); $sql = "INSERT INTO usuario(EMAIL_USUARIO,SENHA_USUARIO,TIPO_USUARIO,STATUS_USUARIO)"; $sql .= " VALUES('{$email}','{$senhaEncriptada}', '{$tipoUsuarioBanco}','{$statusUsuarioBanco}')"; if (mysql_query($sql)) { echo '<script>alert("Sua conta foi criada !")</script>'; echo '<script>'; echo 'location.href="frmLogin.php"'; echo '</script>'; } else { echo '<script>alert("Não foi possível efetuar o cadastro")</script>'; echo '<script>'; echo 'location.href="frmLogin.php"'; echo '</script>'; }
/** * Convience function for hashing a string with Bcrypt. * * @see Bcrypt::hash() * * @param string $input The plain-text pasword to hash. * @return string|false The hashed password or false on error. */ function hash($plainText, $prefix = Bcrypt::DEFAULT_PREFIX, $rounds = Bcrypt::DEFAULT_ROUNDS) { /* Use the given prefix and given rounds. */ $bcrypt = new Bcrypt($prefix, $rounds); return $bcrypt->hash($plainText); }
<?php session_start(); require_once 'conn.php'; require_once '../libs/Bcrypt.php'; $bcrypt = new Bcrypt(15); $action = $_POST['action']; switch ($action) { case 'sign_up': $email = $_POST['email']; $password = $_POST['pword']; $salt = $bcrypt->getSalt(); $hash = $bcrypt->hash($password, $salt); if ($query = $db->prepare("INSERT INTO tbl_users SET email = ?, hashed_password = ?, salt = ?")) { $query->bind_param("sss", $email, $hash, $salt); $query->execute(); $uid = $query->insert_id; //create default settings for new user $select_networks = $db->query("SELECT network FROM tbl_networks"); if ($select_networks->num_rows > 0) { while ($row = $select_networks->fetch_object()) { $network = $row->network; $db->query("INSERT INTO tbl_settings SET network = '{$network}', uid = '{$uid}', status = 0"); } } echo $uid; } break; case 'login': $email = $db->real_escape_string($_POST['email']); $password = $db->real_escape_string($_POST['pword']);
/** * @brief Function Bcrypt * criptografa a senha, retornando a string criptografada, sendo criptografia de apenas uma via. * @param texto passado * @return texto criptografado */ public static function Bcrypt($password) { $hash = Bcrypt::hash($password); return $hash; }
function osc_hash_password($password) { if(version_compare(PHP_VERSION, '5.3.7')>=0) { $options = array('cost' => BCRYPT_COST); return password_hash($password, PASSWORD_BCRYPT, $options); } require_once LIB_PATH . 'Bcrypt.php'; if(CRYPT_BLOWFISH==1) { $bcrypt = new Bcrypt(BCRYPT_COST); return $bcrypt->hash($password); } return sha1($password); }
/** * Set the password for this user * @since Version 3.8.7 * @param string $password * @return $this */ public function setPassword($password = false) { if (!$password || empty($password)) { throw new Exception("Cannot set password - no password was provided"); } /** * Check to make sure it's not a shitty password */ if (!$this->safePassword($password)) { throw new Exception("Your desired password is unsafe. Please choose a different password."); } require_once "includes/bcrypt.class.php"; $BCrypt = new \Bcrypt(RP_BCRYPT_ROUNDS); $password = trim($password); $this->password = md5($password); $this->password_bcrypt = $BCrypt->hash($password); if (filter_var($this->id, FILTER_VALIDATE_INT)) { $this->commit(); $this->addNote("Password changed"); } }
public function actionRegistro() { if (!count($_POST)) { $this->redirect('terminos'); } if (!isset(Yii::app()->session['dir'])) { Yii::app()->session['dir'] = md5(time()); } $subgenero = isset($_POST["subgenero"]) ? $_POST["subgenero"] : null; $otrosOtro = isset($_POST["otrosOtro"]) ? $_POST["otrosOtro"] : null; //OJO: Verificar que llegue el checkbox de la página anterior (convocatoria) //o en su defecto los datos del formulario para validar $objFormularioRegistro = new RegistroForm(); //print_r($_POST['RegistroForm']); if (isset($_POST['RegistroForm'])) { $objFormularioRegistro->attributes = $_POST['RegistroForm']; if (isset(Yii::app()->session['dir'])) { $dir = Yii::app()->session['dir']; } if ($objFormularioRegistro->validate()) { $objUsuario = new Usuarios(); $transaction = $objUsuario->dbConnection->beginTransaction(); $objUsuario->username = $objFormularioRegistro->username; $objUsuario->password = Bcrypt::hash($objFormularioRegistro->password); $objUsuario->estado = 1; $objUsuario->roles_id = 1; if (!$objUsuario->save(false)) { $transaction->rollback(); } $idUsuario = $objUsuario->getPrimaryKey(); $objPerfiles = new Perfiles(); $objPerfiles->nombre = $objFormularioRegistro->nombrePropuesta; $objPerfiles->slug = $this->createSlug($objFormularioRegistro->nombrePropuesta); $objPerfiles->resena = $objFormularioRegistro->resena; $objPerfiles->web = $objFormularioRegistro->web; $objPerfiles->usuarios_id = $idUsuario; $objPerfiles->areas_id = $objFormularioRegistro->area; if (!$objPerfiles->save(false)) { $transaction->rollback(); } $idPerfil = $objPerfiles->getPrimaryKey(); $objRedesHasPerfil = new RedesHasPerfiles(); $objRedesHasPerfil->redes_id = 1; $objRedesHasPerfil->perfiles_id = $idPerfil; $objRedesHasPerfil->url = $objFormularioRegistro->twitter; if (!$objRedesHasPerfil->save(false)) { $transaction->rollback(); } $objRedesHasPerfil = new RedesHasPerfiles(); $objRedesHasPerfil->redes_id = 2; $objRedesHasPerfil->perfiles_id = $idPerfil; $objRedesHasPerfil->url = $objFormularioRegistro->fb; if (!$objRedesHasPerfil->save(false)) { $transaction->rollback(); } if (is_dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/foto_perfil/')) { $directorio = dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/foto_perfil/'); while ($archivo = $directorio->read()) { if ($archivo !== "." && $archivo !== ".." && $archivo !== "thumbnail") { $fotoPerfil = Yii::app()->request->baseUrl . '/files/' . $dir . '/foto_perfil/' . $archivo; $imgData = getimagesize(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/foto_perfil/' . $archivo); $objFotos = new Fotos(); $titulo = explode('.', $archivo); $objFotos->titulo = $titulo[0]; $objFotos->src = $fotoPerfil; $objFotos->thumb = Yii::app()->request->baseUrl . '/files/' . $dir . '/foto_perfil/thumbnail/' . $archivo; $objFotos->ancho = $imgData[0]; $objFotos->alto = $imgData[1]; $objFotos->es_perfil = 1; $objFotos->estado = 1; $objFotos->perfiles_id = $idPerfil; if (!$objFotos->save(false)) { $transaction->rollback(); } break; } } $directorio->close(); } if (is_dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/fotos/')) { $directorio = dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/fotos/'); while ($archivo = $directorio->read()) { if ($archivo !== "." && $archivo !== ".." && $archivo !== "thumbnail") { $foto = Yii::app()->request->baseUrl . '/files/' . $dir . '/fotos/' . $archivo; $objFotos = new Fotos(); $titulo = explode('.', $archivo); $objFotos->titulo = $titulo[0]; $objFotos->src = $foto; $imgData = getimagesize(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/fotos/' . $archivo); $objFotos->ancho = $imgData[0]; $objFotos->alto = $imgData[1]; $objFotos->thumb = Yii::app()->request->baseUrl . '/files/' . $dir . '/fotos/thumbnail/' . $archivo; $objFotos->es_perfil = 0; $objFotos->estado = 1; $objFotos->perfiles_id = $idPerfil; if (!$objFotos->save(false)) { $transaction->rollback(); } } } $directorio->close(); } if (is_dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/audios/')) { $directorio = dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/audios/'); while ($archivo = $directorio->read()) { if ($archivo !== "." && $archivo !== ".." && $archivo !== "thumbnail") { $url = Yii::app()->request->baseUrl . '/files/' . $dir . '/audios/' . $archivo; $objAudio = new Audios(); $titulo = explode('.', $archivo); $objAudio->nombre = $titulo[0]; $objAudio->url = $url; $objAudio->estado = 1; $objAudio->perfiles_id = $idPerfil; if (!$objAudio->save(false)) { $transaction->rollback(); } } } $directorio->close(); } $objPropuesta = new Propuestas(); $objPropuesta->nombre = $objFormularioRegistro->nombrePropuesta; $objPropuesta->representante = $objFormularioRegistro->representante; $objPropuesta->cedula = $objFormularioRegistro->cedula; $objPropuesta->telefono = $objFormularioRegistro->telefono; $objPropuesta->celular = $objFormularioRegistro->celular; $objPropuesta->email = $objFormularioRegistro->email; $objPropuesta->direccion = $objFormularioRegistro->direccion; $objPropuesta->trayectoria = $objFormularioRegistro->trayectoria; $objPropuesta->numero_integrantes = $objFormularioRegistro->numeroIntegrantes; $objPropuesta->resena = $objFormularioRegistro->resena; $objPropuesta->video = $objFormularioRegistro->video; $objPropuesta->estado = 1; $objPropuesta->valor_presentacion = $objFormularioRegistro->valor; $objPropuesta->subgenero = empty($subgenero) ? $otrosOtro : $subgenero; if (is_dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/rider/')) { $directorio = dir(Yii::getPathOfAlias('webroot') . '/files/' . $dir . '/rider/'); while ($archivo = $directorio->read()) { if ($archivo !== "." && $archivo !== ".." && $archivo !== "thumbnail") { $archivoRider = Yii::app()->request->baseUrl . '/files/' . $dir . '/rider/' . $archivo; break; } } $directorio->close(); } $objPropuesta->rider = $archivoRider; $objPropuesta->convocatorias_id = 1; $objPropuesta->perfiles_id = $idPerfil; if ($objPropuesta->save(false)) { $transaction->commit(); $this->redirect('exito'); } else { $transaction->rollback(); } } } //OJO cuando se guarden los datos exitosamente se debe llevar a otra pantalla. $this->pageTitle = "Registro Artístas"; $this->render('registro', array('subgenero' => $subgenero, 'otrosOtro' => $otrosOtro, 'formulario' => $objFormularioRegistro)); }
} // disabling - not sure this looks right } else { if (FALSE && ($action == 'updatehome' && $_SERVER['REQUEST_METHOD'] == 'POST')) { $key = isset($_POST['key']) ? trim($_POST['key']) : null; $email = isset($_POST['email']) ? trim($_POST['email']) : null; $set = array(); if (!$home) { exit; } if ($email) { array_push($set, '`email`="' . mysql_real_escape_string($email) . '"'); } if ($key) { $bcrypt = new Bcrypt(10); $hashed = $bcrypt->hash($key); array_push($set, '`key`="' . mysql_real_escape_string($hashed) . '"'); } if (!mysql_query(sprintf('UPDATE ownership SET %s WHERE `name`="%s"', implode($set, ', '), mysql_real_escape_string($home)))) { header("HTTP/1.1 500 Internal Server Error"); echo json_encode(array('ok' => false, 'error' => mysql_error())); exit; } if ($ajax) { echo json_encode(array('ok' => true, 'error' => false)); } else { header('Location: ' . PATH); } exit; } else { if ($action == 'forgot') {