Version 1.0.0 - modified by Nordstromrack.com | HauteLook Change Log: - the hash_equals function is now used instead of == or === to prevent timing attacks Written by Solar Designer in 2004-2006 and placed in There's absolutely no warranty. The homepage URL for this framework is: http://www.openwall.com/phpass/ Please be sure to update the Version line if you edit this file in any way. It is suggested that you leave the main version number intact, but indicate your project name (after the slash) and add your own revision information. Please do not change the "private" password hashing method implemented in here, thereby making your hashes incompatible. However, if you must, please change the hash type identifier (the "$P$") to something different. Obviously, since this code is in the public domain, the above are not requirements (there can be none), but merely suggestions.
Author: Solar Designer (solar@openwall.com)
Esempio n. 1
0
 /**
  * Check the given plain value against a hash.
  *
  * @param  string  $value
  * @param  string  $hashedValue
  * @param  array   $options
  * @return bool
  */
 public function check($value, $hashedValue, array $options = [])
 {
     if (strlen($hashedValue) === 0) {
         return false;
     }
     return $this->hasher->CheckPassword($value, $hashedValue);
 }
Esempio n. 2
0
 public function testPortableHashes()
 {
     $hasher = new PasswordHash(8, true);
     $correct = 'test12345';
     $wrong = 'test12346';
     $this->assertTrue($hasher->CheckPassword($correct, self::PORTABLE_HASH));
     $this->assertFalse($hasher->CheckPassword($wrong, self::PORTABLE_HASH));
 }
Esempio n. 3
0
 public function testCheckPassword()
 {
     $hasher = new PasswordHash(8, false);
     $password = $hasher->HashPassword('test');
     $person = new Person(['password' => $password]);
     $this->assertTrue($person->checkPassword('test'));
     $this->assertFalse($person->checkPassword('test2'));
 }
Esempio n. 4
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     $passwordHasher = new PasswordHash(8, false);
     if (Schema::hasTable('user')) {
         DB::table('user')->delete();
     }
     DB::table('user')->insert(array('username' => 'test', 'password' => $passwordHasher->HashPassword('test'), 'rights' => 0));
     DB::table('user')->insert(array('username' => 'admin', 'password' => $passwordHasher->HashPassword('admin'), 'rights' => 100));
     DB::table('user')->insert(array('username' => 'test2', 'password' => $passwordHasher->HashPassword('test2'), 'rights' => 0));
 }
 /**
  * Checks the plaintext password against the encrypted Password.
  *
  * Maintains compatibility between old version and the new cookie authentication
  * protocol using PHPass library. The $hash parameter is the encrypted password
  * and the function compares the plain text password when encrypted similarly
  * against the already encrypted password to see if they match.
  *
  * @uses PasswordHash::CheckPassword
  *
  * @param string $password Plaintext user's password
  * @param string $hash     Hash of the user's password to check against.
  *
  * @return bool False, if the $password does not match the hashed password
  */
 public function check($password, $hash)
 {
     // If the hash is still md5...
     if (strlen($hash) <= 32) {
         return $hash == md5($password);
     }
     // If the stored hash is longer than an MD5, presume the
     // new style phpass portable hash.
     return $this->wp_hasher->CheckPassword($password, $hash);
 }
Esempio n. 6
0
 /**
  * Hash user passwords on save.
  *
  * Hashstrength has a default of '10', don't allow less than '8'.
  *
  * @param Entity\Users $usersEntity
  */
 protected function passwordHash(Entity\Users $usersEntity)
 {
     if ($usersEntity->getShadowSave()) {
         return;
     } elseif ($usersEntity->getPassword() && $usersEntity->getPassword() !== '**dontchange**') {
         $hasher = new PasswordHash($this->hashStrength, true);
         $usersEntity->setPassword($hasher->HashPassword($usersEntity->getPassword()));
     } else {
         unset($usersEntity->password);
     }
 }
Esempio n. 7
0
 /**
  * Check a user login request for username/password combinations.
  *
  * @param string  $userName
  * @param string  $password
  *
  * @return boolean
  */
 protected function loginCheckPassword($userName, $password)
 {
     if (!($userEntity = $this->getUserEntity($userName))) {
         return false;
     }
     $hasher = new PasswordHash($this->app['access_control.hash.strength'], true);
     if (!$hasher->CheckPassword($password, $userEntity->getPassword())) {
         $this->loginFailed($userEntity);
         return false;
     }
     return $this->loginFinish($userEntity);
 }
 /**
  * @param array $data
  * @return UserInfo|false|null
  */
 public function create($data)
 {
     $uae = new AddUser($data);
     $uae = \Events::dispatch('on_before_user_add', $uae);
     if (!$uae->proceed()) {
         return false;
     }
     $db = $this->connection;
     $dh = $this->application->make('date');
     $uDateAdded = $dh->getOverridableNow();
     $config = $this->application->make('config');
     $hasher = new PasswordHash($config->get('concrete.user.password.hash_cost_log2'), $config->get('concrete.user.password.hash_portable'));
     if (isset($data['uIsValidated']) && $data['uIsValidated'] == 1) {
         $uIsValidated = 1;
     } elseif (isset($data['uIsValidated']) && $data['uIsValidated'] == 0) {
         $uIsValidated = 0;
     } else {
         $uIsValidated = -1;
     }
     if (isset($data['uIsFullRecord']) && $data['uIsFullRecord'] == 0) {
         $uIsFullRecord = 0;
     } else {
         $uIsFullRecord = 1;
     }
     $password_to_insert = isset($data['uPassword']) ? $data['uPassword'] : null;
     $hash = $hasher->HashPassword($password_to_insert);
     $uDefaultLanguage = null;
     if (isset($data['uDefaultLanguage']) && $data['uDefaultLanguage'] != '') {
         $uDefaultLanguage = $data['uDefaultLanguage'];
     }
     $v = array($data['uName'], $data['uEmail'], $hash, $uIsValidated, $uDateAdded, $uDateAdded, $uIsFullRecord, $uDefaultLanguage, 1);
     $r = $db->prepare("insert into Users (uName, uEmail, uPassword, uIsValidated, uDateAdded, uLastPasswordChange, uIsFullRecord, uDefaultLanguage, uIsActive) values (?, ?, ?, ?, ?, ?, ?, ?, ?)");
     $res = $r->execute($v);
     if ($res) {
         $newUID = $db->Insert_ID();
         $ui = $this->userInfoFactory->getByID($newUID);
         if (is_object($ui)) {
             $uo = $ui->getUserObject();
             $groupControllers = \Group::getAutomatedOnRegisterGroupControllers($uo);
             foreach ($groupControllers as $ga) {
                 if ($ga->check($uo)) {
                     $uo->enterGroup($ga->getGroupObject());
                 }
             }
             // run any internal event we have for user add
             $ue = new UserInfoWithPassword($ui);
             $ue->setUserPassword($password_to_insert);
             \Events::dispatch('on_user_add', $ue);
         }
         return $ui;
     }
 }
 /**
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $resourceOwnerId = $input->getOption('login');
     $password = $input->getOption('password');
     $hasher = new PasswordHash(12, true);
     $passwordHash = $hasher->HashPassword($password);
     if ($this->app['clientlogin.records']->setAccountPassword($resourceOwnerId, $passwordHash)) {
         $this->auditLog(__CLASS__, 'ClientLogin admin command set password for account: ' . $resourceOwnerId);
         $output->writeln("\n<info>Set password for account: {$resourceOwnerId}</info>");
     } else {
         $output->writeln("\n<error>Unable to set password for account: {$resourceOwnerId}</error>");
     }
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     if (Schema::hasTable('cluster')) {
         DB::table('cluster')->delete();
     }
     $passwordHasher = new PasswordHash(8, false);
     if (Schema::hasTable('cluster')) {
         DB::table('cluster')->delete();
     }
     $test_user = DB::table('user')->where('username', '=', 'test')->first();
     DB::table('cluster')->insert(array('clustername' => 'test', 'password' => $passwordHasher->HashPassword('test'), 'user_id' => $test_user->id));
     $admin_user = DB::table('user')->where('username', '=', 'admin')->first();
     DB::table('cluster')->insert(array('clustername' => 'admin', 'password' => $passwordHasher->HashPassword('admin'), 'user_id' => $admin_user->id));
 }
 /**
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $resourceOwnerId = $input->getOption('login');
     $password = $input->getOption('password');
     $emailAddress = $input->getOption('email');
     $hasher = new PasswordHash(12, true);
     $passwordHash = $hasher->HashPassword($password);
     try {
         $this->app['clientlogin.records']->insertAccount(null, $resourceOwnerId, $passwordHash, $emailAddress);
         $this->auditLog(__CLASS__, 'ClientLogin admin command created account: ' . $resourceOwnerId);
         $output->writeln("\n<info>Created account: {$resourceOwnerId}</info>");
     } catch (UniqueConstraintViolationException $e) {
         $output->writeln("\n<error>Account already exists!</error>");
     }
 }
 /**
  * @param Post    $post
  * @param Request $request
  * @param string  $cookieHash
  *
  * @return bool
  */
 public function isPasswordRequired(Post $post, Request $request, $cookieHash)
 {
     if (!$post->getPassword()) {
         return false;
     }
     $cookies = $request->cookies;
     if (!$cookies->has('wp-postpass_' . $cookieHash)) {
         return true;
     }
     $hash = stripslashes($cookies->get('wp-postpass_' . $cookieHash));
     if (0 !== strpos($hash, '$P$B')) {
         return true;
     }
     $wpHasher = new PasswordHash(8, true);
     return !$wpHasher->CheckPassword($post->getPassword(), $hash);
 }
Esempio n. 13
0
 public function testSetRandomPassword()
 {
     $app = $this->getApp();
     $this->addDefaultUser($app);
     $entityName = 'Bolt\\Storage\\Entity\\Users';
     $repo = $app['storage']->getRepository($entityName);
     $logger = $this->getMock('\\Monolog\\Logger', ['info'], ['testlogger']);
     $logger->expects($this->atLeastOnce())->method('info')->with($this->equalTo("Password for user 'admin' was reset via Nut."));
     $app['logger.system'] = $logger;
     $password = new Password($app);
     $newPass = $password->setRandomPassword('admin');
     $userEntity = $repo->getUser('admin');
     $hasher = new PasswordHash($app['access_control.hash.strength'], true);
     $compare = $hasher->CheckPassword($newPass, $userEntity->getPassword());
     $this->assertTrue($compare);
     $this->assertEmpty($userEntity->getShadowpassword());
     $this->assertEmpty($userEntity->getShadowtoken());
     $this->assertNull($userEntity->getShadowvalidity());
 }
Esempio n. 14
0
 /**
  * Execute the console command
  *
  * @return void
  */
 public function fire()
 {
     $hasher = new PasswordHash(8, false);
     $password = $hasher->HashPassword($this->argument('password'));
     $rights = $this->option('admin') != null ? 100 : 0;
     // check if the provided user exists
     $user = User::where('username', '=', $this->argument('username'))->first();
     if (isset($user)) {
         // user exists, let's update it
         $user->password = $password;
         $user->rights = $rights;
         $user->save();
         $this->info("User '{$user->username}' has been updated.");
     } else {
         // user do not exists, let's create it
         $user = new User();
         $user->username = $this->argument('username');
         $user->password = $password;
         $user->rights = $rights;
         $user->save();
         $this->info("User '{$user->username}' has been updated.");
     }
 }
Esempio n. 15
0
 /**
  * @return \Concrete\Core\Error\Error
  */
 public function configure()
 {
     $error = $this->app->make('helper/validation/error');
     /* @var $error \Concrete\Core\Error\ErrorList\ErrorList */
     try {
         $val = $this->app->make('helper/validation/form');
         /* @var \Concrete\Core\Form\Service\Validation $val */
         $val->setData($this->post());
         $val->addRequired("SITE", t("Please specify your site's name"));
         $val->addRequiredEmail("uEmail", t('Please specify a valid email address'));
         $val->addRequired("DB_DATABASE", t('You must specify a valid database name'));
         $val->addRequired("DB_SERVER", t('You must specify a valid database server'));
         $password = $_POST['uPassword'];
         $passwordConfirm = $_POST['uPasswordConfirm'];
         $this->app->make('validator/password')->isValid($password, $error);
         if ($password) {
             if ($password != $passwordConfirm) {
                 $error->add(t('The two passwords provided do not match.'));
             }
         }
         if (is_object($this->fileWriteErrors)) {
             foreach ($this->fileWriteErrors->getList() as $msg) {
                 $error->add($msg);
             }
         }
         $error = $this->validateDatabase($error);
         $error = $this->validateSampleContent($error);
         if ($this->post('canonicalUrlChecked') === '1') {
             try {
                 $url = UrlImmutable::createFromUrl($this->post('canonicalUrl'));
                 if (strcasecmp('http', $url->getScheme()) !== 0) {
                     throw new Exception('The HTTP canonical URL must have the http:// scheme');
                 }
                 $canonicalUrl = (string) $url;
             } catch (Exception $x) {
                 $error->add($x);
             }
         } else {
             $canonicalUrl = '';
         }
         if ($this->post('canonicalSSLUrlChecked') === '1') {
             $url = UrlImmutable::createFromUrl($this->post('canonicalSSLUrl'));
             if (strcasecmp('https', $url->getScheme()) !== 0) {
                 throw new Exception('The SSL canonical URL must have the https:// scheme');
             }
             $canonicalSSLUrl = (string) $url;
         } else {
             $canonicalSSLUrl = '';
         }
         if ($val->test() && !$error->has()) {
             // write the config file
             $vh = $this->app->make('helper/validation/identifier');
             $this->fp = @fopen(DIR_CONFIG_SITE . '/site_install.php', 'w+');
             $this->fpu = @fopen(DIR_CONFIG_SITE . '/site_install_user.php', 'w+');
             if ($this->fp) {
                 $config = isset($_POST['SITE_CONFIG']) ? (array) $_POST['SITE_CONFIG'] : [];
                 $config['database'] = ['default-connection' => 'concrete', 'connections' => ['concrete' => ['driver' => 'c5_pdo_mysql', 'server' => $_POST['DB_SERVER'], 'database' => $_POST['DB_DATABASE'], 'username' => $_POST['DB_USERNAME'], 'password' => $_POST['DB_PASSWORD'], 'charset' => 'utf8']]];
                 $config['canonical-url'] = $canonicalUrl;
                 $config['canonical-ssl-url'] = $canonicalSSLUrl;
                 $config['session-handler'] = $_POST['sessionHandler'];
                 $renderer = new Renderer($config);
                 fwrite($this->fp, $renderer->render());
                 fclose($this->fp);
                 chmod(DIR_CONFIG_SITE . '/site_install.php', 0700);
             } else {
                 throw new Exception(t('Unable to open config/app.php for writing.'));
             }
             if ($this->fpu) {
                 $config = $this->app->make('config');
                 $hasher = new PasswordHash($config->get('concrete.user.password.hash_cost_log2'), $config->get('concrete.user.password.hash_portable'));
                 $configuration = "<?php\n";
                 $configuration .= "define('INSTALL_USER_EMAIL', " . var_export((string) $_POST['uEmail'], true) . ");\n";
                 $configuration .= "define('INSTALL_USER_PASSWORD_HASH', " . var_export((string) $hasher->HashPassword($_POST['uPassword']), true) . ");\n";
                 $configuration .= "define('INSTALL_STARTING_POINT', " . var_export((string) $this->post('SAMPLE_CONTENT'), true) . ");\n";
                 $configuration .= "define('SITE', " . var_export((string) $_POST['SITE'], true) . ");\n";
                 $locale = $this->post('siteLocaleLanguage') . '_' . $this->post('siteLocaleCountry');
                 $configuration .= "define('SITE_INSTALL_LOCALE', " . var_export($locale, true) . ");\n";
                 $configuration .= "define('APP_INSTALL_LANGUAGE', " . var_export($this->post('locale'), true) . ");\n";
                 $res = fwrite($this->fpu, $configuration);
                 fclose($this->fpu);
                 chmod(DIR_CONFIG_SITE . '/site_install_user.php', 0700);
                 if (PHP_SAPI != 'cli') {
                     $this->redirect('/');
                 }
             } else {
                 throw new Exception(t('Unable to open config/site_user.php for writing.'));
             }
         } else {
             if ($error->has()) {
                 $this->set('error', $error);
             } else {
                 $error = $val->getError();
                 $this->set('error', $val->getError());
             }
         }
     } catch (Exception $ex) {
         $this->reset();
         $this->set('error', $ex);
         $error->add($ex);
     }
     $this->setup();
     return $error;
 }
Esempio n. 16
0
 public function hash($password)
 {
     $hasher = new PasswordHash(8, false);
     return $hasher->HashPassword($password);
 }
Esempio n. 17
0
 /**
  * Checks that a submitted password matches the users password
  *
  * @param \CMF\Auth\User $user
  * @param string         $submitted_password
  *
  * @return bool
  */
 public static function has_password(User $user, $submitted_password)
 {
     $user_password = @stream_get_contents($user->get('encrypted_password'));
     if (empty($user_password) || $user_password === false || empty($submitted_password)) {
         return false;
     }
     $hasher = new PasswordHash(8, false);
     return $hasher->CheckPassword($submitted_password, $user_password);
 }
Esempio n. 18
0
 /**
  * Sends email with password request. Accepts email or username
  *
  * @param string $username
  *
  * @return boolean
  */
 public function resetPasswordRequest($username)
 {
     $user = $this->getUser($username);
     $recipients = false;
     if (!empty($user)) {
         $shadowpassword = $this->app['randomgenerator']->generateString(12);
         $shadowtoken = $this->app['randomgenerator']->generateString(32);
         $hasher = new PasswordHash($this->hashStrength, true);
         $shadowhashed = $hasher->HashPassword($shadowpassword);
         $shadowlink = sprintf('%s%sresetpassword?token=%s', $this->app['paths']['hosturl'], $this->app['paths']['bolt'], urlencode($shadowtoken));
         // Set the shadow password and related stuff in the database.
         $update = array('shadowpassword' => $shadowhashed, 'shadowtoken' => $shadowtoken . '-' . str_replace('.', '-', $this->remoteIP), 'shadowvalidity' => date('Y-m-d H:i:s', strtotime('+2 hours')));
         $this->db->update($this->usertable, $update, array('id' => $user['id']));
         // Compile the email with the shadow password and reset link.
         $mailhtml = $this->app['render']->render('mail/passwordreset.twig', array('user' => $user, 'shadowpassword' => $shadowpassword, 'shadowtoken' => $shadowtoken, 'shadowvalidity' => date('Y-m-d H:i:s', strtotime('+2 hours')), 'shadowlink' => $shadowlink));
         $subject = sprintf('[ Bolt / %s ] Password reset.', $this->app['config']->get('general/sitename'));
         $message = $this->app['mailer']->createMessage('message')->setSubject($subject)->setFrom(array($this->app['config']->get('general/mailoptions/senderMail', $user['email']) => $this->app['config']->get('general/mailoptions/senderName', $this->app['config']->get('general/sitename'))))->setTo(array($user['email'] => $user['displayname']))->setBody(strip_tags($mailhtml))->addPart($mailhtml, 'text/html');
         $recipients = $this->app['mailer']->send($message);
         if ($recipients) {
             $this->app['logger.system']->info("Password request sent to '" . $user['displayname'] . "'.", array('event' => 'authentication'));
         } else {
             $this->app['logger.system']->error("Failed to send password request sent to '" . $user['displayname'] . "'.", array('event' => 'authentication'));
             $this->session->getFlashBag()->add('error', Trans::__("Failed to send password request. Please check the email settings."));
         }
     }
     // For safety, this is the message we display, regardless of whether $user exists.
     if ($recipients === false || $recipients > 0) {
         $this->session->getFlashBag()->add('info', Trans::__("A password reset link has been sent to '%user%'.", array('%user%' => $username)));
     }
     return true;
 }
Esempio n. 19
0
 /**
  * Generate a cryptographically secure random string
  * @param int $length
  * @return string
  */
 public function getString($length = 12)
 {
     if (function_exists('random_bytes')) {
         $bytes = random_bytes($length / 2);
     } else {
         $hash = new PasswordHash(8, false);
         $bytes = $hash->get_random_bytes($length / 2);
     }
     return bin2hex($bytes);
 }
Esempio n. 20
0
 /**
  * Sends email with password request. Accepts email or username.
  *
  * @param string $username
  * @param string $remoteIP
  *
  * @return boolean
  */
 public function resetPasswordRequest($username, $remoteIP)
 {
     $userEntity = $this->app['storage']->getRepository('Bolt\\Storage\\Entity\\Users')->getUser($username);
     if (!$userEntity) {
         // For safety, this is the message we display, regardless of whether user exists.
         $this->app['logger.flash']->info(Trans::__("A password reset link has been sent to '%user%'.", ['%user%' => $username]));
         return false;
     }
     $validity = new \DateTime();
     $delay = new \DateInterval('PT2H');
     // Generate shadow password and hash
     $hasher = new PasswordHash($this->app['access_control.hash.strength'], true);
     $shadowPassword = $this->app['randomgenerator']->generateString(12);
     $shadowPasswordHash = $hasher->HashPassword($shadowPassword);
     // Generate shadow token and hash
     $shadowToken = $this->app['randomgenerator']->generateString(32);
     $shadowTokenHash = md5($shadowToken . '-' . str_replace('.', '-', $remoteIP));
     // Set the shadow password and related stuff in the database.
     $userEntity->setShadowpassword($shadowPasswordHash);
     $userEntity->setShadowtoken($shadowTokenHash);
     $userEntity->setShadowvalidity($validity->add($delay));
     $this->app['storage']->getRepository('Bolt\\Storage\\Entity\\Users')->save($userEntity);
     $mailoptions = $this->app['config']->get('general/mailoptions');
     // PHP 5.4 compatibility
     if (empty($mailoptions)) {
         $this->app['logger.flash']->error(Trans::__("The email configuration setting 'mailoptions' hasn't been set. Bolt may be unable to send password reset."));
     }
     // Sent the password reset notification
     $this->resetPasswordNotification($userEntity, $shadowPassword, $shadowToken);
     return true;
 }
Esempio n. 21
0
 function it_returns_false_if_the_hashed_password_is_empty(PasswordHash $hasher)
 {
     $hasher->CheckPassword()->shouldNotBeCalled();
     $this->check('password', '')->shouldReturn(false);
 }
 /**
  * Validate a user against the given credentials.
  *
  * @param \Illuminate\Auth\UserInterface $user
  * @param array $credentials
  * @return bool
  */
 public function validateCredentials(UserInterface $user, array $credentials)
 {
     $plain = $credentials['password'];
     return $this->hasher->CheckPassword($plain, $user->getAuthPassword());
 }
Esempio n. 23
0
 /**
  * @param array $data
  * @param array | false $options
  * @return UserInfo
  */
 public static function add($data, $options = false)
 {
     $options = is_array($options) ? $options : array();
     $db = Loader::db();
     $dh = Loader::helper('date');
     $uDateAdded = $dh->getOverridableNow();
     $hasher = new PasswordHash(\Config::get('concrete.user.password.hash_cost_log2'), \Config::get('concrete.user.password.hash_portable'));
     if ($data['uIsValidated'] == 1) {
         $uIsValidated = 1;
     } elseif (isset($data['uIsValidated']) && $data['uIsValidated'] == 0) {
         $uIsValidated = 0;
     } else {
         $uIsValidated = -1;
     }
     if (isset($data['uIsFullRecord']) && $data['uIsFullRecord'] == 0) {
         $uIsFullRecord = 0;
     } else {
         $uIsFullRecord = 1;
     }
     $password_to_insert = $data['uPassword'];
     $hash = $hasher->HashPassword($password_to_insert);
     if (isset($data['uDefaultLanguage']) && $data['uDefaultLanguage'] != '') {
         $uDefaultLanguage = $data['uDefaultLanguage'];
     }
     $v = array($data['uName'], $data['uEmail'], $hash, $uIsValidated, $uDateAdded, $uDateAdded, $uIsFullRecord, $uDefaultLanguage, 1);
     $r = $db->prepare("insert into Users (uName, uEmail, uPassword, uIsValidated, uDateAdded, uLastPasswordChange, uIsFullRecord, uDefaultLanguage, uIsActive) values (?, ?, ?, ?, ?, ?, ?, ?, ?)");
     $res = $db->execute($r, $v);
     if ($res) {
         $newUID = $db->Insert_ID();
         $ui = UserInfo::getByID($newUID);
         if (is_object($ui)) {
             // run any internal event we have for user add
             $ue = new \Concrete\Core\User\Event\UserInfoWithPassword($ui);
             $ue->setUserPassword($data['uPassword']);
             Events::dispatch('on_user_add', $ue);
         }
         $uo = $ui->getUserObject();
         $groupControllers = \Group::getAutomatedOnRegisterGroupControllers($uo);
         foreach ($groupControllers as $ga) {
             if ($ga->check($uo)) {
                 $uo->enterGroup($ga->getGroupObject());
             }
         }
         return $ui;
     }
 }
Esempio n. 24
0
 public function generatepasswords()
 {
     if (!$this->app['users']->isAllowed('dashboard')) {
         die('You do not have the right privileges to view this page.');
     }
     // Set up the form.
     $form = $this->app['form.factory']->createBuilder('form');
     $form->add('password', 'text');
     $form = $form->getForm();
     $password = false;
     if ($this->app['request']->getMethod() == 'POST') {
         $form->bind($this->app['request']);
         $data = $form->getData();
         if ($form->isValid()) {
             $hasher = new PasswordHash(12, true);
             $password = $hasher->HashPassword($data['password']);
         }
     }
     // Render the form, and show it it the visitor.
     $this->app['twig.loader.filesystem']->addPath(__DIR__);
     $html = $this->app['twig']->render('assets/passwordgenerate.twig', array('form' => $form->createView(), 'password' => $password));
     return new \Twig_Markup($html, 'UTF-8');
 }
Esempio n. 25
0
 /**
  * @param string $password
  *
  * @return bool
  */
 public function checkPassword($password)
 {
     $hasher = new PasswordHash(8, false);
     return $hasher->checkPassword($password, $this->getPassword());
 }
Esempio n. 26
0
 /**
  * @return \Concrete\Core\Error\Error
  */
 public function configure()
 {
     $error = \Core::make('helper/validation/error');
     /* @var $error \Concrete\Core\Error\Error */
     try {
         $val = Core::make('helper/validation/form');
         $val->setData($this->post());
         $val->addRequired("SITE", t("Please specify your site's name"));
         $val->addRequiredEmail("uEmail", t('Please specify a valid email address'));
         $val->addRequired("DB_DATABASE", t('You must specify a valid database name'));
         $val->addRequired("DB_SERVER", t('You must specify a valid database server'));
         $password = $_POST['uPassword'];
         $passwordConfirm = $_POST['uPasswordConfirm'];
         $uh = Core::make('helper/concrete/user');
         $uh->validNewPassword($password, $error);
         if ($password) {
             if ($password != $passwordConfirm) {
                 $error->add(t('The two passwords provided do not match.'));
             }
         }
         if (is_object($this->fileWriteErrors)) {
             $error = $this->fileWriteErrors;
         }
         $error = $this->validateDatabase($error);
         $error = $this->validateSampleContent($error);
         if ($val->test() && !$error->has()) {
             // write the config file
             $vh = Core::make('helper/validation/identifier');
             $this->fp = @fopen(DIR_CONFIG_SITE . '/site_install.php', 'w+');
             $this->fpu = @fopen(DIR_CONFIG_SITE . '/site_install_user.php', 'w+');
             if ($this->fp) {
                 $config = isset($_POST['SITE_CONFIG']) ? (array) $_POST['SITE_CONFIG'] : array();
                 $config['database'] = array('default-connection' => 'concrete', 'connections' => array('concrete' => array('driver' => 'c5_pdo_mysql', 'server' => $_POST['DB_SERVER'], 'database' => $_POST['DB_DATABASE'], 'username' => $_POST['DB_USERNAME'], 'password' => $_POST['DB_PASSWORD'], 'charset' => 'utf8')));
                 $renderer = new Renderer($config);
                 fwrite($this->fp, $renderer->render());
                 fclose($this->fp);
                 chmod(DIR_CONFIG_SITE . '/site_install.php', 0700);
             } else {
                 throw new Exception(t('Unable to open config/app.php for writing.'));
             }
             if ($this->fpu) {
                 $hasher = new PasswordHash(Config::get('concrete.user.password.hash_cost_log2'), Config::get('concrete.user.password.hash_portable'));
                 $configuration = "<?php\n";
                 $configuration .= "define('INSTALL_USER_EMAIL', '" . $_POST['uEmail'] . "');\n";
                 $configuration .= "define('INSTALL_USER_PASSWORD_HASH', '" . $hasher->HashPassword($_POST['uPassword']) . "');\n";
                 $configuration .= "define('INSTALL_STARTING_POINT', '" . $this->post('SAMPLE_CONTENT') . "');\n";
                 $configuration .= "define('SITE', '" . addslashes($_POST['SITE']) . "');\n";
                 if (Localization::activeLocale() != '' && Localization::activeLocale() != 'en_US') {
                     $configuration .= "define('SITE_INSTALL_LOCALE', '" . Localization::activeLocale() . "');\n";
                 }
                 $res = fwrite($this->fpu, $configuration);
                 fclose($this->fpu);
                 chmod(DIR_CONFIG_SITE . '/site_install_user.php', 0700);
                 if (PHP_SAPI != 'cli') {
                     $this->redirect('/');
                 }
             } else {
                 throw new Exception(t('Unable to open config/site_user.php for writing.'));
             }
         } else {
             if ($error->has()) {
                 $this->set('error', $error);
             } else {
                 $error = $val->getError();
                 $this->set('error', $val->getError());
             }
         }
     } catch (Exception $ex) {
         $this->reset();
         $this->set('error', $ex);
         $error->add($ex);
     }
     return $error;
 }
 public function add_users()
 {
     // Firstly, install the core authentication types
     $cba = AuthenticationType::add('concrete', 'Standard');
     $coa = AuthenticationType::add('community', 'concrete5.org');
     $fba = AuthenticationType::add('facebook', 'Facebook');
     $twa = AuthenticationType::add('twitter', 'Twitter');
     $gat = AuthenticationType::add('google', 'Google');
     $fba->disable();
     $twa->disable();
     $coa->disable();
     $gat->disable();
     \Concrete\Core\Tree\TreeType::add('group');
     \Concrete\Core\Tree\Node\NodeType::add('group');
     $tree = GroupTree::get();
     $tree = GroupTree::add();
     // insert the default groups
     // create the groups our site users
     // specify the ID's since auto increment may not always be +1
     $g1 = Group::add(tc("GroupName", "Guest"), tc("GroupDescription", "The guest group represents unregistered visitors to your site."), false, false, GUEST_GROUP_ID);
     $g2 = Group::add(tc("GroupName", "Registered Users"), tc("GroupDescription", "The registered users group represents all user accounts."), false, false, REGISTERED_GROUP_ID);
     $g3 = Group::add(tc("GroupName", "Administrators"), "", false, false, ADMIN_GROUP_ID);
     // insert admin user into the user table
     if (defined('INSTALL_USER_PASSWORD')) {
         $hasher = new PasswordHash(Config::get('concrete.user.password.hash_cost_log2'), Config::get('concrete.user.password.hash_portable'));
         $uPassword = INSTALL_USER_PASSWORD;
         $uPasswordEncrypted = $hasher->HashPassword($uPassword);
     } else {
         $uPasswordEncrypted = INSTALL_USER_PASSWORD_HASH;
     }
     $uEmail = INSTALL_USER_EMAIL;
     $superuser = UserInfo::addSuperUser($uPasswordEncrypted, $uEmail);
     $u = User::getByUserID(USER_SUPER_ID, true, false);
     MailImporter::add(array('miHandle' => 'private_message'));
     UserPointAction::add('won_badge', t('Won a Badge'), 5, false, true);
     // Install conversation default email
     \Conversation::setDefaultSubscribedUsers(array($superuser));
 }
$cliconfig = array_merge($_defaults, $cliArguments);
// Configurations
require $cliconfig['core'] . "/bootstrap/configure.php";
// Autoloader
require $cliconfig['core'] . "/bootstrap/autoload.php";
// CMS
$cms = (require $cliconfig['core'] . "/bootstrap/start.php");
// Database connection
\Database::extend('install', function () use($cliconfig) {
    return \Database::getFactory()->createConnection(array('host' => $cliconfig['db-server'], 'user' => $cliconfig['db-username'], 'password' => $cliconfig['db-password'], 'database' => $cliconfig['db-database']));
});
\Database::setDefaultConnection('install');
$cms['config']['database.connections.install'] = array();
// Disable all caches
Cache::disableAll();
// Install data setup
$passHash = new PasswordHash(Config::get('concrete.user.password.hash_cost_log2'), Config::get('concrete.user.password.hash_portable'));
define('INSTALL_USER_EMAIL', $cliconfig['admin-email']);
define('INSTALL_USER_PASSWORD_HASH', $passHash->HashPassword($cliconfig['admin-password']));
define('INSTALL_STARTING_POINT', $cliconfig['starting-point']);
define('SITE', $cliconfig['site']);
$startingPoint = StartingPointPackage::getClass(INSTALL_STARTING_POINT);
$routines = $startingPoint->getInstallRoutines();
// Redefine the error handlers, overriding any registered by C5
set_error_handler('customErrorHandler');
foreach ($routines as $r) {
    fwrite(STDOUT, sprintf("%s: %s \n", $r->getProgress(), $r->getText()));
    call_user_func(array($startingPoint, $r->getMethod()));
}
fwrite(STDOUT, "!!!!!! Installation Complete: OK !!!!!!\n");
exit(0);
Esempio n. 29
0
 public function make($value, array $options = [])
 {
     return $this->hasher->HashPassword($value);
 }
Esempio n. 30
0
 /**
  * Generate a cryptographically secure random string
  * @param int $length
  * @return string
  */
 public function getString($length = 12)
 {
     $size = ceil($length / 2);
     try {
         if (function_exists('random_bytes')) {
             $bytes = random_bytes($size);
         } else {
             $hash = new PasswordHash(8, false);
             $bytes = $hash->get_random_bytes($size);
         }
     } catch (\Exception $e) {
         die('Could not generate a random string.');
     }
     return substr(bin2hex($bytes), 0, $length);
 }