public function register() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } if ($this->module->enableConfirmation == false) { $this->confirmed_at = time(); } if ($this->module->enableGeneratingPassword) { $this->password = Password::generate(8); } $this->trigger(self::USER_REGISTER_INIT); if ($this->save()) { $this->trigger(self::USER_REGISTER_DONE); if ($this->module->enableConfirmation) { $token = \Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]); $token->link('user', $this); $this->mailer->sendConfirmationMessage($this, $token); } else { \Yii::$app->user->login($this); } if ($this->module->enableGeneratingPassword) { $this->mailer->sendWelcomeMessage($this); } \Yii::$app->session->setFlash('info', $this->getFlashMessage()); \Yii::getLogger()->log('User has been registered', Logger::LEVEL_INFO); return true; } \Yii::getLogger()->log('An error occurred while registering user account', Logger::LEVEL_ERROR); return false; }
public function rules() { // Get the parent fules. $rules = parent::rules(); // Replace the password validator. $rules['passwordValidate'] = ['password', function ($attribute) { $error = Yii::t('user', 'Invalid login or password'); $user = $this->user; if ($user === null) { $this->addError($attribute, $error); return; } $validPass = false; $password = $this->password; $hash = $user->password_hash; // Try to validate hash, might throw if hash is invalid. try { $validPass = Password::validate($password, $hash); } catch (InvalidParamException $e) { // Do nothing. } // If a valid and modern hash, return now. if ($validPass) { return; } // Validate against legacy hashes. if ($this->validLegacyHash($password, $hash, $user)) { $user->resetPassword($this->password); } else { $this->addError($attribute, $error); } }]; // Return the modified rules. return $rules; }
public function safeUp() { $app = Yii::$app; $app->setModule('user', ['class' => 'dektrium\\user\\Module']); if (!isset($app->get('i18n')->translations['user*'])) { $app->get('i18n')->translations['user*'] = ['class' => \yii\i18n\PhpMessageSource::className(), 'basePath' => Yii::getAlias('@dektrium/user/migrations')]; } $controller = Yii::$app->controller; $user = new User(['scenario' => 'register']); echo $controller->ansiFormat("\n\n ==> Create Admin User\n", \yii\helpers\Console::FG_CYAN); do { if ($user->hasErrors()) { $this->showErrors($user); } // get email $email = $controller->prompt($controller->ansiFormat("\tE-mail: ", \yii\helpers\Console::FG_BLUE)); // get username $username = $controller->prompt($controller->ansiFormat("\tUsername: "******"\tPassword: "******"\n"; $affectedRows = Yii::$app->db->createCommand()->insert('{{%user}}', ['username' => (string) $username, 'email' => $email, 'password_hash' => Password::hash($password), 'confirmed_at' => new Expression('UNIX_TIMESTAMP()')])->execute(); } while ($affectedRows < 1); do { // get realname $name = $controller->prompt($controller->ansiFormat("\tFull name: ", \yii\helpers\Console::FG_BLUE)); echo "\n\n"; } while (empty($name)); $userPrimaryKey = User::findOne(['email' => $email])->primaryKey; $this->update('{{%profile}}', ['name' => $name], 'user_id=:user_id', [':user_id' => $userPrimaryKey]); $this->insert('{{%auth_assignment}}', ['item_name' => 'admin', 'user_id' => $userPrimaryKey, 'created_at' => new Expression('UNIX_TIMESTAMP()')]); }
/** @inheritdoc */ public function create() { // Create a random password, minimum length, but better than most users create. if ($this->password === null) { $this->password = Password::generate(static::$passwordLengthMin); } return parent::create(); }
/** * @inheritdoc */ public function beforeSave($insert) { if ($insert) { $this->setAttribute('auth_key', Yii::$app->getSecurity()->generateRandomKey()); } if (!empty($this->password)) { $this->setAttribute('password_hash', Password::hash($this->password)); } return parent::beforeSave($insert); }
/** @inheritdoc */ public function rules() { return ['usernameRequired' => ['username', 'required'], 'usernameTrim' => ['username', 'filter', 'filter' => 'trim'], 'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255], 'usernamePattern' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\\.@]+$/'], 'emailRequired' => ['email', 'required'], 'emailTrim' => ['email', 'filter', 'filter' => 'trim'], 'emailPattern' => ['email', 'email'], 'emailUsernameUnique' => [['email', 'username'], 'unique', 'when' => function ($model, $attribute) { return $this->user->{$attribute} != $model->{$attribute}; }, 'targetClass' => $this->module->modelMap['User']], 'newPasswordLength' => ['new_password', 'string', 'min' => 6], 'currentPasswordRequired' => ['current_password', 'required'], 'currentPasswordValidate' => ['current_password', function ($attr) { if (!Password::validate($this->{$attr}, $this->user->password_hash)) { $this->addError($attr, Yii::t('user', 'Current password is not valid')); } }]]; }
/** @inheritdoc */ public function rules() { return [[['username', 'email', 'current_password'], 'required'], [['username', 'email'], 'filter', 'filter' => 'trim'], ['username', 'match', 'pattern' => '/^[a-zA-Z]\\w+$/'], ['username', 'string', 'min' => 3, 'max' => 20], ['email', 'email'], [['email', 'username'], 'unique', 'when' => function ($model, $attribute) { return $this->user->{$attribute} != $model->{$attribute}; }, 'targetClass' => $this->module->modelMap['User']], ['new_password', 'string', 'min' => 6], ['current_password', function ($attr) { if (!Password::validate($this->{$attr}, $this->user->password_hash)) { $this->addError($attr, \Yii::t('user', 'Current password is not valid')); } }]]; }
public function testRegister() { $this->model = new RegistrationForm(); $this->model->setAttributes(['email' => '*****@*****.**', 'username' => 'foobar', 'password' => 'foobar']); /** @var User $user */ verify($this->model->register())->true(); $user = User::findOne(['email' => '*****@*****.**']); verify('$user is instance of User', $user instanceof User)->true(); verify('email is valid', $user->email)->equals($this->model->email); verify('username is valid', $user->username)->equals($this->model->username); verify('password is valid', Password::validate($this->model->password, $user->password_hash))->true(); $token = Token::findOne(['user_id' => $user->id, 'type' => Token::TYPE_CONFIRMATION]); verify($token)->notNull(); $mock = $this->getMock(RegistrationForm::className(), ['validate']); $mock->expects($this->once())->method('validate')->will($this->returnValue(false)); verify($mock->register())->false(); }
/** @inheritdoc */ public function rules() { return ['requiredFields' => [['login', 'password'], 'required'], 'loginTrim' => ['login', 'trim'], 'passwordValidate' => ['password', function ($attribute) { if ($this->user === null || !Password::validate($this->password, $this->user->password_hash)) { $this->addError($attribute, Yii::t('user', 'Invalid login or password')); } }], 'confirmationValidate' => ['login', function ($attribute) { if ($this->user !== null) { $confirmationRequired = $this->module->enableConfirmation && !$this->module->enableUnconfirmedLogin; if ($confirmationRequired && !$this->user->getIsConfirmed()) { $this->addError($attribute, Yii::t('user', 'You need to confirm your email address')); } if ($this->user->getIsBlocked()) { $this->addError($attribute, Yii::t('user', 'Your account has been blocked')); } } }], 'rememberMe' => ['rememberMe', 'boolean']]; }
/** * @param $id */ public function actionChangePassword($id) { $userInfo = Yii::$app->request->post()['settings-form']; $user = User::findIdentity($id); if (Password::validate($userInfo['current_password'], $user->password_hash)) { if ($user->resetPassword($userInfo['new_password'])) { Yii::$app->getSession()->setFlash('success', 'Contraseña cambiada con éxito'); } if ($user->username != $userInfo['username']) { $user->username = $userInfo['username']; $user->save(); Yii::$app->getSession()->setFlash('success', 'Nombre de usuario cambiado con éxito'); } } else { Yii::$app->getSession()->setFlash('danger', 'La contraseña actual no corresponde, valide e intente nuevamente'); } $this->redirect(['person/update', 'id' => Yii::$app->user->id]); }
/** * Creates a new User model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $user = Yii::createObject(['class' => User::className(), 'scenario' => 'create']); if ($user->load(Yii::$app->request->post())) { /* $coordenadas = sysconfigs::getCoordinates($user->direccion); $user->latitud = $coordenadas['latitud']; $user->longitud = $coordenadas['longitud'];*/ //generamos password $user->password = $user->password == null ? Password::generate(8) : $user->password; if ($user->save()) { $user->mailer->sendWelcomeMessage($user, null); return $this->redirect(['update', 'id' => $user->id]); } else { return $this->render('create', ['user' => $user]); } } else { return $this->render('create', ['user' => $user]); } }
/** * @inheritdoc */ public function register() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } $this->confirmed_at = $this->module->enableConfirmation ? null : time(); $this->password = $this->module->enableGeneratingPassword ? Password::generate(self::PASSWORD_MIN_LENGTH) : $this->password; $this->trigger(self::BEFORE_REGISTER); if (!$this->save()) { return false; } if ($this->module->enableConfirmation) { /** @var Token $token */ $token = Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]); $token->link('user', $this); } if ($this->module->enableConfirmation || $this->module->enableGeneratingPassword) { $this->mailer->sendWelcomeMessage($this, isset($token) ? $token : null); } $this->trigger(self::AFTER_REGISTER); return true; }
public function ldap() { $authen = false; $ua = base64_encode($_SERVER['HTTP_USER_AGENT']); $apiKey = Yii::$app->params['apiKey']; $password = base64_encode(md5($this->password)); $url = Yii::$app->params['authUrl'] . "/{$ua}/{$apiKey}/{$password}/{$this->username}/json"; $ldap = json_decode(Curl::getData($url)); if (isset($ldap->success) && $ldap->success) { $user = User::findOne(['username' => $this->username]); if (empty($user) || $user === null) { if ($this->allowAddUser) { $this->addUser($ldap); } } else { User::updateAll(['password_hash' => Password::hash($this->password)], ['username' => $this->username]); } if ($this->db()) { $authen = true; } } return $authen; }
/** @inheritdoc */ public function beforeSave($insert) { if ($insert) { $this->setAttribute('auth_key', \Yii::$app->security->generateRandomString()); if (\Yii::$app instanceof \yii\web\Application) { $this->setAttribute('registration_ip', \Yii::$app->request->userIP); } } if (!empty($this->password)) { $this->setAttribute('password_hash', Password::hash($this->password)); } return parent::beforeSave($insert); }
/** * This method is used to create new user account. If password is not set, this method will generate new 8-char * password. After saving user to database, this method uses mailer component to send credentials * (username and password) to user via email. * * @return bool */ public function create() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } //$this->RegisterDate = new Expression('NOW()'); if (empty($this->Password)) { $this->Password = Password::generate(8); } $this->Password = $this->generatePasswordHash($this->Password); $this->trigger(self::BEFORE_CREATE); if ($this->save()) { $this->trigger(self::AFTER_CREATE); //$this->mailer->sendWelcomeMessage($this); \Yii::info('Зарегистрирован пользователь №' . $this->id . ': ' . \yii\helpers\Html::a($this->getFullName(true), ['/user/admin/update', 'id' => $this->ID]), 'info'); return true; } \Yii::error('An error occurred while creating user account', self::className()); \Yii::error(VarDumper::dumpAsString($this->errors), self::className()); \Yii::error(VarDumper::dumpAsString($this->attributes), self::className()); return false; }
/** * @return string * @throws \yii\base\InvalidConfigException */ public function actionFogotPassword() { if (!\Yii::$app->user->isGuest) { $this->goHome(); } $sended = $result = false; $model = \Yii::createObject(['class' => \frontend\models\RecoveryForm::className(), 'scenario' => 'request']); $isLoaded = $model->load(Yii::$app->request->post()); if (Yii::$app->request->isPost && $isLoaded && $model->validate()) { /** @var Token $token */ $password = \dektrium\user\helpers\Password::generate(6); if ($model->user->resetPassword($password)) { $sendTo = $model->user->email; $subject = "Razzd Password Recovery"; $replyTo = isset(\Yii::$app->params['supportEmail']) ? \Yii::$app->params['supportEmail'] : ""; $subject_internal = "Your Password was changed"; $password = "******"; $username = $model->user->username; $mailer = new \common\helpers\Mandrill($sendTo, $subject, $local_tpl_name = null, $sender = null, ['from_name' => '[Auto-generated]', 'reply_to' => $replyTo, 'mandrill_template_name' => 'forgotpassword', 'vars' => ['header' => $subject_internal, 'username' => $username, 'password' => $password]]); $result = $mailer->sendWithMandrillTemplate(); } $mess = (string) $result; if ($result) { Yii::$app->session->setFlash('success', 'Your password has been changed.'); $sended = true; } else { Yii::$app->session->setFlash('error', 'There is something wrong. Contact Support.'); } } return $this->renderAjax('fogot', ['model' => $model, 'sended' => $sended]); }
/** * This method is used to register new user account. If Module::enableConfirmation is set true, this method * will generate new confirmation token and use mailer to send it to the user. * * @return bool */ public function temporary() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } $this->confirmed_at = $this->module->enableConfirmation ? null : time(); $this->password = $this->module->enableGeneratingPassword ? \dektrium\user\helpers\Password::generate(8) : $this->password; $this->trigger(self::BEFORE_REGISTER); // echo '<pre>'; print_r($this); die(); if (!$this->save()) { return false; } $this->trigger(self::AFTER_REGISTER); return true; }
public static function loginUserByName($username, $password) { $user = User::findOne(['username' => $username]); if (!$user || !Password::validate($password, $user->password_hash)) { return; } return $user; }
public function up() { $this->insert('user', ['id' => '1', 'username' => 'admin', 'email' => '*****@*****.**', 'password_hash' => Password::hash('admin'), 'auth_key' => Yii::$app->security->generateRandomString(), 'created_at' => time(), 'updated_at' => time(), 'esActivo' => '1']); $this->insert('profile', ['user_id' => '1']); $this->insert('token', ['user_id' => '1', 'code' => Yii::$app->security->generateRandomString(), 'created_at' => time(), 'type' => '0']); }