hash() public static method

Generate a password hash
public static hash ( string $strPassword ) : string
$strPassword string The unencrypted password
return string The encrypted password
コード例 #1
0
 /**
  * Run the controller and parse the password template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_password');
     if (\Input::post('FORM_SUBMIT') == 'tl_password') {
         $pw = \Input::postUnsafeRaw('password');
         $cnf = \Input::postUnsafeRaw('confirm');
         // The passwords do not match
         if ($pw != $cnf) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
         } elseif (Utf8::strlen($pw) < \Config::get('minPasswordLength')) {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
         } elseif ($pw == $this->User->username) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
         } else {
             // Make sure the password has been changed
             if (\Encryption::verify($pw, $this->User->password)) {
                 \Message::addError($GLOBALS['TL_LANG']['MSC']['pw_change']);
             } else {
                 $this->loadDataContainer('tl_user');
                 // Trigger the save_callback
                 if (is_array($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'])) {
                     foreach ($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'] as $callback) {
                         if (is_array($callback)) {
                             $this->import($callback[0]);
                             $pw = $this->{$callback[0]}->{$callback[1]}($pw);
                         } elseif (is_callable($callback)) {
                             $pw = $callback($pw);
                         }
                     }
                 }
                 $objUser = \UserModel::findByPk($this->User->id);
                 $objUser->pwChange = '';
                 $objUser->password = \Encryption::hash($pw);
                 $objUser->save();
                 \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
                 $this->redirect('contao/main.php');
             }
         }
         $this->reload();
     }
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->messages = \Message::generate();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['pw_new']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['MSC']['pw_change'];
     $objTemplate->submitButton = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['continue']);
     $objTemplate->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['confirm'][0];
     return $objTemplate->getResponse();
 }
コード例 #2
0
 /**
  * Check if user authentication succeeds on phpbb site and if so update contao member
  *
  * @param $username
  * @param $password
  * @param User $user
  * @return bool
  */
 public function onCheckCredentials($username, $password, User $user)
 {
     // Only try to login if it's frontend user
     if ($user instanceof FrontendUser) {
         $loginResult = System::getContainer()->get('phpbb_bridge.connector')->validateLogin($username, $password);
         // Login was successful on phpbb side. Maybe user changed his password. So do we for contao then
         if ($loginResult === true) {
             $user->password = Encryption::hash($password);
             $user->save();
             return true;
         }
     }
     return false;
 }
コード例 #3
0
 /**
  * @param null $dc
  * @throws \Exception
  */
 public function setAutoPassword($dc = null)
 {
     // Front end call
     if (!$dc instanceof DataContainer) {
         return;
     }
     if ($this->isDisabledAccountmail($dc)) {
         return;
     }
     $intId = $dc->id;
     if (Input::get('act') == 'overrideAll' && Input::get('fields') && $intId === null) {
         // Define indicator for given or not given password on overrideAll mode
         if (!isset($GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'])) {
             $strPassword = $this->getPostPassword();
             $GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'] = $strPassword == '' || $strPassword == '*****' ? true : false;
             if ($GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'] === true) {
                 // Set password, that no error occurs with "password not set"
                 $strNewPassword = substr(str_shuffle('abcdefghkmnpqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ0123456789'), 0, 8);
                 $this->setPostPassword($strNewPassword);
             }
             Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
         }
         return;
     }
     $strPassword = $this->getPostPassword($intId);
     if ($strPassword !== null && $strPassword == '') {
         $strModel = Model::getClassFromTable($dc->table);
         $objAccount = $strModel::findByPk($intId);
         if ($objAccount !== null) {
             $strNewPassword = substr(str_shuffle('abcdefghkmnpqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ0123456789'), 0, 8);
             $this->setPostPassword($strNewPassword, $intId);
             Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
             $objAccount->password = Encryption::hash($strNewPassword);
             $objAccount->save();
         }
     }
 }
コード例 #4
0
 /**
  * Renders a form to set the install tool password.
  *
  * @return Response|RedirectResponse The response object
  */
 private function setPassword()
 {
     $request = $this->container->get('request_stack')->getCurrentRequest();
     if ('tl_password' !== $request->request->get('FORM_SUBMIT')) {
         return $this->render('password.html.twig');
     }
     $password = $request->request->get('password');
     $confirmation = $request->request->get('confirmation');
     // The passwords do not match
     if ($password !== $confirmation) {
         return $this->render('password.html.twig', ['error' => $this->trans('password_confirmation_mismatch')]);
     }
     $installTool = $this->container->get('contao.install_tool');
     $minlength = $installTool->getConfig('minPasswordLength');
     // The passwords is too short
     if (Utf8::strlen($password) < $minlength) {
         return $this->render('password.html.twig', ['error' => sprintf($this->trans('password_too_short'), $minlength)]);
     }
     $installTool->persistConfig('installPassword', Encryption::hash($password));
     $this->container->get('contao.install_tool_user')->setAuthenticated(true);
     return $this->getRedirectResponse();
 }
コード例 #5
0
 /**
  * Imports a user from phpbb to contao
  *
  * @param $username
  * @param $password
  * @return bool
  * @throws \Exception
  */
 public function importUser($username, $password)
 {
     if ($this->debug) {
         System::log("phpbb_bridge: " . __METHOD__, __METHOD__, TL_ACCESS);
     }
     // Find User in forum
     $user = $this->getUser($username);
     if ($user) {
         System::log('Importing User ' . $username, __METHOD__, TL_ACCESS);
         // Try to find user by real username if he entered username_clean
         // he may not be imported yet with it's clean username
         $contaoUser = MemberModel::findByUsername($user->username);
         if (null == $contaoUser) {
             $contaoUser = new MemberModel();
         }
         $contaoUser->username = $user->username;
         $contaoUser->username_clean = $user->username_clean;
         $contaoUser->email = $user->user_email;
         $contaoUser->firstname = 'Vorname';
         $contaoUser->lastname = 'Nachname';
         $contaoUser->password = Encryption::hash($password);
         $contaoUser->login = 1;
         $contaoUser->tstamp = $contaoUser->dateAdded = time();
         $contaoUser->groups = $this->getForumMemberGroupIds(true);
         // @todo add try catch, make it more safe, logout phpbb user on fail?
         $contaoUser->save();
         System::log('User imported: ' . $contaoUser->username, __METHOD__, TL_ACCESS);
         // username_clean used for login
         if ($username != $contaoUser->username) {
             Input::setPost('username', $contaoUser->username);
         }
         return true;
     } else {
         System::log($username . ' could not be found in phpbb db', __METHOD__, TL_ACCESS);
         return false;
     }
 }
コード例 #6
0
ファイル: InstallTool.php プロジェクト: burguin/test02
 /**
  * Persists the admin user.
  *
  * @param string $username The username
  * @param string $name     The name
  * @param string $email    The e-mail address
  * @param string $password The plain text password
  * @param string $language The language
  */
 public function persistAdminUser($username, $name, $email, $password, $language)
 {
     $statement = $this->connection->prepare("\n            INSERT INTO tl_user(\n                tstamp,\n                name,\n                email,\n                username,\n                password,\n                language,\n                backendTheme,\n                admin,\n                showHelp,\n                useRTE,\n                useCE,\n                thumbnails,\n                dateAdded\n            ) VALUES (\n                :time,\n                :name,\n                :email,\n                :username,\n                :password,\n                :language,\n                'flexible',\n                1,\n                1,\n                1,\n                1,\n                1,\n                :time\n            )\n        ");
     $replace = ['#' => '&#35;', '<' => '&#60;', '>' => '&#62;', '(' => '&#40;', ')' => '&#41;', '\\' => '&#92;', '=' => '&#61;'];
     $statement->execute([':time' => time(), ':name' => strtr($name, $replace), ':email' => $email, ':username' => strtr($username, $replace), ':password' => Encryption::hash($password), ':language' => $language]);
 }
コード例 #7
0
ファイル: User.php プロジェクト: qzminski/contao-core-bundle
 /**
  * Try to login the current user
  *
  * @return boolean True if the user could be logged in
  */
 public function login()
 {
     \System::loadLanguageFile('default');
     // Do not continue if username or password are missing
     if (empty($_POST['username']) || empty($_POST['password'])) {
         return false;
     }
     // Load the user object
     if ($this->findBy('username', \Input::post('username', true)) == false) {
         $blnLoaded = false;
         // HOOK: pass credentials to callback functions
         if (isset($GLOBALS['TL_HOOKS']['importUser']) && is_array($GLOBALS['TL_HOOKS']['importUser'])) {
             foreach ($GLOBALS['TL_HOOKS']['importUser'] as $callback) {
                 $this->import($callback[0], 'objImport', true);
                 $blnLoaded = $this->objImport->{$callback[1]}(\Input::post('username', true), \Input::postUnsafeRaw('password'), $this->strTable);
                 // Load successfull
                 if ($blnLoaded === true) {
                     break;
                 }
             }
         }
         // Return if the user still cannot be loaded
         if (!$blnLoaded || $this->findBy('username', \Input::post('username', true)) == false) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
             $this->log('Could not find user "' . \Input::post('username', true) . '"', __METHOD__, TL_ACCESS);
             return false;
         }
     }
     $time = time();
     // Set the user language
     if (\Input::post('language')) {
         $this->language = \Input::post('language');
     }
     // Lock the account if there are too many login attempts
     if ($this->loginCount < 1) {
         $this->locked = $time;
         $this->loginCount = \Config::get('loginCount');
         $this->save();
         // Add a log entry and the error message, because checkAccountStatus() will not be called (see #4444)
         $this->log('User "' . $this->username . '" has been locked for ' . ceil(\Config::get('lockPeriod') / 60) . ' minutes', __METHOD__, TL_ACCESS);
         \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['accountLocked'], ceil(($this->locked + \Config::get('lockPeriod') - $time) / 60)));
         // Send admin notification
         if (\Config::get('adminEmail') != '') {
             $objEmail = new \Email();
             $objEmail->subject = $GLOBALS['TL_LANG']['MSC']['lockedAccount'][0];
             $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['lockedAccount'][1], $this->username, TL_MODE == 'FE' ? $this->firstname . " " . $this->lastname : $this->name, \Idna::decode(\Environment::get('base')), ceil(\Config::get('lockPeriod') / 60));
             $objEmail->sendTo(\Config::get('adminEmail'));
         }
         return false;
     }
     // Check the account status
     if ($this->checkAccountStatus() == false) {
         return false;
     }
     // The password has been generated with crypt()
     if (\Encryption::test($this->password)) {
         $blnAuthenticated = \Encryption::verify(\Input::postUnsafeRaw('password'), $this->password);
     } else {
         list($strPassword, $strSalt) = explode(':', $this->password);
         $blnAuthenticated = $strSalt == '' ? $strPassword === sha1(\Input::postUnsafeRaw('password')) : $strPassword === sha1($strSalt . \Input::postUnsafeRaw('password'));
         // Store a SHA-512 encrpyted version of the password
         if ($blnAuthenticated) {
             $this->password = \Encryption::hash(\Input::postUnsafeRaw('password'));
         }
     }
     // HOOK: pass credentials to callback functions
     if (!$blnAuthenticated && isset($GLOBALS['TL_HOOKS']['checkCredentials']) && is_array($GLOBALS['TL_HOOKS']['checkCredentials'])) {
         foreach ($GLOBALS['TL_HOOKS']['checkCredentials'] as $callback) {
             $this->import($callback[0], 'objAuth', true);
             $blnAuthenticated = $this->objAuth->{$callback[1]}(\Input::post('username', true), \Input::postUnsafeRaw('password'), $this);
             // Authentication successfull
             if ($blnAuthenticated === true) {
                 break;
             }
         }
     }
     // Redirect if the user could not be authenticated
     if (!$blnAuthenticated) {
         --$this->loginCount;
         $this->save();
         \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
         $this->log('Invalid password submitted for username "' . $this->username . '"', __METHOD__, TL_ACCESS);
         return false;
     }
     $this->setUserFromDb();
     // Update the record
     $this->lastLogin = $this->currentLogin;
     $this->currentLogin = $time;
     $this->loginCount = \Config::get('loginCount');
     $this->save();
     // Generate the session
     $this->regenerateSessionId();
     $this->generateSession();
     $this->log('User "' . $this->username . '" has logged in', __METHOD__, TL_ACCESS);
     // HOOK: post login callback
     if (isset($GLOBALS['TL_HOOKS']['postLogin']) && is_array($GLOBALS['TL_HOOKS']['postLogin'])) {
         foreach ($GLOBALS['TL_HOOKS']['postLogin'] as $callback) {
             $this->import($callback[0], 'objLogin', true);
             $this->objLogin->{$callback[1]}($this);
         }
     }
     return true;
 }
コード例 #8
0
ファイル: FormPassword.php プロジェクト: Mozan/core-bundle
 /**
  * Validate input and set value
  *
  * @param mixed $varInput The user input
  *
  * @return mixed The validated user input
  */
 protected function validator($varInput)
 {
     $this->blnSubmitInput = false;
     if (!strlen($varInput) && (strlen($this->varValue) || !$this->mandatory)) {
         return '';
     }
     if (Utf8::strlen($varInput) < \Config::get('minPasswordLength')) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
     }
     if ($varInput != $this->getPost($this->strName . '_confirm')) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
     }
     $varInput = parent::validator($varInput);
     if (!$this->hasErrors()) {
         $this->blnSubmitInput = true;
         return \Encryption::hash($varInput);
     }
     return '';
 }
コード例 #9
0
ファイル: Password.php プロジェクト: contao/core-bundle
 /**
  * Validate input and set value
  *
  * @param mixed $varInput
  *
  * @return string
  */
 protected function validator($varInput)
 {
     $this->blnSubmitInput = false;
     if (($varInput == '' || $varInput == '*****') && $this->varValue != '') {
         return '*****';
     }
     if (Utf8::strlen($varInput) < \Config::get('minPasswordLength')) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
     }
     if ($varInput != $this->getPost($this->strName . '_confirm')) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
     }
     if ($varInput == $GLOBALS['TL_USERNAME']) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
     }
     $varInput = parent::validator($varInput);
     if (!$this->hasErrors()) {
         $this->blnSubmitInput = true;
         \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
         return \Encryption::hash($varInput);
     }
     return '';
 }
コード例 #10
0
 /**
  * Create an admin user
  */
 protected function createAdminUser()
 {
     try {
         $objAdmin = $this->Database->execute("SELECT COUNT(*) AS count FROM tl_user WHERE admin=1");
         if ($objAdmin->count > 0) {
             $this->Template->adminCreated = true;
         } elseif (\Input::post('FORM_SUBMIT') == 'tl_admin') {
             // Do not allow special characters in usernames
             if (preg_match('/[#\\(\\)\\/<=>]/', \Input::post('username', true))) {
                 $this->Template->usernameError = $GLOBALS['TL_LANG']['ERR']['extnd'];
             } elseif (strpos(\Input::post('username', true), ' ') !== false) {
                 $this->Template->usernameError = sprintf($GLOBALS['TL_LANG']['ERR']['noSpace'], $GLOBALS['TL_LANG']['MSC']['username']);
             } elseif (!\Validator::isEmail(\Input::post('email', true))) {
                 $this->Template->emailError = $GLOBALS['TL_LANG']['ERR']['email'];
             } elseif (\Input::post('pass', true) != \Input::post('confirm_pass', true)) {
                 $this->Template->passwordError = $GLOBALS['TL_LANG']['ERR']['passwordMatch'];
             } elseif (utf8_strlen(\Input::post('pass', true)) < \Config::get('minPasswordLength')) {
                 $this->Template->passwordError = sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength'));
             } elseif (\Input::post('pass', true) == \Input::post('username', true)) {
                 $this->Template->passwordError = $GLOBALS['TL_LANG']['ERR']['passwordName'];
             } elseif (\Input::post('name') != '' && \Input::post('email', true) != '' && \Input::post('username', true) != '') {
                 $time = time();
                 $strPassword = \Encryption::hash(\Input::post('pass', true));
                 $this->Database->prepare("INSERT INTO tl_user (tstamp, name, email, username, password, language, backendTheme, admin, showHelp, useRTE, useCE, thumbnails, dateAdded) VALUES ({$time}, ?, ?, ?, ?, ?, ?, 1, 1, 1, 1, 1, {$time})")->execute(\Input::post('name'), \Input::post('email', true), \Input::post('username', true), $strPassword, str_replace('-', '_', $GLOBALS['TL_LANGUAGE']), \Config::get('backendTheme'));
                 \Config::persist('adminEmail', \Input::post('email', true));
                 // Scan the upload folder (see #6134)
                 if ($this->Database->tableExists('tl_files') && $this->Database->query("SELECT COUNT(*) AS count FROM tl_files")->count < 1) {
                     $this->import('Database\\Updater', 'Updater');
                     $this->Updater->scanUploadFolder();
                 }
                 $this->reload();
             }
             $this->Template->adminName = \Input::post('name');
             $this->Template->adminEmail = \Input::post('email', true);
             $this->Template->adminUser = \Input::post('username', true);
         }
     } catch (ResponseException $e) {
         throw $e;
         // see #267
     } catch (\Exception $e) {
         $this->Template->adminCreated = false;
     }
 }