Example #1
8
function add_member($username, $password)
{
    require 'password.php';
    try {
        define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
        define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
        define('DB_USER', getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
        define('DB_PASS', getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
        define('DB_NAME', getenv('OPENSHIFT_GEAR_NAME'));
        try {
            $dsn = 'mysql:dbname=members;host=' . DB_HOST . ';port=' . DB_PORT;
            $db = new PDO($dsn, DB_USER, DB_PASS);
        } catch (PDOException $ex) {
            echo 'Error!: ' . $ex->getMessage();
            die;
        }
        $password = password_hash($password, PASSWORD_BCRYPT);
        echo $password;
        $query = $db->query("USE members");
        $query = $db->query("INSERT INTO members (username, password) VALUES ('{$username}', '{$password}')");
        header('Location: main_login.php');
        return TRUE;
    } catch (Exception $ex) {
        return FALSE;
    }
}
 public function testInsertMapped()
 {
     $name = 'My Name';
     $this->mapped->insert(['email' => '*****@*****.**', 'password' => password_hash('password', PASSWORD_DEFAULT), 'user_name' => $name, 'age' => 5]);
     $user = $this->mapped->where('user_name', $name)->first();
     $this->assertSame($name, $user['user_name']);
 }
Example #3
0
 /**
  * Validate that the given username and password are valid
  *
  * @param string  $user     Username
  * @param string  $pass     Password
  * @param boolean $isMd5    Flag to indicate whether incoming password 
  *                          is plaintext or md5
  *
  * @return boolean
  */
 public function validate($user, $userPass, $isMd5 = false, CI_Input $input = null)
 {
     $ret = $this->getUserByUsername($user);
     // make sure we're using an md5 format, passwords are hashed md5s (yes, really)
     $pass = $isMd5 ? $userPass : md5($userPass);
     // did we get a row and do the passwords match?
     if (isset($ret[0])) {
         if (password_verify($pass, $ret[0]->password)) {
             return true;
         } else {
             // may be the password in the database was stored when CI's
             // global_xss_filtering was set to true. We can only test for
             // this if the password passed in was not md5'd.
             if (false === $isMd5) {
                 $pass = $input->xss_clean($userPass);
                 $pass = md5($pass);
                 if (password_verify($pass, $ret[0]->password)) {
                     // it was! Let's store the actually $userPass
                     $password = password_hash(md5($userPass), PASSWORD_DEFAULT);
                     $this->db->where('username', $user);
                     $this->db->update('user', array('password' => $password));
                     return true;
                 }
             }
         }
     }
     return false;
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     DB::table('tbl_users')->truncate();
     $faker = \Faker\Factory::create();
     for ($i = 0; $i < 10; $i++) {
         switch (mt_rand(1, 4)) {
             case 1:
                 $insertion = 'van';
                 break;
             case 2:
                 $insertion = 'de';
                 break;
             case 3:
                 $insertion = 'van der';
                 break;
             default:
                 $insertion = '';
         }
         $city2 = "";
         $street2 = "";
         $house_nr2 = "";
         $postalcode2 = "";
         if (mt_rand(1, 2) == 1) {
             $street2 = $faker->streetName;
             $house_nr2 = $faker->numberBetween(0, 2000);
             $postalcode2 = $faker->postcode;
             $city2 = $faker->city;
         }
         \App\User::create(['username' => $faker->userName, 'password' => password_hash('password', PASSWORD_DEFAULT), 'email' => $faker->email, 'firstname' => $faker->firstName, 'lastname' => $faker->lastName, 'insertion' => $insertion, 'phone_nr' => $faker->phoneNumber, 'birthdate' => $faker->date($format = 'Y-m-d', $max = 'now') . " " . $faker->time($format = 'H:i:s', $max = 'now'), 'city' => $faker->city, 'street' => $faker->streetName, 'house_nr' => $faker->numberBetween(0, 2000), 'postalcode' => $faker->postcode, 'city2' => $city2, 'street2' => $street2, 'house_nr2' => $house_nr2, 'postalcode2' => $postalcode2]);
     }
 }
Example #5
0
 public function edit($newUsername, $newPassword, $id)
 {
     $updateQuery = "UPDATE users SET password = ?, username = ? WHERE id = ?";
     $result = $this->databaseInstance->prepare($updateQuery);
     $result->execute([$newUsername, password_hash($newPassword, PASSWORD_DEFAULT), $id]);
     return $result->rowCount() > 0;
 }
 public function actionCadastro()
 {
     $model = new Usuario();
     ///Aqui não tem como pegar o valor do $model->login
     $login = $model->login;
     $user = Usuario::find('first', ['login' => $login]);
     if (\Kanda::$post->post($model)) {
         //Manter essa daqui! Está criando o mesmo encima
         //Nesse caso está substituindo as variaveis $login,$user
         $login = $model->login;
         $user = Usuario::find('first', ['login' => $login]);
         $model->senha = password_hash($model->senha, PASSWORD_DEFAULT);
         if (!$user) {
             if ($model->save()) {
                 $this->Json(['class' => 'sucess', 'msg' => 'Cadastrado com Sucesso']);
             } else {
                 $this->Json(['class' => 'warning', 'msg' => 'Erro para cadastrar']);
             }
         } else {
             $this->Json(['class' => 'warning', 'msg' => 'Usuario ja cadastrado']);
         }
     } else {
         return $this->render('cadastro', ['model' => $model]);
     }
 }
Example #7
0
 public function resetpassword($id = 0)
 {
     $options = array('cost' => 11);
     $data['password'] = password_hash('123456', PASSWORD_BCRYPT, $options);
     $this->user_model->update($id, $data);
     redirect('admin/doctors');
 }
Example #8
0
 public function create($data)
 {
     $options = array('cost' => 11);
     $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT, $options);
     parent::create($data);
     return $this->db->insert_id();
 }
Example #9
0
function passwordExists($dbConn, $username, $password)
{
    $isValid = false;
    $dbQuery = "SELECT Password FROM USERS WHERE Username = '******' LIMIT 1";
    FB::info('passwordExists() query: ' . $dbQuery);
    $dbRows = mysqli_query($dbConn, $dbQuery);
    $dbValues = mysqli_fetch_assoc($dbRows);
    $dbPassword = $dbValues['Password'];
    if (password_verify($password, $dbPassword)) {
        $isValid = true;
        FB::log('Password is valid!');
        // Check if the password needs a rehash.
        if (password_needs_rehash($dbPassword, PASSWORD_DEFAULT)) {
            FB::log('Rehashing password!');
            $dbPassword = password_hash($password, PASSWORD_DEFAULT);
            $dbQuery = "UPDATE USERS SET Password = '******' WHERE Username = '******'";
            FB::info('Password rehash query: ' . $dbQuery);
            $dbRows = mysqli_query($dbConn, $dbQuery);
            if ($dbRows) {
                FB::log('Password rehash successful!');
            } else {
                FB::error('Password rehash failed: ' . mysqli_error($dbConn));
            }
        }
    }
    return $isValid;
}
    public function insert_user()
    {
        $project_type = $this->input->post('project_type');
        $project_title = $this->input->post('project_title');
        $project_category = $this->input->post('project_category');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $project_ = $this->input->post('project_');
        $keypass = '******' . $password;
        $password_hash = password_hash($keypass, PASSWORD_BCRYPT);
        //--------------------------------------------------------------------------
        $sqlch1 = 'SELECT user_name FROM users WHERE user_name = ? OR email = ?';
        $sqlcheck1 = $this->db->query($sqlch1, array($username, $email));
        if ($this->db->affected_rows() > 0) {
            print_r('Number of affected rows:' . $this->db->affected_rows() . '</br>');
            echo 'Either the Username or email already exists.</br>';
        } else {
            $sql = 'INSERT INTO users ( first_name, last_name, email, user_name, password )	
				  VALUES (' . $this->db->escape($firstname) . ',
						  ' . $this->db->escape($lastname) . ',
						  ' . $this->db->escape($email) . ',
						  ' . $this->db->escape($username) . ',
						  ' . $this->db->escape($password_hash) . ')';
            $result = $this->db->query($sql);
        }
        //----------------------------------------------------------------------------
        return $result;
    }
 public function agregarProductor()
 {
     $cadena = "1234567890abcd";
     for ($i = 0; $i <= 7; $i++) {
         $generador_password = substr($cadena, mt_rand(0, strlen($cadena) - 1), 1);
         $this->user_password .= $generador_password;
     }
     $this->user_password_hash = password_hash($this->user_password, PASSWORD_DEFAULT);
     $this->user_name = $this->nombre . $this->apellidop;
     $sql = "INSERT INTO usuarios(id_usuario, nombre, apellidop, apellidom) \r\n\t\t\t\tVALUES (null, '{$this->nombre}', '{$this->apellidop}', '{$this->apellidom}')";
     $insertUsuario = $this->db->consultaRetorno($sql);
     $sql = "SELECT id_usuario FROM usuarios";
     $selectUsuario = $this->db->consultaRetorno($sql);
     for ($i = 0; $row = $this->db->recorrer_assoc($selectUsuario); $i++) {
         $id_usuario = $row['id_usuario'];
     }
     $this->id_usuario = $id_usuario;
     $this->user_captcha = password_hash($_POST['user_captcha'], PASSWORD_DEFAULT);
     $sql = "INSERT INTO users(id_user, user_name, user_password_hash, user_email, user_captcha, idperfil, idusuario, user_registration_datetime)\r\n\t\t\tVALUES (null,'{$this->user_name}', '{$this->user_password_hash}', '{$this->user_email}', '{$this->user_captcha}', '{$this->tipo}', '{$this->id_usuario}', NOW())";
     $insertUser = $this->db->consultaRetorno($sql);
     if ($insertUsuario == true && $insertUser == true) {
         $this->link($this->user_name, $this->user_email, $this->user_password_hash, $this->user_captcha, $this->id_usuario);
     } else {
         $this->error[] = "<span class='label label-danger posicion'>Error Desconocido Intente De Nuevo.</span>";
         $sql = "DELETE FROM users WHERE idusuario = '{$this->id_usuario}'";
         $a = $this->db->consultaRetorno($sql);
         $sql = "DELETE FROM usuarios WHERE id_usuario = '{$this->id_usuario}'";
         $b = $this->db->consultaRetorno($sql);
     }
 }
Example #12
0
 public function registrationUser()
 {
     $this->load->library(["form_validation"]);
     $this->load->helper("email");
     $this->form_validation->set_rules("tabUsername", "Username", "trim|required|min_length[5]|max_length[40] ");
     $this->form_validation->set_rules("tabPassword", "Password", "required|min_length[2]|max_length[60] ");
     $this->form_validation->set_rules("tabEmail", "Email", "trim|required|valid_email|max_length[254]");
     $message = [];
     if ($this->form_validation->run()) {
         $this->load->model("Users");
         $user_signin_data = ["login" => $this->input->post("tabUsername", true), "password" => password_hash($this->input->post("tabPassword"), PASSWORD_BCRYPT), "email" => $this->input->post("tabEmail")];
         $message = ["text" => "User " . $user_signin_data["login"]];
         if (empty($this->Users->getUserByLogin($user_signin_data["login"]))) {
             $this->Users->add($user_signin_data);
             $template = "loginForm";
             $message["text"] .= " succesfully registered";
         } else {
             $template = "signupForm";
             $message["text"] .= " already exist";
         }
     } else {
         $this->form_validation->set_error_delimiters("<div class='text-danger'>", "</div>");
         $template = "signupForm";
     }
     $this->loadTemplateView($template, $message);
 }
Example #13
0
 public function create()
 {
     $firstname = $_POST['firstname'];
     $lastname = $_POST['lastname'];
     $email = $_POST['email'];
     $username = $_POST['username'];
     $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
     $conn = Db::getConnection();
     $sql = "SELECT *\n\t\t\t\tFROM users";
     $q = $conn->prepare($sql);
     $q->execute();
     $users = $q->fetchAll(\PDO::FETCH_ASSOC);
     $validator = new Validator();
     $error = $validator->validateRegisterForm($_POST, $users);
     //echo '<pre>'; var_dump($error); echo '</pre>';die();
     if ($error) {
         //echo '<pre>'; var_dump($error);die(); echo '</pre>';
         $html = new Html($this->controllerName);
         $html->error = $error;
         //echo '<pre>'; var_dump($html->error);die(); echo '</pre>';
         //;kweojn'dlfv'dlfkv
         $html->render('index');
     } else {
         $newUserSql = "INSERT INTO users\n\t\t\t(`firstname`, `lastname`, `email`, `username`, `password`, `admin`)\n\t\t\tVALUES\n\t\t\t('{$firstname}', '{$lastname}', '{$email}', '{$username}', '{$password}', '0')";
         $q = $conn->prepare($newUserSql);
         $q->execute();
         header('Location: /login/index');
     }
 }
Example #14
0
 /**
  * Provides functionality for a user to edit their profile
  */
 public function actionEdit()
 {
     $model = Users::model()->findByPk(Yii::app()->user->id);
     if (Cii::get($_POST, 'Users', NULL) !== NULL) {
         // Load the bcrypt hashing tools if the user is running a version of PHP < 5.5.x
         if (!function_exists('password_hash')) {
             require_once YiiBase::getPathOfAlias('ext.bcrypt.bcrypt') . '.php';
         }
         $cost = Cii::getBcryptCost();
         if ($_POST['Users']['password'] != '') {
             $_POST['Users']['password'] = password_hash(Users::model()->encryptHash($_POST['Users']['email'], $_POST['Users']['password'], Yii::app()->params['encryptionKey']), PASSWORD_BCRYPT, array('cost' => $cost));
         } else {
             unset($_POST['Users']['password']);
         }
         unset($_POST['Users']['status']);
         unset($_POST['Users']['user_role']);
         $model->attributes = Cii::get($_POST, 'Users', array());
         $model->about = Cii::get(Cii::get($_POST, 'Users', array()), 'about', NULL);
         if ($model->save()) {
             Yii::app()->user->setFlash('success', Yii::t('ciims.controllers.Profile', 'Your profile has been updated!'));
             $this->redirect($this->createUrl('/profile/' . $model->id));
         } else {
             Yii::app()->user->setFlash('warning', Yii::t('ciims.controllers.Profile', 'There were errors saving your profile. Please correct them before trying to save again.'));
         }
     }
     $this->render('edit', array('model' => $model));
 }
 public function register(RegisterBindingModel $model)
 {
     if (!$model) {
         $this->response['error'] = 'Invalid model!';
         return $this->response;
     }
     $usernameCheck = $this->dbContext->getUsersRepository()->filterByUsername(" = '" . $model->getUsername() . "'")->findOne();
     if ($usernameCheck->getId()) {
         $this->response['error'] = 'Username already taken!';
         return $this->response;
     }
     $emailCheck = $this->dbContext->getUsersRepository()->filterByEmail(" = '" . $model->getEmail() . "'")->findOne();
     if ($emailCheck->getId()) {
         $this->response['error'] = 'Email already in use!';
         return $this->response;
     }
     $user = new User($model->getUsername(), password_hash($model->getPassword(), PASSWORD_BCRYPT), $model->getEmail(), $model->getTelephone());
     $this->dbContext->getUsersRepository()->add($user);
     $this->dbContext->saveChanges();
     $user = $this->dbContext->getUsersRepository()->filterByUsername(" = '" . $model->getUsername() . "'")->findOne();
     $userId = intval($user->getId());
     $userRole = new Usersrole($userId, 2, 0);
     $this->dbContext->getUsersrolesRepository()->add($userRole);
     $this->dbContext->saveChanges();
     $this->response['success'] = 'Register successful!';
     return $this->response;
 }
 public function createImageKey($user, $dblink)
 {
     if ($stm = $dblink->prepare("SELECT 2fa_imgname FROM  " . TABLE_USERS . " WHERE email = ?")) {
         $stm->execute(array($user));
         $row = $stm->fetch();
         $stm = NULL;
         $file = 'uploads/2fa/' . $row['2fa_imgname'];
     }
     $im = new Image();
     $imageclean = $im->loadLocalFile($file);
     $imagekey = $im->embedStegoKey($imageclean);
     $stegoKey = $im->stegoKey;
     $hash = password_hash($stegoKey, PASSWORD_DEFAULT);
     if ($stm = $dblink->prepare("UPDATE " . TABLE_USERS . " SET 2fa_hash = ? WHERE email = ?")) {
         $stm->execute(array($hash, $user));
         $stm = NULL;
     }
     if (ob_get_level()) {
         ob_end_clean();
     }
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=KeyImage.png');
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     //header('Content-Length: ' . filesize($file));
     $ok = imagepng($imagekey);
     //, NULL, 9
     imagedestroy($imagekey);
     return $ok;
 }
 public function inscription_1()
 {
     if (isset($_SESSION['user'])) {
         $this->redirectToRoute('accueil');
         // si ok envoie page 2
     }
     if (isset($_POST['suivant'])) {
         $mail = $_POST['wuser']['mail'];
         $user_manager = new userManager();
         $verif = $user_manager->emailExists($mail);
         if ($verif) {
             debug("Cet email est déjà utilisé !");
             $this->show('inscription/inscription1');
             // redirection si erreur
         } else {
             //envoi image + changement nom_image
             $uploads_dir = "C:/xampp/htdocs/projet_lotl/public/assets/img/uploads/";
             //debug($_FILES);die();
             $tmp_name = $_FILES['avatar']['tmp_name'];
             $name = time() . "_" . $_FILES['avatar']['name'];
             $result = move_uploaded_file($tmp_name, "{$uploads_dir}{$name}");
             $_POST['wuserInsc']['avatar'] = $name;
             $_SESSION['wuserInsc'] = $_POST['wuser'];
             //hashage du mdp
             $_SESSION['wuserInsc']['mot_de_passe'] = password_hash($_SESSION['wuserInsc']['mot_de_passe'], PASSWORD_DEFAULT);
             //debug($_SESSION['wuser']);die();
             $this->redirectToRoute('inscription2');
             // si ok envoie page 2
         }
     }
     $this->show('inscription/inscription1');
     // redirection si erreur
 }
Example #18
0
 public function postShowRegisterPage()
 {
     $errors = [];
     $validation_data = ['first_name' => 'min:3', 'last_name' => 'min:3', 'email' => 'email', 'verify_email' => 'email', 'password' => 'min:3', 'email' => 'equalTo:verify_email', 'password' => 'equalTo:verify_password'];
     // validate data
     $validator = new Validator();
     $errors = $validator->isValid($validation_data);
     //  print_r($errors);
     //  exit();
     // if validation fails, go back to register
     // page and display error message
     if (sizeof($errors) > 0) {
         $_SESSION['msg'] = $errors;
         header("Location: /register");
         exit;
     }
     // save this data into a database
     $user = new User();
     $user->first_name = $_REQUEST['first_name'];
     $user->last_name = $_REQUEST['last_name'];
     $user->email = $_REQUEST['email'];
     $user->password = password_hash($_REQUEST['password'], PASSWORD_DEFAULT);
     $user->save();
     echo "Posted!";
 }
 /**
  * handles the entire registration process. checks all error possibilities
  * and creates a new user in the database if everything is fine
  */
 private function registerNewUser()
 {
     if (empty($_POST['user_name'])) {
         $this->errors[] = "Empty Username";
     } elseif (empty($_POST['user_password_new']) || empty($_POST['user_password_repeat'])) {
         $this->errors[] = "Empty Password";
     } elseif ($_POST['user_password_new'] !== $_POST['user_password_repeat']) {
         $this->errors[] = "Password and password repeat are not the same";
     } elseif (strlen($_POST['user_password_new']) < 6) {
         $this->errors[] = "Password has a minimum length of 6 characters";
     } elseif (strlen($_POST['user_name']) > 64 || strlen($_POST['user_name']) < 2) {
         $this->errors[] = "Username cannot be shorter than 2 or longer than 64 characters";
     } elseif (!preg_match('/^[a-z\\d]{2,64}$/i', $_POST['user_name'])) {
         $this->errors[] = "Username does not fit the name scheme: only a-Z and numbers are allowed, 2 to 64 characters";
     } elseif (empty($_POST['user_email'])) {
         $this->errors[] = "Email cannot be empty";
     } elseif (strlen($_POST['user_email']) > 64) {
         $this->errors[] = "Email cannot be longer than 64 characters";
     } elseif (!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
         $this->errors[] = "Your email address is not in a valid email format";
     } elseif (!empty($_POST['user_name']) && strlen($_POST['user_name']) <= 64 && strlen($_POST['user_name']) >= 2 && preg_match('/^[a-z\\d]{2,64}$/i', $_POST['user_name']) && !empty($_POST['user_email']) && strlen($_POST['user_email']) <= 64 && filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) && !empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat']) && $_POST['user_password_new'] === $_POST['user_password_repeat']) {
         // create a database connection
         $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
         // change character set to utf8 and check it
         if (!$this->db_connection->set_charset("utf8")) {
             $this->errors[] = $this->db_connection->error;
         }
         // if no connection errors (= working database connection)
         if (!$this->db_connection->connect_errno) {
             // escaping, additionally removing everything that could be (html/javascript-) code
             $user_name = $this->db_connection->real_escape_string(strip_tags($_POST['user_name'], ENT_QUOTES));
             $user_email = $this->db_connection->real_escape_string(strip_tags($_POST['user_email'], ENT_QUOTES));
             $user_password = $_POST['user_password_new'];
             // crypt the user's password with PHP 5.5's password_hash() function, results in a 60 character
             // hash string. the PASSWORD_DEFAULT constant is defined by the PHP 5.5, or if you are using
             // PHP 5.3/5.4, by the password hashing compatibility library
             $user_password_hash = password_hash($user_password, PASSWORD_DEFAULT);
             // check if user or email address already exists
             $sql = "SELECT * FROM users WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_email . "';";
             $query_check_user_name = $this->db_connection->query($sql);
             if ($query_check_user_name->num_rows == 1) {
                 $this->errors[] = "Sorry, that username / email address is already taken.";
             } else {
                 // write new user's data into database
                 $sql = "INSERT INTO users (user_name, user_password_hash, user_email)\n                            VALUES('" . $user_name . "', '" . $user_password_hash . "', '" . $user_email . "');";
                 $query_new_user_insert = $this->db_connection->query($sql);
                 // if user has been added successfully
                 if ($query_new_user_insert) {
                     $this->messages[] = "Your account has been created successfully. You can now log in.";
                 } else {
                     $this->errors[] = "Sorry, your registration failed. Please go back and try again.";
                 }
             }
         } else {
             $this->errors[] = "Sorry, no database connection.";
         }
     } else {
         $this->errors[] = "An unknown error occurred.";
     }
 }
 public function changePasswordddd()
 {
     $pass = password_hash('Opti369', PASSWORD_DEFAULT);
     $data = array('password' => $pass);
     $this->db->where('id', 13);
     $this->db->update('tbl_sites', $data);
 }
Example #21
0
 public function testPassword()
 {
     $password = '******';
     $hash = password_hash($password, PASSWORD_BCRYPT);
     $this->assertNotEmpty($hash);
     $this->assertTrue(password_verify($password, $hash));
 }
Example #22
0
 public function add()
 {
     $this->userObject = new User();
     $data = array('email' => $_POST['email'], 'password' => password_hash($_POST['password'], PASSWORD_DEFAULT), 'first_name' => $_POST['firstname'], 'last_name' => $_POST['lastname']);
     $result = $this->userObject->add_user($data);
     $this->set('message', $result);
 }
Example #23
0
 /**
  * {@inheritDoc}
  */
 public function hash($value)
 {
     if (!($hash = password_hash($value, PASSWORD_DEFAULT))) {
         throw new RuntimeException('Error hashing value. Check system compatibility with password_hash().');
     }
     return $hash;
 }
 public function testPassword()
 {
     $passwd = password_hash('WowSoSecretPassword', PASSWORD_DEFAULT);
     $this->assertEmpty($this->user->getPassword());
     $this->user->setPassword($passwd);
     $this->assertEquals($passwd, $this->user->getPassword());
 }
Example #25
0
 public static function CreateNewAccount()
 {
     // validate input
     if (!self::validateUserName(Request::post('new_account_name'))) {
         return false;
     }
     if (!self::validateUserPassword(Request::post('new_account_password'), Request::post('new_account_password_repeat'))) {
         return false;
     }
     // connect to database
     $db = Database::getFactory()->getConnection();
     if (!$db) {
         Session::add('feedback_negative', 'Critical error. Can\'t connect to database.');
         return false;
     }
     // get a password hash
     $passwordHash = password_hash(Request::post('new_account_password'), PASSWORD_DEFAULT);
     // write new users data into database
     $sql = "INSERT INTO users ( user_id,  user_name,  user_password,  user_registration_time)\n                       VALUES (:user_id, :user_name, :user_password, :user_registration_time)";
     $query = $db->prepare($sql);
     $query->execute(array(':user_id' => null, ':user_name' => Request::post('new_account_name'), ':user_password' => $passwordHash, ':user_registration_time' => time('c')));
     $count = $query->rowCount();
     if ($count == 1) {
         Session::add('feedback_positive', 'New account created successfully.');
         return true;
     }
     // if it gets to this point, something went wrong
     Session::add('feedback_negative', 'Something went wrong.');
     return false;
 }
Example #26
0
 public function logreg()
 {
     $flag = 1;
     $this->load->library('form_validation');
     // установка правил валидации
     $this->form_validation->set_rules($this->config->item('reg_validation'));
     if ($this->form_validation->run() === TRUE) {
         // получение данных с формы
         $email = $this->input->post('email');
         $pass = $this->input->post('password');
         $name = $this->input->post('name');
         $lastname = $this->input->post('lastname');
         $birthday = $this->input->post('birthday');
         $this->load->model("User_Model");
         $this->load->model('Cart_Model');
         $data['result'] = $this->User_Model->check_user($email, $pass);
         if ($data['result']['status'] == 2 && $flag > 0) {
             $this->User_Model->insert(array('email' => $email, 'password' => password_hash($pass, PASSWORD_DEFAULT), 'name' => $name, 'lastname' => $lastname, 'birthday' => $birthday));
             $data['result'] = array('status' => 0);
         }
     } else {
         $data['result']['status'] = 1;
         $data['result']['message'] = $this->form_validation->error_string();
     }
     $this->output->json_output($data);
 }
function submitForm(){
  $params = json_decode(file_get_contents('php://input'), true );
  //print_r($params['data']['password']);
  $errors = array();
  $return = array();
  if(!isset($params['data']['email']) || $params['data']['email'] == '' ){
    $errors['errors'] = "Please enter an email address.";
    print_r(json_encode($errors));
    exit();
  }
  if(isset($params['data']['password'])){
    $password = $params['data']['password'];
    $return['e_pass'] = password_hash($password, PASSWORD_DEFAULT);
  }else{
    $errors['errors'] = "Please enter a password.";
    print_r(json_encode($errors));
    exit();
  }
  $email = $params['data']['email'];
  if ($email != "") {
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['errors'] = "Email is not a valid email!";
    }
  } 
  if(isset($params['data']['message'])){
    $message = trim($params['data']['message']);
    $return['message'] = filter_var($message, FILTER_SANITIZE_STRING);
  }
  if(isset($errors['errors'])){
    print_r(json_encode($errors));
  }else{
    print_r(json_encode($return));
  }
}
Example #28
0
 public function onsubmit($sender)
 {
     $this->setError('');
     if ($this->_login == '') {
         $this->setError('Введите логин');
     } else {
         if ($this->_password == '') {
             $this->setError('Введите пароль');
         } else {
             if ($this->_confirm == '') {
                 $this->setError('Подтвердите пароль');
             } else {
                 if ($this->_confirm != $this->_password) {
                     $this->setError('Неверное подтверждение');
                 } else {
                     if ($user = Helper::login($this->_login) != false) {
                         $this->setError('Логин уже существует');
                     }
                 }
             }
         }
     }
     if (!$this->isError()) {
         $user = new User();
         $user->userlogin = $this->_login;
         $user->userpass = \password_hash($this->_password, PASSWORD_DEFAULT);
         $user->Save();
         App::Redirect('\\ZippyERP\\System\\Pages\\UserInfo', $user->user_id);
     }
     $this->_confirm = '';
     $this->_password = '';
 }
Example #29
0
 public function register(Request $request, Response $response, array $arguments)
 {
     $errors = [];
     $body = ['email' => null, 'password' => null];
     if (is_array($request->getParsedBody())) {
         $body = array_merge($body, $request->getParsedBody());
     }
     if (!isset($body['email'])) {
         array_push($errors, ['value' => 'email', 'error' => 'EMAIL_MISSING', 'message' => 'Email address is missing']);
     }
     if (!isset($body['password'])) {
         array_push($errors, ['value' => 'password', 'error' => 'PASSWORD_MISSING', 'message' => 'Password is missing']);
     }
     if (!filter_var($body['email'], FILTER_VALIDATE_EMAIL)) {
         array_push($errors, ['value' => 'email', 'error' => 'EMAIL_INVALID', 'message' => 'Email address is invalid']);
     }
     if (!User::where(['email' => $body['email']])->get()->isEmpty()) {
         array_push($errors, ['value' => 'email', 'error' => 'EMAIL_IN_USE', 'message' => 'Email address is in use']);
     }
     if (!$errors) {
         $user = new User();
         $user->email = mb_strtolower($body['email']);
         $user->password = password_hash($body['password'], PASSWORD_DEFAULT);
         $user->save();
         return $response->withJson($user, 201);
     } else {
         return $response->withJson($errors, 400);
     }
 }