/** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::findIdentityByEmail($this->email); } return $this->_user; }
/** * @return User $user */ private function getUser() { if (!$this->user) { $this->user = User::findIdentityByEmail($this->email); } return $this->user; }
private function createStudio($StudioForm, \app\modules\users\models\User $User) { if ($StudioForm->load(Yii::$app->request->post()) && $StudioForm->validate()) { // TODO обернуть в транзакцию $Studio = new Studio(); $Studio->type = $StudioForm->type; $Studio->name = $StudioForm->name; $User->country_id = $StudioForm->countryId; $User->city_id = $StudioForm->cityId; $Studio->currency_id = $StudioForm->currencyId; $Studio->custom_delivery = $StudioForm->custom_delivery; $Studio->custom_payment = $StudioForm->custom_payment; $Studio->slogan = $StudioForm->slogan; $Studio->description = $StudioForm->description; // Сохраним студию назначив ее пользователю $User->link('studio', $Studio); // Когда у Студии будет id (после записи), назначим связи многие ко многим // TODO попробовать сразу подать массив в link, т.к. запрос на каждую итерацию $deliveryObjects = Delivery::findAll($StudioForm->deliveryList); foreach ($deliveryObjects as $delivery) { $Studio->link('delivery', $delivery); } $paymentObjects = Payment::findAll($StudioForm->paymentList); foreach ($paymentObjects as $payment) { $Studio->link('payment', $payment); } // Назначим новую роль пользователю (atelierOwner или storeOwner) $User->assignRole($Studio->type . 'Owner'); // Рендерим страницу магазина или ателье return $this->redirect(['index']); } $StudioForm->fillCountry($User); $StudioForm->fillCity($User); return $this->render('create', ['studioForm' => $StudioForm]); }
/** * Si le formulaire est valide, on crée une clé d'identification & on expédie à l'utilisateur un mail de ré-initialisation * * @return bool */ public function processRequest() { if ($this->validate()) { try { /** @var User $user */ if (!($user = User::findIdentityByEmail($this->email))) { // CHECK_SECURITY // On ne devrait pas avoir ce cas là puisque l'existence du mail dans la base de données a été vérifiée dans lr formulaire // Il s'agit sans doute d'une tentative de piratage return false; } $user->reset_password_token = Yii::$app->getSecurity()->generateRandomString(); if (!$user->save()) { Yii::error('Erreur sur $user->save()', __METHOD__); return false; } Yii::$app->mailer->compose('/mail/askResetPassword', compact('user'))->setFrom(Yii::$app->params['adminEmail'])->setTo(h::safeRecipientEmail($user->email))->setSubject(HUsers::t('titles', 'Your password reset request'))->send(); return true; } catch (Exception $x) { Yii::error($x->getMessage(), __METHOD__); return false; } } else { return false; } }
/** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === null) { $this->_user = User::findByUsername($this->username); } return $this->_user; }
/** * Creates a new User model. * If creation is successful, the browser will be redirected to the 'view' page. * * @return mixed */ public function actionCreate() { $model = new User(['scenario' => User::SCENARIO_CREATE]); if (Yii::$app->request->isPost) { // Traitement du formulaire if (!($model->load(Yii::$app->request->post()) && $model->save())) { // On ré-affiche le formulaire avec ses erreurs Yii::$app->session->setFlash('flash-warning', HLib::t('messages', 'There are errors in your form')); } else { // Retour à la liste ou redirection sur la page d'édition, selon le bouton qui a été cliqué Yii::$app->session->setFlash('flash-success', HLib::t('messages', 'Create successful')); $requestedRedirection = Yii::$app->request->getBodyParam('action') == 'saveAndKeepEditing' ? Url::toRoute(['/users/users/update', 'id' => $model->id]) : Url::toRoute('/users/users/index'); return $this->redirect($requestedRedirection); } } // Affichage ou ré-affichage return $this->render('create', compact('model')); }
public function __construct($user_id = false) { if ($user_id) { $this->user = User::findByAttributes(['user_id' => $user_id]); } else { $this->user = Yii::$app->user->model; } $this->onedriveUserAccess = OnedriveUserAccess::findByAttributes(['user_id' => $this->user->id]); }
/** * Авторизуем пользователя. */ public function actionLogin() { // В случае если пользователь не гость, то мы перенаправляем его на главную страницу. В противном случае он бы увидел 403-ю ошибку. if (!Yii::$app->user->isGuest) { $this->goHome(); } $model = new User(['scenario' => 'login']); if ($model->load(Yii::$app->request->post())) { $user = User::findByUsername($model->login); if ($user && $user->validatePassword($model->password)) { Yii::$app->user->login($user, 3600 * 24 * 30); return $this->goBack(); } else { $model->addError('', 'Неверно введен логин или пароль'); return $this->render('login', ['model' => $model]); } } // Рендерим представление. return $this->render('login', ['model' => $model]); }
public function __construct($initUserInYiiApp = false) { $user = User::findByAttributes(['name' => 'Test', 'last_name' => 'Test']); if (!$user) { $user = new User(); $user->setAttributes(['name' => 'Test', 'last_name' => 'Test']); $user->save(); $user = User::findByAttributes(['name' => 'Test', 'last_name' => 'Test']); } $this->user = $user; if ($initUserInYiiApp) { Yii::$app->user->model = $this->user; } }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { /** @var ActiveQuery $query */ $query = User::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['like', 'password', $this->password])->andFilterWhere(['like', 'remember_token', $this->remember_token]); return $dataProvider; }
/** * Finds the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return User the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * Si on met à jour un email depuis le backend admin, il faut s'assurer que la nouvelle adresse mail sn'est pas déjà prise * * @param string $attribute the attribute currently being validated */ public function validateUpdatedEmail($attribute) { if (!$this->hasErrors()) { if ($newEmail = hArray::getValue($this->getDirtyAttributes(), 'email')) { if (User::findIdentityByEmail($newEmail)) { $this->addError($attribute, HUsers::t('messages', 'This user already exists')); } } } }
$this->title = Module::t('users', 'Users'); $this->params['subtitle'] = Module::t('users', 'Users list'); $this->params['breadcrumbs'] = [$this->title]; $gridId = 'users-grid'; $gridConfig = ['id' => $gridId, 'tableOptions' => ['class' => 'table table-bordered table-hover'], 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\CheckboxColumn'], 'id', ['attribute' => 'username', 'format' => 'html', 'value' => function ($model) { return Html::a($model['username'], ['update', 'id' => $model['id']], ['data-pjax' => 0]); }], 'email:email', ['attribute' => 'first_name', 'value' => 'profile.first_name'], ['attribute' => 'last_name', 'value' => 'profile.last_name'], ['attribute' => 'status', 'format' => 'html', 'value' => function ($model) { if ($model->status === $model::STATUS_ACTIVE) { $class = 'label-success'; } elseif ($model->status === $model::STATUS_INACTIVE) { $class = 'label-warning'; } else { $class = 'label-danger'; } return '<span class="label ' . $class . '">' . $model->getStatus() . '</span>'; }, 'filter' => Html::activeDropDownList($searchModel, 'status', User::getStatusesList(), ['class' => 'form-control', 'prompt' => Module::t('users', 'Select status')])], ['attribute' => 'role', 'filter' => Html::activeDropDownList($searchModel, 'role', User::getRolesList(), ['class' => 'form-control', 'prompt' => Module::t('users', 'Select role')])], ['attribute' => 'created_at', 'format' => 'date', 'filter' => DatePicker::widget(['model' => $searchModel, 'attribute' => 'created_at', 'options' => ['class' => 'form-control'], 'clientOptions' => ['dateFormat' => 'dd.mm.yy']])], ['attribute' => 'updated_at', 'format' => 'date', 'filter' => DatePicker::widget(['model' => $searchModel, 'attribute' => 'updated_at', 'options' => ['class' => 'form-control'], 'clientOptions' => ['dateFormat' => 'dd.mm.yy']])]]]; $boxButtons = $actions = []; $showActions = false; if (Yii::$app->user->can('BackendCreateUsers')) { $boxButtons[] = '{create}'; } if (Yii::$app->user->can('BackendUpdateUsers')) { $actions[] = '{update}'; $showActions = $showActions || true; } if (Yii::$app->user->can('BackendDeleteUsers')) { $boxButtons[] = '{batch-delete}'; $actions[] = '{delete}'; $showActions = $showActions || true; } if ($showActions === true) {
/** * Получить связанные со студией способы доставки * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); }
</div> <div class="col-sm-6"> <?php echo $form->field($user, 'password2')->passwordInput(); ?> </div> </div> <div class="row"> <div class="col-sm-6"> <?php echo $form->field($user, 'status')->dropDownList(User::getStatusesList(), ['prompt' => Module::t('users', 'Select status')]); ?> </div> <div class="col-sm-6"> <?php echo $form->field($user, 'role')->dropDownList(User::getRolesList(), ['prompt' => Module::t('users', 'Select role')]); ?> </div> </div> <div class="row"> <div class="col-sm-12"> <!-- --><?php //= $form->field($profile, 'avatar_url')->widget(Widget::className(), // [ // 'settings' => [ // 'url' => ['fileapi-upload'] // ], // 'crop' => true, // 'cropResizeWidth' => 100, // 'cropResizeHeight' => 100 // ]
/** * @return ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id'])->inverseOf('profile'); }
/** * @return \yii\db\ActiveQuery */ public function getCreator() { return $this->hasOne(User::className(), ['id' => 'creator_id']); }