/** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::find()->published()->andWhere(['or', ['username' => $this->username], ['email' => $this->username]])->one(); } return $this->_user; }
public function down() { if ($user = User::find()->where(['username' => 'admin'])->one()) { /** @var $user User */ $user->delete(); echo 'User "' . $user->username . '" deleted.'; } }
/** * Creates data provider instance with search query applied * @param array $params * @param bool $trashed * @return ActiveDataProvider */ public function search($params, $trashed = false) { $query = User::find(); if ($trashed) { $query->trashed(); } else { $query->published(); } $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['updated_at' => SORT_DESC]]]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'deleted_at' => $this->deleted_at, 'last_visit_at' => $this->last_visit_at, 'login_ip' => $this->login_ip]); $query->andFilterWhere(['like', 'username', $this->username])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['like', 'password_hash', $this->password_hash])->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])->andFilterWhere(['like', 'auth_key', $this->auth_key]); if (count($this->getRoles())) { /** @var \yii\rbac\DbManager $auth */ $auth = Yii::$app->authManager; $query->leftJoin($auth->assignmentTable . ' roles', 'roles.user_id=id'); $query->andWhere(['roles.item_name' => $this->getRoles()]); } return $dataProvider; }
/** * @param $client \yii\authclient\BaseClient * @throws \yii\db\Exception */ public function onAuthSuccess($client) { $attributes = $client->getUserAttributes(); /* @var $auth UserAuthClient */ $auth = UserAuthClient::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // авторизация $user = $auth->user; Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && User::find()->where(['email' => $attributes['email']])->exists()) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Пользователь с такой электронной почтой как в {client} уже существует, но с ним не связан. Для начала войдите на сайт использую электронную почту, для того, что бы связать её.", ['client' => $client->getTitle()])]); } else { $password = Yii::$app->security->generateRandomString(6); $user = new User(['username' => $attributes['login'], 'email' => $attributes['email'], 'password' => $password]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new UserAuthClient(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user); } else { print_r($auth->getErrors()); } } else { print_r($user->getErrors()); } } } } else { // Пользователь уже зарегистрирован if (!$auth) { // добавляем внешний сервис аутентификации $auth = new UserAuthClient(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]); $auth->save(); } } }
/** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); }
/** * @return User */ public function getUser() { return self::hasOne(User::className(), ['id' => 'created_by']); }
public function getOwner() { return $this->hasOne(User::className(), ['id' => 'created_by']); }
/** * 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 ForbiddenHttpException * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { /** @var $model User */ if (($model = User::findOne($id)) !== null) { // проверка на суперадминство if ($model->getIsSuperAdmin() && $model->id != Yii::$app->user->id) { throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.')); } // проверка на право админить данного пользователя if (!Yii::$app->user->can('administrateUser', ['user' => $model])) { throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.')); } return $model; } else { throw new NotFoundHttpException(Yii::t('gromver.platform', 'The requested page does not exist.')); } }
/** * 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(Yii::t('gromver.platform', 'The requested page does not exist.')); } }
<div class="user-form"> <?php $form = ActiveForm::begin(['layout' => 'horizontal']); ?> <?php echo $form->field($model, 'username')->textInput(['maxlength' => 64, 'disabled' => $model->scenario !== $model::SCENARIO_CREATE ? true : false, 'autocomplete' => 'off']); ?> <?php echo $form->field($model, 'email')->textInput(['maxlength' => 128, 'disabled' => $model->scenario !== $model::SCENARIO_CREATE ? true : false, 'autocomplete' => 'off']); ?> <?php echo $form->field($model, 'status')->dropDownList(\gromver\platform\core\modules\user\models\User::statusLabels()); ?> <?php echo $form->field($model, 'password')->passwordInput(['autocomplete' => 'off']); ?> <?php echo $form->field($model, 'passwordConfirm')->passwordInput(['autocomplete' => 'off']); ?> <?php echo $form->field($model, 'roles')->listBox(\yii\helpers\ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'name'), ['multiple' => 'multiple']); ?> <div>
</div> <?php /*// echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a(Yii::t('gromver.platform', 'Create {modelClass}', [ 'modelClass' => 'User', ]), ['create'], ['class' => 'btn btn-success']) ?> </p>*/ ?> <?php echo GridView::widget(['id' => 'table-grid', 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'pjax' => true, 'pjaxSettings' => ['neverTimeout' => true], 'columns' => [['class' => '\\kartik\\grid\\CheckboxColumn'], ['attribute' => 'id', 'hAlign' => GridView::ALIGN_CENTER, 'vAlign' => GridView::ALIGN_MIDDLE, 'width' => '60px'], ['attribute' => 'username', 'vAlign' => GridView::ALIGN_MIDDLE], ['attribute' => 'email', 'vAlign' => GridView::ALIGN_MIDDLE, 'format' => 'email'], ['attribute' => 'status', 'vAlign' => GridView::ALIGN_MIDDLE, 'value' => function ($model) { /** @var User $model */ return $model->getStatusLabel(); }, 'filter' => User::statusLabels()], ['attribute' => 'roles', 'vAlign' => GridView::ALIGN_MIDDLE, 'value' => function ($model) { /** @var User $model */ return implode(', ', $model->isSuperAdmin ? array_merge([Html::tag('span', Yii::t('gromver.platform', 'Super Administrator'), ['class' => 'text-muted'])], $model->roles) : $model->roles); }, 'format' => 'html', 'filter' => \yii\helpers\ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'name')], ['attribute' => 'login_ip', 'hAlign' => GridView::ALIGN_CENTER, 'vAlign' => GridView::ALIGN_MIDDLE, 'value' => function ($model) { /** @var User $model */ return long2ip($model->login_ip); }, 'width' => '100px'], ['class' => 'kartik\\grid\\ActionColumn', 'width' => '100px', 'template' => '{login} {params} {view} {update} {trash}', 'buttons' => ['params' => function ($url, $model, $key) { /** @var User $model */ return Html::a('<i class="glyphicon glyphicon-th-list"></i>', ['backend/param/index', 'user_id' => $model->id], ['title' => Yii::t('gromver.platform', 'Params'), 'data-pjax' => 0]); }, 'login' => function ($url, $model, $key) { /** @var User $model */ return Yii::$app->user->can('administrate') ? Html::a('<i class="glyphicon glyphicon-log-in"></i>', ['login-as', 'id' => $model->id], ['title' => Yii::t('gromver.platform', 'Login as {user}', ['user' => $model->username]), 'data-method' => 'post', 'data-confirm' => Yii::t('gromver.platform', 'Are you sure want to login as {user}?', ['user' => $model->username])]) : ''; }, 'trash' => function ($url, $model, $key) { /** @var User $model */ return Html::a('<i class="glyphicon glyphicon-trash"></i>', ['trash', 'id' => $model->id], ['title' => Yii::t('gromver.platform', 'Delete User'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'delete', 'data-pjax' => 0]); }]]], 'responsive' => true, 'hover' => true, 'condensed' => true, 'floatHeader' => true, 'bordered' => false, 'panel' => ['heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-th-list"></i> ' . Html::encode($this->title) . ' </h3>', 'type' => 'info', 'before' => Html::a('<i class="glyphicon glyphicon-plus"></i> ' . Yii::t('gromver.platform', 'Add'), ['create'], ['class' => 'btn btn-success', 'data-pjax' => 0]) . ' ' . Html::a('<i class="glyphicon glyphicon-trash"></i> ' . Yii::t('gromver.platform', 'Trash'), ['index-trash'], ['class' => 'btn btn-default', 'data-pjax' => 0]), 'after' => Html::a('<i class="glyphicon glyphicon-trash"></i> ' . Yii::t('gromver.platform', 'Delete'), ['bulk-trash'], ['class' => 'btn btn-danger', 'data-pjax' => '0', 'onclick' => 'processAction(this); return false']) . ' ' . Html::a('<i class="glyphicon glyphicon-repeat"></i> ' . Yii::t('gromver.platform', 'Reset List'), ['index'], ['class' => 'btn btn-info']), 'showFooter' => false]]);
private function sendPasswordResetEmail($email) { /** @var User $user */ $user = User::findOne(['status' => User::STATUS_ACTIVE, 'email' => $email]); if (!$user) { return false; } //$user->password_reset_token = Yii::$app->security->generateRandomString(); $user->generatePasswordResetToken(); if ($user->save(false)) { /** @var \gromver\platform\core\modules\auth\Module $authModule */ $authModule = $this->module; $mailer = Instance::ensure($authModule->mailer, BaseMailer::className()); return $mailer->compose($authModule->emailLayoutPasswordResetToken, ['user' => $user])->setFrom(Yii::$app->supportEmail)->setTo($user->email)->setSubject(Yii::t('gromver.platform', 'Password reset for {name}.', ['name' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']]))->send(); } return false; }