Example #1
0
 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!');
         }
     }
 }
 /**
  * Validate the user password
  *
  * @author Arvind Singh
  * @access public
  *
  * @param string $password
  *            // Password string
  *
  * @param string $hash
  *            // Hash string
  *
  * @return boolean
  */
 public function verify($password, $hash)
 {
     if ($this->method == 'md5') {
         return $hash == md5($this->salt . $password);
     } elseif ($this->method == 'sha1') {
         return $hash == sha1($this->salt . $password);
     } elseif ($this->method == 'bcrypt') {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         return $bcrypt->verify($password, $hash);
     }
 }
Example #3
0
 public function doPostAction()
 {
     $username = $_POST['username'];
     $bcrypt = new Bcrypt(15);
     if ($bcrypt->verify($_POST['password'], $this->User->getUserPassword($username))) {
         $_SESSION['username'] = $username;
         $this->sendMainPage();
     } else {
         $this->setMessage('Data login Anda salah!');
         $this->sendLoginPage();
     }
 }
Example #4
0
 public function post($f3)
 {
     if ($this->authForm->isValid($f3->get('POST'))) {
         $users = $this->getDB('users');
         $user = $users->findOne(array('email=?', $f3->get('POST.email')));
         $crypt = \Bcrypt::instance();
         if ($user->mailvalidation) {
             $f3->set('SESSION.errormsg', 'Account nicht aktiviert!');
             $f3->reroute('/auth');
         } elseif ($crypt->verify($f3->get('POST.password'), $user->password)) {
             $f3->set('SESSION.user', array('id' => $user->id, 'email' => $user->email, 'raidleader' => $user->raidleader, 'admin' => $user->admin));
             if ($f3->get('GET.url')) {
                 $f3->reroute($f3->get('GET.url'));
             } else {
                 $f3->reroute('/');
             }
         } else {
             $f3->set('SESSION.errormsg', 'EMail oder Passwort falsch');
             $f3->reroute('/auth');
         }
     } else {
         $f3->set('SESSION.failedFields', array_keys($this->authForm->getFailedFields()));
         $f3->set('SESSION.errormsg', implode("<br>", $this->authForm->getFailedFields()));
         $f3->reroute('/auth');
     }
 }
Example #5
0
 function Set($f3)
 {
     if (!\Check::confirm('POST.password')) {
         $this->flash('Konfirmasi Password Tidak Cocok');
         $f3->reroute($f3->get('URI'));
     }
     $post = $f3->get('POST');
     $db_host = $post['DB_HOST'];
     $db_name = $post['DB_NAME'];
     $db_user = $post['DB_USER'];
     $db_pass = $post['DB_PASS'];
     $dsn = "mysql:host={$db_host};port=3306;dbname={$db_name}";
     $db = new \DB\SQL($dsn, $db_user, $db_pass);
     try {
         $db->begin();
         $db->exec(explode(';', $f3->read('installation/install.sql')));
         $user = new \DB\SQL\Mapper($db, 'user');
         $user->username = $post['username'];
         $user->password = \Bcrypt::instance()->hash($post['password']);
         $user->type = 1;
         $user->save();
         $key = bin2hex(openssl_random_pseudo_bytes(32));
         $data = "[globals]\nDEBUG=0\nAUTOLOAD=\"controller/;model/\"\nUI=\"view/\"\nAPP_KEY=\"{$key}\"\nDB_SET=\"{$dsn}\"\nDB_USER=\"{$db_user}\"\nDB_PASS=\"{$db_pass}\"";
         $f3->write('config/config.ini', $data);
         $f3->write('config/route.ini', $f3->read('installation/route.ini'));
         $db->commit();
         $this->flash('Success... Silahkan Hapus Folder Installation', 'success');
     } catch (Exception $e) {
         $db->rollback();
         $this->flash($e->getMessage());
         $f3->reroute('/');
     }
     $f3->reroute('/');
 }
 /**
  * crypt password
  * Defines whether to use bcrypt or salted MD5
  * @param $val
  * @return string
  */
 public function set_password($val)
 {
     $f3 = \Base::instance();
     if (!$val) {
         $userDetails = new self();
         $userDetails->load(array('username = ?', $f3->get('POST.username')));
         $val = $userDetails->password;
         return $val;
     } else {
         $hash_engine = $f3->get('password_hash_engine');
         switch ($hash_engine) {
             case 'bcrypt':
                 $crypt = \Bcrypt::instance();
                 $val = $crypt->hash($val);
                 break;
             case 'md5':
                 // fall-through
             // fall-through
             default:
                 $val = md5($val . $f3->get('password_md5_salt'));
                 break;
         }
         return $val;
     }
 }
 /**
  * Login Procedure
  * @param $f3
  * @param $params
  */
 public function login($f3, $params)
 {
     if ($f3->exists('POST.username') && $f3->exists('POST.password')) {
         sleep(3);
         // login should take a while to kick-ass brute force attacks
         $user = new \Model\User();
         $user->load(array('username = ?', $f3->get('POST.username')));
         if (!$user->dry()) {
             // check hash engine
             $hash_engine = $f3->get('password_hash_engine');
             $valid = false;
             if ($hash_engine == 'bcrypt') {
                 $valid = \Bcrypt::instance()->verify($f3->get('POST.password'), $user->password);
             } elseif ($hash_engine == 'md5') {
                 $valid = md5($f3->get('POST.password') . $f3->get('password_md5_salt')) == $user->password;
             }
             if ($valid) {
                 @$f3->clear('SESSION');
                 //recreate session id
                 $f3->set('SESSION.user_id', $user->_id);
                 if ($f3->get('CONFIG.ssl_backend')) {
                     $f3->reroute('https://' . $f3->get('HOST') . $f3->get('BASE') . '/');
                 } else {
                     $f3->reroute('/cnc');
                 }
             }
         }
         \Flash::instance()->addMessage('Wrong Username/Password', 'danger');
     }
     $this->response->setTemplate('templates/login.html');
 }
Example #8
0
 private static function getRandomBytes($count)
 {
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
         // OpenSSL slow on Win
         $bytes = openssl_random_pseudo_bytes($count);
     }
     if ($bytes === '' && is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
         $bytes = fread($hRand, $count);
         fclose($hRand);
     }
     if (strlen($bytes) < $count) {
         $bytes = '';
         if (self::$randomState === null) {
             self::$randomState = microtime();
             if (function_exists('getmypid')) {
                 self::$randomState .= getmypid();
             }
         }
         for ($i = 0; $i < $count; $i += 16) {
             self::$randomState = md5(microtime() . self::$randomState);
             if (PHP_VERSION >= '5') {
                 $bytes .= md5(self::$randomState, true);
             } else {
                 $bytes .= pack('H*', md5(self::$randomState));
             }
         }
         $bytes = substr($bytes, 0, $count);
     }
     return $bytes;
 }
Example #9
0
 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);
     }
 }
Example #10
0
 /**
  *  @see SqlMapper::__set($key, $value);
  */
 function __set($key, $value)
 {
     if ($key == "password") {
         $value = Bcrypt::instance()->hash($value, $this->createSalt(), 14);
     }
     parent::__set($key, $value);
 }
Example #11
0
 static function _beforeSave($self)
 {
     $pass = $self->get('password');
     $crypt = \Bcrypt::instance();
     if ($crypt->needs_rehash($pass)) {
         $self->set('password', $crypt->hash($pass));
     }
 }
Example #12
0
 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());
     }
 }
Example #13
0
 function tryLogin($entered, $savedHash)
 {
     try {
         Bcrypt::check($entered, $savedHash);
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
Example #14
0
 public function login()
 {
     $fw = Base::instance();
     if (!$this->map->dry()) {
         return true;
     } else {
         $this->map->load([$this->prop['username'] . '=:u', ':u' => $fw['POST.' . $this->prop['username']]], ['limit' => 1]);
         if ($this->map->dry() || !\Bcrypt::instance()->verify($fw['POST.' . $this->prop['password']], $this->map->get($this->prop['password']))) {
             $fw['error'] = 'Login gagal!';
             return false;
         }
     }
     $this->isLogged = true;
     return $this->setSession($this->map->get($this->prop['id']), $this->map->cast());
 }
Example #15
0
function loggedIn()
{
    global $mysqli;
    if (isset($_SESSION['id']) && isset($_SESSION['secret'])) {
        $id = intval($_SESSION['id']);
        $check = $mysqli->query("SELECT users.secret FROM users WHERE users.id = {$id} LIMIT 1");
        $results = $check->fetch_assoc();
        if (Bcrypt::check($_SESSION['secret'], $results['secret'])) {
            return $id;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 /**
  * crypt password
  * @param $val
  * @return string
  */
 public function set_password($val)
 {
     $f3 = \Base::instance();
     $hash_engine = $f3->get('password_hash_engine');
     switch ($hash_engine) {
         case 'bcrypt':
             $crypt = \Bcrypt::instance();
             $val = $crypt->hash($val);
             break;
         case 'md5':
             // fall-through
         // fall-through
         default:
             $val = md5($val . $f3->get('password_md5_salt'));
             break;
     }
     return $val;
 }
Example #17
0
 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;
     }
 }
Example #18
0
if (ini_get('register_globals')) {
    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>
 public function actionGenerarPassword()
 {
     echo Bcrypt::check("CNBDGFAA");
 }
Example #20
0
<?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!';
}
Example #21
0
 /**
  * @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;
 }
Example #22
0
<?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']);
Example #23
0
 static function pass($pass, $hash)
 {
     return (bool) Bcrypt::instance()->verify($pass, $hash);
 }
Example #24
0
<?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']}");
Example #25
0
 /**
  * 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);
 }
Example #26
0
 /**
  * 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'));
 }
 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;
     }
 }
Example #28
0
 /**
  * verify a user by his password
  * @param $password
  * @return bool
  */
 public function verify($password)
 {
     $valid = false;
     if (!$this->dry()) {
         $valid = (bool) \Bcrypt::instance()->verify($password, $this->password);
     }
     return $valid;
 }
Example #29
0
 public static function checkhash($current, $stored)
 {
     $algo = self::config()->hash;
     if ($algo == 'bcrypt') {
         return Bcrypt::check($current, $stored);
     } else {
         if (self::config()->useEncryptedPassword == true) {
             $current = self::hash($current);
         }
         return $current == $stored;
     }
 }
Example #30
0
<?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()
    {