Beispiel #1
0
 function inscriptionAction()
 {
     $this->metas(array('DC.Title' => "Fiche d'inscription"));
     $this->branche->append();
     $m = new Wtk_Form_Model('inscription');
     // FICHE INDIVIDU
     $g = $m->addGroup('fiche');
     $i = $g->addString('prenom', "Prénom");
     $m->addConstraintRequired($i);
     $i = $g->addString('nom', "Nom");
     $m->addConstraintRequired($i);
     $t = new Unites();
     $sexes = $t->findSexesAccueillis();
     if (in_array('m', $sexes) || count($sexes) > 1) {
         $enum = array('h' => 'Masculin', 'f' => 'Féminin');
         $i = $g->addEnum('sexe', 'Sexe', null, $enum);
         $m->addConstraintRequired($i);
     } else {
         $i = $g->addString('sexe', 'Sexe', $sexes[0])->setReadonly(true);
     }
     $i = $g->addDate('naissance', "Date de naissance", 0);
     $m->addConstraintRequired($i);
     // COMPTE
     $g = $m->addGroup('compte');
     $i = $g->addEMail('adelec', "Adresse électronique");
     $t = new Inscriptions();
     $m->addConstraintForbid($i, $t->findAllEMails(), "Cette adresse électronique est déjà utilisée");
     $i0 = $g->addString('motdepasse', "Mot de passe");
     $m->addConstraintLength($i0, 6);
     $i1 = $g->addString('confirmer', "Confirmer");
     $m->addConstraintEqual($i1, $i0);
     $i = $g->addString('presentation', "Présentation");
     $m->addConstraintRequired($i);
     $this->view->model = $pm = new Wtk_Pages_Model_Form($m);
     if ($pm->validate()) {
         $data = $m->get('fiche');
         $data['adelec'] = strtolower($m->get('compte/adelec'));
         $data['password'] = Users::hashPassword($m->get('compte/adelec'), $m->get('compte/motdepasse'));
         $data['presentation'] = $m->compte->presentation;
         $db = $t->getAdapter();
         $db->beginTransaction();
         try {
             $k = $t->insert($data);
             $i = $t->findOne($k);
             $this->logger->info("Nouvelle inscription", $this->_helper->Url('valider', 'membres', null, array('adelec' => $i->adelec)));
             $this->_helper->Flash->info("Inscription en modération");
             $mail = new Strass_Mail_Inscription($i);
             try {
                 $mail->send();
             } catch (Zend_Mail_Transport_Exception $e) {
                 $this->logger->error("Échec de l'envoi de mail aux admins", null, $e);
             }
             $db->commit();
         } catch (Exception $e) {
             $db->rollBack();
             throw $e;
         }
         $this->redirectSimple('index', 'unites', null, array(), true);
     }
 }
Beispiel #2
0
 static function AuthenticateLogin($data, $settings, $marathon, $campaign, $database)
 {
     $userName = '';
     $password = '';
     $salt = '';
     $error = false;
     $errorMessage;
     $output;
     if (array_key_exists('username', $data)) {
         $userName = $data['username'];
     } else {
         if (array_key_exists(0, $data)) {
             $userName = $data[0];
         } else {
             $error = true;
             $errorMessage = 'No username was provided.';
         }
     }
     if (array_key_exists('password', $data)) {
         $password = $data['password'];
     } else {
         if (array_key_exists(1, $data)) {
             $password = $data[1];
         } else {
             $error = true;
             $errorMessage = 'No password was provided.';
         }
     }
     if (!$error) {
         $sql = 'CALL sp_return_passwordsalt (:username, :marathon_id, :campaign_id)';
         $statement = $database->prepare($sql);
         if ($statement->execute([':username' => $userName, ':marathon_id' => $marathon, ':campaign_id' => $campaign])) {
             $salt = $statement->fetchAll(PDO::FETCH_ASSOC);
             if (isset($salt[0]['salt'])) {
                 $salt = $salt[0]['salt'];
             } else {
                 $error = true;
                 $errorMessage = 'No user found with that username.';
             }
         }
     }
     if ($database instanceof ZdpArrayObject) {
         $error = true;
         $errorMessage = $database['error'];
     }
     if (!$error) {
         $sql = 'CALL sp_return_authentication (:username, :password, :marathon_id, :campaign_id)';
         $statement = $database->prepare($sql);
         if ($statement->execute([':username' => $userName, ':password' => Users::hashPassword($password, $salt), ':marathon_id' => $marathon, ':campaign_id' => $campaign])) {
             $user = $statement->fetchAll(PDO::FETCH_ASSOC);
             $_SESSION['userId'] = $user[0]['user_id'];
             $output = new ZdpArrayObject(['result' => session_id()]);
         } else {
             $output = new ZdpArrayObject(['error' => $statement->errorInfo()]);
         }
     } else {
         $output = new ZdpArrayObject(['error' => $errorMessage]);
     }
     return $output;
 }
 /**
  * Authenticates a user.
  * The example implementation makes sure if the username and password
  * are both 'demo'.
  * In practical applications, this should be changed to authenticate
  * against some persistent user identity storage (e.g. database).
  * @return boolean whether authentication succeeds.
  */
 public function authenticate()
 {
     if (preg_match('/@/', $this->username)) {
         //$this->username can filled by username or email
         $record = Users::model()->findByAttributes(array('email' => $this->username));
     } else {
         $record = Users::model()->findByAttributes(array('username' => $this->username));
     }
     if ($record === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if ($record->password !== Users::hashPassword($record->salt, $this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->_id = $record->user_id;
             $this->setState('level', $record->level_id);
             $this->setState('profile', $record->profile_id);
             $this->setState('language', $record->language_id);
             $this->email = $record->email;
             $this->setState('username', $record->username);
             $this->setState('displayname', $record->displayname);
             $this->setState('creation_date', $record->creation_date);
             $this->setState('lastlogin_date', $record->lastlogin_date);
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
 /**
  * Save the model
  * @return boolean True if the model was updated, False otherwise
  */
 function save()
 {
     # Sanitization
     if (empty($this->login)) {
         return false;
     }
     $this->modified = date('Y-m-d H:i:s');
     $this->nicename = $this->nicename ? $this->nicename : $this->email;
     $this->login = $this->login ? $this->login : $this->email;
     if (substr($this->password, 0, 4) != '$2a$') {
         $this->password = Users::hashPassword($this->password);
     }
     return parent::save();
 }
Beispiel #5
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Users();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Users'])) {
         $model->attributes = $_POST['Users'];
         $acak = $model->generateSalt();
         $model->password = $model->hashPassword($_POST['Users']['password'], $acak);
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Beispiel #6
0
 function initAdmin()
 {
     extract($this->data['admin']);
     $i = new Individu();
     $i->prenom = $prenom;
     $i->nom = $nom;
     $i->sexe = $sexe;
     $i->adelec = $adelec;
     $i->naissance = $naissance;
     $i->slug = $i->getTable()->createSlug($i->getFullname());
     $i->save();
     $u = new User();
     $u->individu = $i->id;
     $u->username = $adelec;
     $u->password = Users::hashPassword($adelec, $motdepasse);
     $u->admin = true;
     $u->save();
     Zend_Registry::set('user', $u);
 }
 /**
  * Создание админа
  */
 public function actionStep4()
 {
     $model = new Step4Form();
     if (isset($_POST['Step4Form'])) {
         $model->setAttributes($_POST['Step4Form']);
         if ($model->validate()) {
             $transaction = db()->beginTransaction();
             try {
                 db()->createCommand()->insert('{{users}}', array('login' => $model->login, 'password' => Users::hashPassword($model->password), 'email' => $model->email, 'activated' => Users::STATUS_ACTIVATED, 'referer' => Users::generateRefererCode(), 'role' => Users::ROLE_ADMIN, 'registration_ip' => userIp(), 'ls_id' => 1, 'created_at' => date('Y-m-d H:i:s')));
                 db()->createCommand()->insert('{{user_profiles}}', array('user_id' => db()->getLastInsertID(), 'balance' => 100500));
                 $transaction->commit();
                 $this->redirect(array('step5'));
             } catch (Exception $e) {
                 $transaction->rollback();
                 user()->setFlash(FlashConst::MESSAGE_ERROR, $e->getMessage());
             }
         }
     }
     $this->render('step4', array('model' => $model));
 }
 public function actionStep2($hash)
 {
     $cache = new CFileCache();
     $cache->init();
     if (($hashInfo = $cache->get($this->_cacheName . $hash)) !== FALSE) {
         $cache->delete($this->_cacheName . $hash);
         $user = db()->createCommand("SELECT COUNT(0) FROM `{{users}}` WHERE `email` = :email AND `login` = :login LIMIT 1")->bindParam('email', $hashInfo['email'], PDO::PARAM_STR)->bindParam('login', $hashInfo['login'], PDO::PARAM_STR)->queryScalar();
         if ($user) {
             $newPassword = Users::generatePassword(rand(Users::PASSWORD_MIN_LENGTH, Users::PASSWORD_MAX_LENGTH));
             // Обновляю пароль на сервере
             try {
                 $l2 = l2('ls', $hashInfo['ls_id'])->connect();
                 $encryptPassword = $l2->passwordEncrypt($newPassword);
                 $login = $hashInfo['login'];
                 $email = $hashInfo['email'];
                 $res = $l2->getDb()->createCommand("UPDATE {{accounts}} SET password = :password WHERE login = :login LIMIT 1")->bindParam('password', $encryptPassword, PDO::PARAM_STR)->bindParam('login', $login, PDO::PARAM_STR)->execute();
                 if ($res) {
                     $encryptPassword = Users::hashPassword($newPassword);
                     db()->createCommand("UPDATE {{users}} SET password = :password WHERE email = :email AND login = :login LIMIT 1")->bindParam('password', $encryptPassword, PDO::PARAM_STR)->bindParam('email', $email, PDO::PARAM_STR)->bindParam('login', $login, PDO::PARAM_STR)->execute();
                     notify()->forgottenPasswordStep2($email, array('password' => $newPassword));
                     user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'На почту указанную при регистрации отправлен новый пароль.'));
                 } else {
                     user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.'));
                 }
             } catch (Exception $e) {
                 user()->setFlash(FlashConst::MESSAGE_ERROR, $e->getMessage());
             }
         } else {
             user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Аккаунт не найден.'));
         }
     } else {
         user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Ключ для восстановления пароля не найден.'));
     }
     if (user()->hasFlash(FlashConst::MESSAGE_ERROR)) {
         $this->redirect(array('index'));
     }
     $this->redirect(array('/login/default/index'));
 }
Beispiel #9
0
 public function authenticate($credential, $password, $cookie = false)
 {
     $this->dispatch('onBeginAuthenticate', new BaseEvent($this, array($credential)));
     if (empty($credential) || empty($password)) {
         return self::ERROR_CREDENTIAL_INVALID;
     }
     $this->_identity = $credential;
     $this->_credential = $password;
     if (strpos($credential, '@') !== false) {
         $user = \Users::retrieveByEmail($credential);
     } else {
         $user = \Users::retrieveByUsername($credential);
     }
     if (!$user || empty($user) || !$user instanceof \Users) {
         return self::ERROR_UNKNOWN_IDENTITY;
     }
     if ($user instanceof \Users) {
         if ($user->password != \Users::hashPassword($password, $user->password)) {
             return self::ERROR_CREDENTIAL_INVALID;
         }
         $this->_clearCookie();
         if ($cookie) {
             $this->setCookie($user);
         }
         $this->setSession($user);
         $this->_setIsAuthenticated(true);
         $user->setLastVisitTime(new DateTime());
         $user->setLastLoginIp(Base::getApp()->getClientIp());
         $user->save();
         if ($user) {
             $this->dispatch('onAfterAuthenticate', new BaseEvent($this, $user->getAttributes()));
         }
         return $this->isAuthenticated();
     }
     return false;
 }
Beispiel #10
0
 public function setCredential($credential)
 {
     extract($this->_identity);
     $this->_credential = Users::hashPassword($username, $credential);
     return $this;
 }
$usage = "\nUsage: php {$argv[0]} <IUnderStandTheRisks>";
echo $colorCLI->warning($warning);
if ($argc != 2) {
    exit($colorCLI->error("\nWrong number of parameters{$usage}"));
} else {
    if ($argv[1] !== 1 && $argv[1] != '<IUnderStandTheRisks>' && $argv[1] != 'IUnderStandTheRisks' && $argv[1] != 'true') {
        exit($colorCLI->error("\nInvalid parameter(s){$usage}"));
    }
}
$pdo = new Settings();
$users = $pdo->query("SELECT id, username, email, password FROM users");
$update = $pdo->Prepare('UPDATE users SET password = :password WHERE id = :id');
$Users = new Users(['Settings' => $pdo]);
foreach ($users as $user) {
    if (needUpdate($user)) {
        $hash = $Users->hashPassword($user['email']);
        if ($hash !== false) {
            $update->execute([':password' => $hash, ':id' => $user['id']]);
            echo $colorCLI->primary('Updating hash for user:'******'username'];
        } else {
            echo $colorCLI->error('Error updating hash for user:'******'username'];
        }
    }
}
function needUpdate($user)
{
    global $colorCLI;
    $status = true;
    if (empty($user['email'])) {
        $status = false;
        echo $colorCLI->error('Cannot update password hash - Email is not set for user: '******'username']);
Beispiel #12
0
 * reason, it will allow the password hash on the account to be changed.
 * Hopefully that will allow admin access to fix any further problems.
 */
require_once dirname(__FILE__) . '/../../../www/config.php';
use nzedb\db\Settings;
$pdo = new Settings();
if ($argc < 3) {
    exit($pdo->log->error('Not enough parameters!' . PHP_EOL . 'Argument 1: New password.' . PHP_EOL . 'Argument 2: ID or username of the user.' . PHP_EOL));
}
$password = $argv[1];
$identifier = $argv[2];
if (is_numeric($password)) {
    exit($pdo->log->error('Password cannot be numbers only!'));
}
$field = is_numeric($identifier) ? 'id' : 'username';
$user = $pdo->queryOneRow(sprintf("SELECT id, username FROM users WHERE %s = %s", $field, is_numeric($identifier) ? $identifier : $pdo->escapeString($identifier)));
if ($user !== false) {
    $users = new Users(['Settings' => $pdo]);
    $hash = $users->hashPassword($password);
    $result = false;
    if ($hash !== false) {
        $hash = $pdo->queryExec(sprintf('UPDATE users SET password = %s WHERE id = %d', $hash, $user['id']));
    }
    if ($result === false || $hash === false) {
        echo $pdo->log->error('An error occured during update attempt.' . PHP_EOL . $pdo->errorInfo());
    } else {
        echo $pdo->log->headerOver("Updated {$user['username']}'s password hash to: ") . $pdo->log->primary("{$hash}");
    }
} else {
    echo $pdo->log->error("Unable to find {$field} '{$identifier}' in the users. Cannot change password.");
}
Beispiel #13
0
 /**
  * Change password, XHR request
  *
  * POST /user/change_pass
  * @return string
  */
 public function executeChangePass()
 {
     $current = $this->post('current_pass');
     $new = $this->post('new_pass');
     $confirm = $this->post('confirm_pass');
     $user = $this->getSessionUser();
     $error = [];
     if ($new != $confirm) {
         $error['confirm'] = t('Confirm password not match!');
     }
     if ($user->getPassword() != \Users::hashPassword($current, $user->getPassword())) {
         $error['current_pass'] = t('Current password not valid!');
     }
     $ajax = new \AjaxResponse();
     $ajax->type = \AjaxResponse::ERROR;
     if (!empty($error)) {
         $ajax->message = t('Lỗi');
         $ajax->error = $error;
         return $this->renderText($ajax->toString());
     }
     //everything ok
     $user->setPassword(\Users::hashPassword($new, $user->getPassword()));
     //reset password but keep salt
     if ($user->save(false)) {
         //quick save
         $ajax->type = \AjaxResponse::SUCCESS;
         $ajax->message = t('Password was change. Plz login again with new password!');
         CMSBackendAuth::getInstance()->logout();
     } else {
         $ajax->message = t('Something went wrong, plz try again. Thanks!');
     }
     return $this->renderText($ajax->toString());
 }
Beispiel #14
0
 function setPassword($password)
 {
     $digest = Users::hashPassword($this->username, $password);
     $this->password = $digest;
     return $this;
 }