Beispiel #1
0
 if ($gCurrentUser->isWebmaster() && $gCurrentUser->getValue('usr_id') != $getUserId) {
     $oldPassword = '';
 } else {
     $oldPassword = $_POST['old_password'];
 }
 $newPassword = $_POST['new_password'];
 $newPasswordConfirm = $_POST['new_password_confirm'];
 /***********************************************************************/
 /* Handle form input */
 /***********************************************************************/
 if (($oldPassword !== '' || $gCurrentUser->isWebmaster()) && $newPassword !== '' && $newPasswordConfirm !== '') {
     if (strlen($newPassword) >= 8) {
         if ($newPassword === $newPasswordConfirm) {
             // check if old password is correct.
             // Webmaster could change password of other users without this verification.
             if (PasswordHashing::verify($oldPassword, $user->getValue('usr_password')) || $gCurrentUser->isWebmaster() && $gCurrentUser->getValue('usr_id') != $getUserId) {
                 $user->setPassword($newPassword);
                 $user->save();
                 // if password of current user changed, then update value in current session
                 if ($user->getValue('usr_id') == $gCurrentUser->getValue('usr_id')) {
                     $gCurrentUser->setPassword($newPassword);
                 }
                 $phrase = 'success';
             } else {
                 $phrase = $gL10n->get('PRO_PASSWORD_OLD_WRONG');
             }
         } else {
             $phrase = $gL10n->get('PRO_PASSWORDS_NOT_EQUAL');
         }
     } else {
         $phrase = $gL10n->get('PRO_PASSWORD_LENGTH');
 * PHP 5.5 provides simple, easy and secure password handling with bcrypt and
 * automatic random salting. The values below are all hashes for the password
 * 'password' except the 3rd which is 'passworda'. You'll notice that every hash
 * is significantly different from the other and that password_verify can determine
 * if the password matches the hash.
 *
 * Reloading the sample will result in all new hashes.
 */
class PasswordHashing
{
    protected $password = '******';
    public function getPassword()
    {
        return $this->password;
    }
    public function createPasswordArray()
    {
        $password = $this->getPassword();
        return [password_hash($password, PASSWORD_DEFAULT), password_hash($password, PASSWORD_DEFAULT), password_hash($password . 'a', PASSWORD_DEFAULT), password_hash($password, PASSWORD_DEFAULT), password_hash($password, PASSWORD_DEFAULT), password_hash($password, PASSWORD_DEFAULT)];
    }
}
$passwordHasher = new PasswordHashing();
$password = $passwordHasher->getPassword();
$passwordArray = $passwordHasher->createPasswordArray();
var_dump($passwordArray);
// Check passwords:
foreach ($passwordArray as $passwordValue) {
    echo "Password {$passwordValue} matches {$password}: ";
    echo password_verify($password, $passwordValue) ? 'Yes' : 'No';
    echo '<br>';
}
Beispiel #3
0
 /**
  * Creates a new unique auto login id for this user.
  * @param int $userId The id of the current user.
  * @return string Returns the auto login id.
  */
 public function generateAutoLoginId($userId)
 {
     return $userId . ':' . PasswordHashing::genRandomPassword(40);
 }
Beispiel #4
0
 /**
  * Check if a valid password is set for the user and return true if the correct password
  * was set. Optional the current session could be updated to a valid login session.
  * @param string $password             The password for the current user. This should not be encoded.
  * @param bool   $setAutoLogin         If set to true then this login will be stored in AutoLogin table
  *                                     and the user doesn't need to login another time with this browser.
  *                                     To use this functionality @b $updateSessionCookies must be set to true.
  * @param bool   $updateSessionCookies The current session will be updated to a valid login.
  *                                     If set to false then the login is only valid for the current script.
  * @param bool   $updateHash           If set to true the code will check if the current password hash uses
  *                                     the best hashing algorithm. If not the password will be rehashed with
  *                                     the new algorithm. If set to false the password will not be rehashed.
  * @param bool   $isWebmaster          If set to true the code will check if the current password hash uses
  * @return true|string Return true if login was successful and a string with the reason why the login failed.
  *                     Possible reasons: SYS_LOGIN_MAX_INVALID_LOGIN
  *                                       SYS_LOGIN_NOT_ACTIVATED
  *                                       SYS_LOGIN_USER_NO_MEMBER_IN_ORGANISATION
  *                                       SYS_LOGIN_USER_NO_WEBMASTER
  *                                       SYS_LOGIN_USERNAME_PASSWORD_INCORRECT
  */
 public function checkLogin($password, $setAutoLogin = false, $updateSessionCookies = true, $updateHash = true, $isWebmaster = false)
 {
     global $gPreferences, $gCookiePraefix, $gCurrentSession, $gSessionId, $installedDbVersion;
     $invalidLoginCount = $this->getValue('usr_number_invalid');
     // if within 15 minutes 3 wrong login took place -> block user account for 15 minutes
     if ($invalidLoginCount >= 3 && time() - strtotime($this->getValue('usr_date_invalid', 'Y-m-d H:i:s')) < 60 * 15) {
         $this->clear();
         return 'SYS_LOGIN_MAX_INVALID_LOGIN';
     }
     $currHash = $this->getValue('usr_password');
     if (PasswordHashing::verify($password, $currHash)) {
         // Password correct
         // if user is not activated/valid return error message
         if (!$this->getValue('usr_valid')) {
             return 'SYS_LOGIN_NOT_ACTIVATED';
         }
         $sqlWebmaster = '';
         // only check for webmaster role if version > 2.3 because before we don't have that flag
         if ($isWebmaster && version_compare($installedDbVersion, '2.4.0') === 1) {
             $sqlWebmaster = ', rol_webmaster';
         }
         // Check if user is currently member of a role of an organisation
         $sql = 'SELECT DISTINCT mem_usr_id' . $sqlWebmaster . '
                   FROM ' . TBL_MEMBERS . '
             INNER JOIN ' . TBL_ROLES . '
                     ON rol_id = mem_rol_id
             INNER JOIN ' . TBL_CATEGORIES . '
                     ON cat_id = rol_cat_id
                  WHERE mem_usr_id = ' . $this->getValue('usr_id') . '
                    AND rol_valid  = 1
                    AND mem_begin <= \'' . DATE_NOW . '\'
                    AND mem_end    > \'' . DATE_NOW . '\'
                    AND cat_org_id = ' . $this->organizationId;
         $userStatement = $this->db->query($sql);
         if ($userStatement->rowCount() === 0) {
             return 'SYS_LOGIN_USER_NO_MEMBER_IN_ORGANISATION';
         }
         $userRow = $userStatement->fetch();
         if ($isWebmaster && version_compare($installedDbVersion, '2.4.0') === 1 && $userRow['rol_webmaster'] == 0) {
             return 'SYS_LOGIN_USER_NO_WEBMASTER';
         }
         // Rehash password if the hash is outdated and rehashing is enabled
         if ($updateHash && PasswordHashing::needsRehash($currHash)) {
             $this->setPassword($password);
             $this->save();
         }
         if ($updateSessionCookies) {
             $gCurrentSession->setValue('ses_usr_id', $this->getValue('usr_id'));
             $gCurrentSession->save();
         }
         // should the user stayed logged in automatically, than the cookie would expire in one year
         if ($setAutoLogin && $gPreferences['enable_auto_login'] == 1) {
             $gCurrentSession->setAutoLogin();
         } else {
             $this->setValue('usr_last_session_id', null);
         }
         if ($updateSessionCookies) {
             // set cookie for session id and remove ports from domain
             $domain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
             setcookie($gCookiePraefix . '_ID', $gSessionId, 0, '/', $domain, 0);
             // count logins and update login dates
             $this->saveChangesWithoutRights();
             $this->updateLoginData();
         }
         return true;
     } else {
         // Password wrong
         // log invalid logins
         if ($invalidLoginCount >= 3) {
             $this->setValue('usr_number_invalid', 1);
         } else {
             $this->setValue('usr_number_invalid', $this->getValue('usr_number_invalid') + 1);
         }
         $this->setValue('usr_date_invalid', DATETIME_NOW);
         $this->saveChangesWithoutRights();
         $this->save(false);
         // don't update timestamp
         $this->clear();
         if ($this->getValue('usr_number_invalid') >= 3) {
             return 'SYS_LOGIN_MAX_INVALID_LOGIN';
         } else {
             return 'SYS_LOGIN_USERNAME_PASSWORD_INCORRECT';
         }
     }
 }
Beispiel #5
0
        $gMessage->show($gL10n->get('SYS_NO_RIGHTS'));
    }
    $phrase = $gL10n->get('SYS_DELETE_DATA');
    // User aus der Admidio Datenbank loeschen
    $user->delete();
} elseif ($getMode === 4) {
    // nur Webmaster duerfen User neue Zugangsdaten zuschicken
    // nur ausfuehren, wenn E-Mails vom Server unterstuetzt werden
    // nur an Mitglieder der eigenen Organisation schicken
    if (!$gCurrentUser->isWebmaster() || $gPreferences['enable_system_mails'] != 1 || $this_orga == false) {
        $gMessage->show($gL10n->get('SYS_NO_RIGHTS'));
    }
    if ($gPreferences['enable_system_mails'] == 1) {
        try {
            // neues Passwort generieren und abspeichern
            $password = PasswordHashing::genRandomPassword(8);
            $user->setPassword($password);
            $user->save();
            // Mail an den User mit den Loginaten schicken
            $sysmail = new SystemMail($gDb);
            $sysmail->addRecipient($user->getValue('EMAIL'), $user->getValue('FIRST_NAME') . ' ' . $user->getValue('LAST_NAME'));
            $sysmail->setVariable(1, $password);
            $sysmail->sendSystemMail('SYSMAIL_NEW_PASSWORD', $user);
            $gMessage->setForwardUrl($gNavigation->getUrl());
            $gMessage->show($gL10n->get('SYS_EMAIL_SEND'));
        } catch (AdmException $e) {
            $e->showText();
        }
    }
} elseif ($getMode === 5) {
    // Fragen, ob Zugangsdaten verschickt werden sollen
Beispiel #6
0
                   AND usr_valid  = 1
                   AND LENGTH(usr_login_name) > 0
                 GROUP BY usr_id';
        $pdoStatement = $gDb->query($sql);
        $count = $pdoStatement->rowCount();
        // show error if no user found or more than one user found
        if ($count === 0) {
            $gMessage->show($gL10n->get('SYS_LOSTPW_EMAIL_ERROR', $_POST['recipient_email']));
        } elseif ($count > 1) {
            $gMessage->show($gL10n->get('SYS_LOSTPW_SEVERAL_EMAIL', $_POST['recipient_email']));
        }
        $row = $pdoStatement->fetch();
        $user = new User($gDb, $gProfileFields, $row['usr_id']);
        // create and save new password and activation id
        $newPassword = PasswordHashing::genRandomPassword(8);
        $activationId = PasswordHashing::genRandomPassword(10);
        $user->setPassword($newPassword, true);
        $user->setValue('usr_activation_code', $activationId);
        $sysmail = new SystemMail($gDb);
        $sysmail->addRecipient($user->getValue('EMAIL'), $user->getValue('FIRST_NAME', 'database') . ' ' . $user->getValue('LAST_NAME', 'database'));
        $sysmail->setVariable(1, $newPassword);
        $sysmail->setVariable(2, $g_root_path . '/adm_program/system/password_activation.php?usr_id=' . $user->getValue('usr_id') . '&aid=' . $activationId);
        $sysmail->sendSystemMail('SYSMAIL_ACTIVATION_LINK', $user);
        $user->saveChangesWithoutRights();
        $user->save();
        $gMessage->setForwardUrl($g_root_path . '/adm_program/system/login.php');
        $gMessage->show($gL10n->get('SYS_LOSTPW_SEND', $_POST['recipient_email']));
    } catch (AdmException $e) {
        $e->showHtml();
    }
} else {
Beispiel #7
0
 /**
  * Set a new value for a password column of the database table.
  * The value is only saved in the object. You must call the method @b save to store the new value to the database
  * @param string $newPassword   The new value that should be stored in the database field
  * @param bool   $isNewPassword Should the column password or new_password be set
  * @param bool   $doHashing     Should the password get hashed before inserted. Default is true
  * @return bool Returns @b true if the value is stored in the current object and @b false if a check failed
  */
 public function setPassword($newPassword, $isNewPassword = false, $doHashing = true)
 {
     global $gPreferences;
     $columnName = 'usr_password';
     if ($isNewPassword) {
         $columnName = 'usr_new_password';
     }
     if ($doHashing) {
         // get the saved cost value that fits your server performance best and rehash your password
         $cost = 10;
         if (isset($gPreferences['system_hashing_cost'])) {
             $cost = intval($gPreferences['system_hashing_cost']);
         }
         $newPassword = PasswordHashing::hash($newPassword, PASSWORD_DEFAULT, array('cost' => $cost));
     }
     return parent::setValue($columnName, $newPassword, false);
 }
Beispiel #8
0
         }
         // else continue with code below
     }
 }
 // setzt die Ausfuehrungszeit des Scripts auf 2 Min., da hier teilweise sehr viel gemacht wird
 // allerdings darf hier keine Fehlermeldung wg. dem safe_mode kommen
 @set_time_limit(300);
 $mainVersion = substr($installedDbVersion, 0, 1);
 $subVersion = substr($installedDbVersion, 2, 1);
 $microVersion = substr($installedDbVersion, 4, 1);
 $microVersion = (int) $microVersion + 1;
 $flagNextVersion = true;
 // erst einmal die evtl. neuen Orga-Einstellungen in DB schreiben
 require_once 'db_scripts/preferences.php';
 // calculate the best cost value for your server performance
 $benchmarkResults = PasswordHashing::costBenchmark();
 $orga_preferences['system_hashing_cost'] = $benchmarkResults['cost'];
 $sql = 'SELECT * FROM ' . TBL_ORGANIZATIONS;
 $orgaStatement = $gDb->query($sql);
 while ($row_orga = $orgaStatement->fetch()) {
     $gCurrentOrganization->setValue('org_id', $row_orga['org_id']);
     $gCurrentOrganization->setPreferences($orga_preferences, false);
 }
 if ($gDbType === 'mysql') {
     // disable foreign key checks for mysql, so tables can easily deleted
     $sql = 'SET foreign_key_checks = 0 ';
     $gDb->query($sql);
 }
 // before version 3 we had an other update mechanism which will be handled here
 if ($mainVersion < 3) {
     // nun in einer Schleife die Update-Scripte fuer alle Versionen zwischen der Alten und Neuen einspielen
Beispiel #9
0
 /**
  * Check if a valid password is set for the user and return true if the correct password
  * was set. Optional the current session could be updated to a valid login session.
  * @param  string       $password             The password for the current user. This should not be encoded.
  * @param  bool         $setAutoLogin         If set to true then this login will be stored in AutoLogin table
  *                                            and the user doesn't need to login another time with this browser.
  *                                            To use this functionality @b $updateSessionCookies must be set to true.
  * @param  bool         $updateSessionCookies The current session will be updated to a valid login.
  *                                            If set to false then the login is only valid for the current script.
  * @throws AdmException SYS_LOGIN_FAILED
  *                                           SYS_LOGIN_FAILED
  *                                           SYS_PASSWORD_UNKNOWN
  * @return true         Return true if the correct password for this user was given to this method.
  */
 public function checkLogin($password, $setAutoLogin = false, $updateSessionCookies = true)
 {
     global $gPreferences, $gCookiePraefix, $gCurrentSession, $gSessionId;
     if ($this->getValue('usr_number_invalid') >= 3) {
         // if within 15 minutes 3 wrong login took place -> block user account for 15 minutes
         if (time() - strtotime($this->getValue('usr_date_invalid', 'Y-m-d H:i:s')) < 900) {
             $this->clear();
             throw new AdmException('SYS_LOGIN_FAILED');
         }
     }
     $currHash = $this->getValue('usr_password');
     if (PasswordHashing::verify($password, $currHash)) {
         if (PasswordHashing::needsRehash($currHash)) {
             $this->setPassword($password);
             $this->save();
         }
         if ($updateSessionCookies) {
             $gCurrentSession->setValue('ses_usr_id', $this->getValue('usr_id'));
             $gCurrentSession->save();
         }
         // soll der Besucher automatisch eingeloggt bleiben, dann verfaellt das Cookie erst nach einem Jahr
         if ($setAutoLogin && $gPreferences['enable_auto_login'] == 1) {
             $timestamp_expired = time() + 60 * 60 * 24 * 365;
             $autoLogin = new AutoLogin($this->db, $gSessionId);
             // falls bereits ein Autologin existiert (Doppelanmeldung an 1 Browser),
             // dann kein Neues anlegen, da dies zu 'Duplicate Key' fuehrt
             if ($autoLogin->getValue('atl_usr_id') === '') {
                 $autoLogin->setValue('atl_session_id', $gSessionId);
                 $autoLogin->setValue('atl_usr_id', $this->getValue('usr_id'));
                 $autoLogin->save();
             }
         } else {
             $timestamp_expired = 0;
             $this->setValue('usr_last_session_id', null);
         }
         if ($updateSessionCookies) {
             // Cookies fuer die Anmeldung setzen und evtl. Ports entfernen
             $domain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
             setcookie($gCookiePraefix . '_ID', $gSessionId, $timestamp_expired, '/', $domain, 0);
             // User-Id und Autologin auch noch als Cookie speichern
             // vorher allerdings noch serialisieren, damit der Inhalt nicht so einfach ausgelesen werden kann
             setcookie($gCookiePraefix . '_DATA', $setAutoLogin . ';' . $this->getValue('usr_id'), $timestamp_expired, '/', $domain, 0);
             // count logins and update login dates
             $this->saveChangesWithoutRights();
             $this->updateLoginData();
         }
         return true;
     } else {
         // log invalid logins
         if ($this->getValue('usr_number_invalid') >= 3) {
             $this->setValue('usr_number_invalid', 1);
         } else {
             $this->setValue('usr_number_invalid', $this->getValue('usr_number_invalid') + 1);
         }
         $this->setValue('usr_date_invalid', DATETIME_NOW);
         $this->save(false);
         // don't update timestamp
         $this->clear();
         if ($this->getValue('usr_number_invalid') >= 3) {
             throw new AdmException('SYS_LOGIN_FAILED');
         } else {
             throw new AdmException('SYS_PASSWORD_UNKNOWN');
         }
     }
 }