/** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate() { if (!$this->hasErrors()) { $user = new User(); $identity = $user->authenticate($this->username, $this->password); switch ($identity->errorCode) { case User::ERROR_NONE: $duration = $this->rememberMe ? Module::getInstance()->rememberMeTime : 0; Yii::$app->user->login($identity, $duration); break; case User::ERROR_EMAIL_INVALID: $this->addError("username", Module::t("Email is incorrect.")); break; case User::ERROR_USERNAME_INVALID: $this->addError("username", Module::t("Username is incorrect.")); break; case User::ERROR_STATUS_NOTACTIV: $this->addError("status", Module::t("Your account is not activated.")); break; case User::ERROR_STATUS_BAN: $this->addError("status", Module::t("Your account is blocked.")); break; case User::ERROR_PASSWORD_INVALID: $this->addError("password", Module::t("Password is incorrect.")); break; } } }
public function safeDown() { switch ($this->dbType()) { case "mysql": $this->addColumn(Module::getInstance()->tableUsers, 'createtime', "int(10) NOT NULL"); $this->addColumn(Module::getInstance()->tableUsers, 'lastvisit', "int(10) NOT NULL"); $this->execute("UPDATE " . Module::getInstance()->tableUsers . " SET createtime = UNIX_TIMESTAMP(create_at), lastvisit = UNIX_TIMESTAMP(lastvisit_at)"); $this->dropColumn(Module::getInstance()->tableUsers, 'create_at'); $this->dropColumn(Module::getInstance()->tableUsers, 'lastvisit_at'); break; case "pgsql": $this->addColumn(Module::getInstance()->tableUsers, 'createtime', "int NOT NULL default 0"); $this->addColumn(Module::getInstance()->tableUsers, 'lastvisit', "int NOT NULL default 0"); $this->execute("UPDATE " . Module::getInstance()->tableUsers . " SET createtime = extract(epoch from create_at), lastvisit = extract(epoch from lastvisit_at)"); $this->dropColumn(Module::getInstance()->tableUsers, 'create_at'); $this->dropColumn(Module::getInstance()->tableUsers, 'lastvisit_at'); break; case "sqlite": default: $this->addColumn(Module::getInstance()->tableUsers, 'createtime', "int(10)"); $this->addColumn(Module::getInstance()->tableUsers, 'lastvisit', "int(10)"); $this->execute("UPDATE " . Module::getInstance()->tableUsers . " SET createtime = strftime('%s',create_at), lastvisit = strftime('%s',lastvisit_at)"); $this->execute('ALTER TABLE "' . Module::getInstance()->tableUsers . '" RENAME TO "' . __CLASS__ . '_' . Module::getInstance()->tableUsers . '"'); $this->createTable(Module::getInstance()->tableUsers, ["id" => "pk", "username" => "varchar(20) NOT NULL", "password" => "varchar(128) NOT NULL", "email" => "varchar(128) NOT NULL", "activkey" => "varchar(128) NOT NULL", "createtime" => "int(10) NOT NULL", "lastvisit" => "int(10) NOT NULL", "superuser" => "int(1) NOT NULL", "status" => "int(1) NOT NULL"]); $this->execute('INSERT INTO "' . Module::getInstance()->tableUsers . '" SELECT "id","username","password","email","activkey","createtime","lastvisit","superuser","status" FROM "' . __CLASS__ . '_' . Module::getInstance()->tableUsers . '"'); $this->execute('DROP TABLE "' . __CLASS__ . '_' . Module::getInstance()->tableUsers . '"'); break; } }
/** * Registration user */ public function actionRegistration() { Profile::$regMode = true; $model = new RegistrationForm(); $profile = new Profile(); $module = Module::getInstance(); // ajax validator // if (Yii::$app->request->isAjax) { // if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) { // Yii::$app->response->format = Response::FORMAT_JSON; // return ActiveForm::validateMultiple([$model, $profile]); // } // } if (Yii::$app->user->id) { $this->redirect($module->profileUrl); } else { if ($model->load(Yii::$app->request->post())) { $profile->load(Yii::$app->request->post()); if ($model->validate() && $profile->validate()) { $model->activkey = Module::encrypting(microtime() . $model->password); $model->superuser = 0; $model->status = $module->activeAfterRegister ? User::STATUS_ACTIVE : User::STATUS_NOACTIVE; if ($model->save(false)) { $profile->user_id = $model->id; $profile->save(false); if ($module->sendActivationMail) { $url = Url::to(array_merge($module->activationUrl, ["activkey" => $model->activkey, "email" => $model->email]), true); $activation_url = Html::a($url, $url); Module::sendMail($model->email, Module::t("{site_name} account activation", ['site_name' => Yii::$app->name]), 'register', ['activation_url' => $activation_url]); } if (($module->loginNotActiv || $module->activeAfterRegister && $module->sendActivationMail == false) && $module->autoLogin) { Yii::$app->user->login($model); $this->redirect($module->returnUrl); } else { if (!$module->activeAfterRegister && !$module->sendActivationMail) { Yii::$app->user->setFlash('success', Module::t("Thank you for your registration. Contact Admin to activate your account.")); } elseif ($module->activeAfterRegister && $module->sendActivationMail == false) { Yii::$app->user->setFlash('success', Module::t("Thank you for your registration. Please {{login}}.", ['{{login}}' => Html::a(Module::t('Login'), $module->loginUrl)])); } elseif ($module->loginNotActiv) { Yii::$app->user->setFlash('success', Module::t("Thank you for your registration. Please check your email or login.")); } else { Yii::$app->user->setFlash('success', Module::t("Thank you for your registration. Please check your email.")); } return $this->refresh(); } } } else { $profile->validate(); } } return $this->render('/user/registration', ['model' => $model, 'profile' => $profile]); } }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * * @return \marsoltys\yii2user\models\User */ public function loadUser() { if ($this->model === null) { if (Yii::$app->user->id) { $this->model = Module::getInstance()->user(); } if ($this->model === null) { $this->redirect(Module::getInstance()->loginUrl); } } return $this->model; }
<?php echo $form->field($model, 'username'); ?> <?php echo $form->field($model, 'password')->passwordInput(); ?> <div class="form-group"> <div class="col-lg-offset-2 col-lg-11"> <?php echo Html::a(Module::t("Register"), Module::getInstance()->registrationUrl); ?> | <?php echo Html::a(Module::t("Lost Password?"), Module::getInstance()->recoveryUrl); ?> </div> </div> <?php echo $form->field($model, 'rememberMe')->checkbox(['template' => "<div class=\"col-lg-offset-2 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>"]); ?> <div class="form-group"> <div class="col-lg-offset-2 col-lg-11"> <?php echo Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']); ?> </div> </div>
/** * @return string the associated database table name */ public static function tableName() { return Module::getInstance()->tableProfileFields; }
/** * * Project: Yii2User * Date: 12/11/2015 * @author Mariusz Soltys. * @version 1.0.0 * @license http://opensource.org/licenses/MIT * */ /* @var $this \yii\web\View */ /* @var $content string */ use marsoltys\yii2user\assets\UserAssets; use marsoltys\yii2user\Module; use yii\web\View; UserAssets::register($this); $this->beginContent(Module::getInstance()->mainLayout); $this->registerJS('$(".flashes .alert").delay(3000).fadeOut("slow").slideUp("slow")', View::POS_READY, 'HideEffect'); if (!Yii::$app->request->isAjax) { $flashMessages = Yii::$app->user->getFlashes(); if ($flashMessages) { echo '<div class="flashes">'; foreach ($flashMessages as $key => $message) { echo '<div class="alert alert-' . $key . '">' . $message . "</div>\n"; } echo '</div>'; } } ?> <?php echo $content;
/** * Send emails to specified $email address * @param string $email * @param string $subject * @param string $view * @param array $params * @return bool */ public static function sendMail($email, $subject, $view, $params = []) { if (empty($params['from'])) { $params['from'] = Yii::$app->params['adminEmail']; } /** @var $mailer Mailer*/ $mailer = Yii::$app->mailer; $view = Module::getInstance()->mailViews . "/" . $view; $mailer->compose($view, $params)->setFrom($params['from'])->setTo($email)->setSubject($subject)->send(); return $mailer; }
<?php use marsoltys\yii2user\components\UHtml; use marsoltys\yii2user\models\ProfileField; use marsoltys\yii2user\Module; use yii\grid\GridView; use yii\helpers\Html; /** * @var \yii\web\View $this * @var \marsoltys\yii2user\models\UserSearch $searchModel * @var \yii\data\ActiveDataProvider $dataProvider */ $this->params['breadcrumbs'] = [['label' => Module::t('Profile Fields'), 'url' => ['admin']], Module::t('Manage')]; Module::getInstance()->setMenu([['label' => Module::t('Create Profile Field'), 'url' => ['create']], ['label' => Module::t('Manage Profile Field'), 'url' => ['/user/profile-field/admin']], ['label' => Module::t('Manage Users'), 'url' => ['/user/admin']]]); $this->registerJs("\n \$('.search-button').click(function(){\n \$('.search-form').toggle();\n return false;\n });\n \$('.search-form form').submit(function(){\n \$.fn.yiiGridView.update('profile-field-grid', {\n data: \$(this).serialize()\n });\n return false;\n });\n "); ?> <h1><?php echo Module::t('Manage Profile Fields'); ?> </h1> <p><?php echo Module::t("You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b> or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done."); ?> </p> <?php echo Html::a(Module::t('Advanced Search'), '#', ['class' => 'search-button']); ?> <div class="search-form" style="display:none"> <?php
/** * Returns User model if authenticated or false if not * @param string $username entered through login form * @param string $password entered through login form * @return User * @throws \yii\base\InvalidConfigException */ public function authenticate($username, $password) { $user = $this::find()->notsafe()->filterWhere(['or', ['username' => $username], ['email' => $username]])->one(); if (!$user) { $user->errorCode = self::ERROR_USERNAME_INVALID; } elseif (!Yii::$app->getSecurity()->validatePassword($password, $user->password)) { $user->errorCode = self::ERROR_PASSWORD_INVALID; } elseif ($user->status == self::STATUS_NOACTIVE && Module::getInstance()->loginNotActiv == false) { $user->errorCode = self::ERROR_STATUS_NOTACTIV; } elseif ($user->status == self::ERROR_STATUS_BAN) { $user->errorCode = self::ERROR_STATUS_BAN; } else { $user->errorCode = self::ERROR_NONE; } return $user; }
<?php use marsoltys\yii2user\Module; use yii\helpers\Html; use yii\widgets\ActiveForm; $this->title = Yii::$app->name . ' - ' . Module::t("Change password"); $this->params['breadcrumbs'] = [['label' => Module::t("Profile"), 'url' => ['/user/profile']], Module::t("Change password")]; $menu = [['label' => Module::t('List User'), 'url' => ['/user']], ['label' => Module::t('Profile'), 'url' => ['/user/profile']], ['label' => Module::t('Edit'), 'url' => ['/user/profile/edit']], ['label' => Module::t('Logout'), 'url' => ['/user/logout']]]; if (Module::isAdmin()) { array_unshift($menu, ['label' => Module::t('Manage Users'), 'url' => ['/user/admin']]); } Module::getInstance()->setMenu($menu); ?> <div class="change-password"> <h1><?php echo Module::t("Change password"); ?> </h1> <p class="note"><?php echo Module::t('Fields with <span class="required">*</span> are required.'); ?> </p> <div class="col-lg-4"> <?php $form = ActiveForm::begin(['id' => 'changepassword-form', 'enableAjaxValidation' => true, 'validateOnSubmit' => true, 'options' => ['class' => 'form-horizontal'], 'fieldConfig' => ['labelOptions' => ['class' => 'control-label']]]); ?>
public function behaviors() { return Module::getInstance()->getBehaviorsFor(get_class($this)); }
<?php use marsoltys\yii2user\Module; /** * @var $this yii\web\View * @var \marsoltys\yii2user\models\User $model * @var \marsoltys\yii2user\models\Profile $profile */ $this->params['breadcrumbs'] = [['label' => Module::t('Users'), 'url' => ['admin']], ['label' => $model->username, 'url' => ['view', 'id' => $model->id]], Module::t('Update')]; Module::getInstance()->addMenu(['label' => Module::t('View User'), 'url' => ['view', 'id' => $model->id]]); ?> <h1><?php echo Module::t('Update User') . " " . $model->id; ?> </h1> <?php echo $this->render('_form', ['model' => $model, 'profile' => $profile]);
<?php use marsoltys\yii2user\models\ProfileField; use marsoltys\yii2user\Module; use yii\widgets\DetailView; $this->params['breadcrumbs'] = [['label' => Module::t('Users'), 'url' => ['index']], $model->username]; Module::getInstance()->setMenu([['label' => Module::t('List User'), 'url' => ['index']]]); ?> <h1><?php echo Module::t('View User') . ' "' . $model->username . '"'; ?> </h1> <?php // For all users $attributes = ['username']; $profileFields = ProfileField::find()->forAll()->sort()->all(); if ($profileFields) { foreach ($profileFields as $field) { array_push($attributes, ['label' => Module::t($field->title), 'attribute' => $field->varname, 'value' => $field->widgetView($model->profile) ? $field->widgetView($model->profile) : ($field->range ? Profile::range($field->range, $model->profile->getAttribute($field->varname)) : $model->profile->getAttribute($field->varname))]); } } array_push($attributes, 'create_at', ['attribute' => 'lastvisit_at', 'value' => $model->lastvisit_at != '0000-00-00 00:00:00' ? $model->lastvisit_at : Module::t('Not visited')]); echo DetailView::widget(['model' => $model, 'attributes' => $attributes]);
<?php /* @var $this \yii\web\View */ use marsoltys\yii2user\assets\UserAssets; use marsoltys\yii2user\Module; use yii\bootstrap\Nav; //UserAssets::register($this); /* @var $content string */ $this->beginContent('@marsoltys/yii2user/views/layouts/main.php'); ?> <div class="row"> <div class="col-md-2"> <?php echo Nav::widget(['items' => Module::getInstance()->getMenu(), 'options' => ['class' => 'nav-pills nav-stacked']]); ?> </div> <div class="col-md-10"> <?php echo $content; ?> </div> </div> <?php $this->endContent();
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. */ public function actionUpdate() { $model = $this->loadModel(); $profile = $model->profile; $post = Yii::$app->request->post(); if ($model->load($post) && $profile->load($post)) { $validation = $this->performAjaxValidation([$model, $profile]); if ($validation !== false) { return $validation; } if ($model->validate() && $profile->save()) { $old_password = User::find()->notsafe()->findbyPk($model->id)->one(); if ($old_password->password != $model->password) { $model->password = Module::getInstance()->encrypting($model->password); $model->activkey = Yii::$app->security->generateRandomString(); } if ($model->save(true)) { return $this->redirect(['view', 'id' => $model->id]); } } } return $this->render('update', ['model' => $model, 'profile' => $profile]); }
<?php use marsoltys\yii2user\models\Profile; use marsoltys\yii2user\models\ProfileField; use marsoltys\yii2user\models\User; use marsoltys\yii2user\Module; use yii\widgets\DetailView; /** * @var \yii\web\View $this * @var \marsoltys\yii2user\models\User $model */ $this->params['breadcrumbs'] = [['label' => Module::t('Users'), 'url' => ['admin']], $model->username]; Module::getInstance()->addMenu(['label' => Module::t('Update User'), 'url' => ['update', 'id' => $model->id]], 3); Module::getInstance()->addMenu(['label' => Module::t('Delete User'), 'url' => '#', 'linkOptions' => ['submit' => ['delete', 'id' => $model->id], 'confirm' => Module::t('Are you sure to delete this item?')]], 4); $this->title = Module::t('View User') . ' "' . $model->username . '"'; ?> <h1><?php echo Module::t('View User') . ' "' . $model->username . '"'; ?> </h1> <?php $attributes = ['id', 'username']; $profileFields = ProfileField::find()->forOwner()->sort()->all(); if ($profileFields) { foreach ($profileFields as $field) { $val = ''; if ($field->widgetView($model->profile)) { $val = $field->widgetView($model->profile); } else {
/** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { $labels = ['user_id' => Module::t('User ID')]; $model = self::getFields(); foreach ($model as $field) { if (Module::getInstance()->fieldsMessage) { $l = Module::t($field->title, [], Module::getInstance()->fieldsMessage); } else { $l = Module::t($field->title); } $labels[$field->varname] = $l; } return $labels; }
<?php use marsoltys\yii2user\Module; /** * @var \yii\base\View $this * @var \marsoltys\yii2user\models\ProfileField $model */ $this->params['breadcrumbs'] = [['label' => Module::t('Profile Fields'), 'url' => ['admin']], ['label' => $model->title, 'url' => ['view', 'id' => $model->id]], Module::t('Update')]; Module::getInstance()->setMenu([['label' => Module::t('Create Profile Field'), 'url' => ['/user/profile-field/create']], ['label' => Module::t('View Profile Field'), 'url' => ['view', 'id' => $model->id]], ['label' => Module::t('Manage Profile Field'), 'url' => ['admin']], ['label' => Module::t('Manage Users'), 'url' => ['/user/admin']]]); ?> <h1><?php echo Module::t('Update Profile Field ') . $model->id; ?> </h1> <?php echo $this->render('_form', ['model' => $model]);
<?php use marsoltys\yii2user\Module; use yii\widgets\DetailView; /** @var $model \marsoltys\yii2user\models\ProfileField */ /** @var $this \yii\web\View*/ $this->params['breadcrumbs'] = [['label' => Module::t('Profile Fields'), 'url' => ['admin']], Module::t($model->title)]; Module::getInstance()->setMenu([['label' => Module::t('Create Profile Field'), 'url' => ['create']], ['label' => Module::t('Update Profile Field'), 'url' => ['update', 'id' => $model->id]], ['label' => Module::t('Delete Profile Field'), 'url' => ['delete', 'id' => $model->id], 'linkOptions' => ['data' => ['method' => 'POST', 'confirm' => Module::t('Are you sure to delete this item?')]]], ['label' => Module::t('Manage Profile Field'), 'url' => ['admin']], ['label' => Module::t('Manage Users'), 'url' => ['/user/admin']]]); ?> <h1><?php echo Module::t('View Profile Field #') . $model->varname; ?> </h1> <?php echo DetailView::widget(['model' => $model, 'attributes' => ['id', 'varname', 'title', 'field_type', 'field_size', 'field_size_min', 'required', 'match', 'range', 'error_message', 'other_validator', 'widget', 'widgetparams', 'default', 'position', 'visible']]);
public function safeDown() { $this->dropTable(Module::getInstance()->tableProfileFields); $this->dropTable(Module::getInstance()->tableProfiles); $this->dropTable(Module::getInstance()->tableUsers); }
/** * Change password */ public function actionChangepassword() { ///**@var UserChangePassword $model*/ $model = new UserChangePassword(); if (Yii::$app->user->id) { if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $new_password = User::find()->notsafe()->andWhere(['id' => Yii::$app->user->id])->one(); $new_password->password = Module::encrypting($model->password); $new_password->activkey = Module::encrypting(microtime() . $model->password); $new_password->save(); Yii::$app->user->setFlash('success', Module::t("New password has been saved.")); $this->redirect(["profile"]); } } return $this->render('changepassword', ['model' => $model]); } return $this->redirect(Module::getInstance()->loginUrl); }