public function run() { $request = Yii::$app->request; $user = Yii::createObject($this->modelClass, ['scenario' => $this->scenario]); $profile = Yii::createObject($this->profileClass); $roles = []; if ($this->roleArray !== null) { $roles = call_user_func($this->roleArray, $this); } $roleArray = ArrayHelper::map($roles, 'name', 'description'); $statusArray = []; if ($this->statusArray !== null) { $statusArray = call_user_func($this->statusArray, $this); } if ($user->load($request->post()) && $profile->load($request->post())) { if ($user->validate() && $profile->validate()) { $user->populateRelation('profile', $profile); if ($user->save(false)) { $this->trigger('success', new Event(['data' => $user])); return $this->controller->redirect(Url::to([$this->updateRoute, 'id' => $user->id])); } else { $this->trigger('success', new Event(['data' => Module::t('admin', 'Failed create user')])); return $this->controller->refresh(); } } elseif ($request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile)); } } return $this->render(compact(['user', 'profile', 'roleArray', 'statusArray'])); }
public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->status = User::STATUS_WAIT; $user->generateAuthKey(); $user->generateEmailConfirmToken(); if ($user->save()) { $auth = Yii::$app->authManager; $userRoleDefault = $auth->getRole('user'); $auth->assign($userRoleDefault, $user->getId()); $userProfile = new Profile(); $userProfile->user_id = $user->getId(); $userProfile->user_agent = Yii::$app->request->getUserAgent(); $userProfile->user_ip = Yii::$app->request->getUserIP(); $userProfile->name = $user->username; $userProfile->avatar_id = 1; //default.png (id = 1) $userProfile->save(false); Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])->setTo($this->email)->setSubject(Module::t('app', 'EMAIL_SIGNUP_SUBJECT') . Yii::$app->name)->send(); } return $user; } return null; }
/** * Create php file for rbac directory * Set directory config common.php * section components authManager */ public function actionInit() { $auth = Yii::$app->authManager; $auth->removeAll(); //удаляем старые данные //Создадим права доступа к управлению пользователями $blog = $auth->createPermission('manageUsers'); $blog->description = Module::t('module', 'RBAC_MANAGE_USERS'); $auth->add($blog); //Включаем наш обработчик $rule = new UserRoleRule(); $auth->add($rule); //Добавляем роли $user = $auth->createRole('user'); $user->description = Module::t('module', 'USER_ROLE_USER'); $user->ruleName = $rule->name; $auth->add($user); $moder = $auth->createRole('moder'); $moder->description = Module::t('module', 'USER_ROLE_MODERATOR'); $moder->ruleName = $rule->name; $auth->add($moder); //Добавляем потомков $auth->addChild($moder, $user); $auth->addChild($moder, $blog); $admin = $auth->createRole('admin'); $admin->description = Module::t('module', 'USER_ROLE_ADMINISTRATOR'); $admin->ruleName = $rule->name; $auth->add($admin); $auth->addChild($admin, $moder); }
/** * Set info for vkontakte registration * * @author Ilya Sheershoff <*****@*****.**> * @param array $attributes * @return array [$user, $profile] */ protected function setInfoVkontakte($attributes) { /** @var \app\modules\user\models\User $user */ /** @var \app\modules\user\models\Profile $profile */ $user = $this->module->model("User"); $profile = $this->module->model("Profile"); foreach ($_SESSION as $k => $v) { if (is_object($v) && get_class($v) == "yii\\authclient\\OAuthToken") { /** @var \yii\authclient\OAuthToken $v */ $user->email = $v->getParam('email'); } } // set email/username if they are set // note: email may be missing if user signed up using a phone number if (!empty($attributes["email"])) { $user->email = $attributes["email"]; } if (!empty($attributes["first_name"]) && !empty($attributes["last_name"])) { $user->username = "******"first_name"]} {$attributes["last_name"]}"; } // use vkontakte_id name as username as fallback if (empty($attributes["email"]) && empty($attributes["username"])) { $user->username = "******"id"]}"; } $profile->full_name = "{$attributes["first_name"]} {$attributes["last_name"]}"; return [$user, $profile]; }
/** * Check if token is valid. * * @return boolean true if token is valid */ public function isValidToken() { if (SecurityHelper::isValidToken($this->token, Module::param('recoveryWithin', false)) === true) { return ($this->_user = User::findByToken($this->token, 'active')) !== null; } return false; }
/** * Validates the password. * This method serves as the inline validation for password. */ public function validateOldPassword($attribute, $params) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->{$attribute})) { $this->addError($attribute, Module::t('model', 'Invalid old password')); } }
/** * Sign Up page. * If record will be successful created, user will be redirected to home page. */ public function run() { $user = Yii::createObject($this->modelClass, ['scenario' => 'signup']); $profile = Yii::createObject($this->profileClass); $post = Yii::$app->request->post(); if ($user->load($post) && $profile->load($post)) { if ($user->validate() && $profile->validate()) { $user->populateRelation('profile', $profile); if ($user->save(false)) { if (Module::param('requireEmailConfirmation', false)) { $this->trigger('success', new Event(['data' => Module::t('model', 'Your account has been created successfully. An email has been sent to you with detailed instructions.', ['url' => Url::to($this->resendRoute)])])); } else { Yii::$app->user->login($user); $this->trigger('success', new Event(['data' => Module::t('model', 'Your account has been created successfully.')])); } return $this->controller->goHome(); } else { $this->trigger('danger', new Event(['data' => Module::t('model', 'Create account failed. Please try again later.')])); return $this->controller->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile)); } } return $this->render(compact('user', 'profile')); }
/** * Send forgot email * @return bool */ public function sendForgotEmail() { /** @var Mailer $mailer */ /** @var Message $message */ /** @var \app\modules\user\models\UserToken $userToken */ if ($this->validate()) { // get user $user = $this->getUser(); // calculate expireTime $expireTime = $this->module->resetExpireTime; $expireTime = $expireTime ? gmdate("Y-m-d H:i:s", strtotime($expireTime)) : null; // create userToken $userToken = $this->module->model("UserToken"); $userToken = $userToken::generate($user->id, $userToken::TYPE_PASSWORD_RESET, null, $expireTime); // modify view path to module views $mailer = Yii::$app->mailer; $oldViewPath = $mailer->viewPath; $mailer->viewPath = $this->module->emailViewPath; // send email $subject = Yii::$app->id . " - " . Yii::t("user", "Forgot password"); $result = $mailer->compose('forgotPassword', compact("subject", "user", "userToken"))->setTo($user->email)->setSubject($subject)->send(); // restore view path and return result $mailer->viewPath = $oldViewPath; return $result; } return false; }
public function actionCreate() { $username = $this->prompt(Module::t('console', 'Username:'******'console', 'Email:')); $password = $this->prompt(Module::t('console', 'Password:'******'console', 'First Name:')); $surname = $this->prompt(Module::t('console', 'Last Name:')); $sex = $this->confirm(Module::t('console', 'Male ?'), 1); if ($username && $email && $password) { $user = $this->insertUser($username, $email, $password); $id = $user->id; $this->stdout('Added user with:' . PHP_EOL); $this->stdout('ID:', Console::FG_GREY); $this->stdout($id . PHP_EOL, Console::FG_YELLOW); $this->stdout('Username:'******'Email:', Console::FG_GREY); $this->stdout($email . PHP_EOL, Console::FG_YELLOW); $this->stdout('Password:', Console::FG_GREY); $this->stdout($password . PHP_EOL, Console::FG_YELLOW); if ($id && $name && $surname && $sex) { $this->insertProfile($id, $name, $surname, $sex); } } }
/** * Send a recovery password token. * * @return boolean true if recovery token was successfully sent */ public function recovery() { $this->_model = User::findByEmail($this->email, 'active'); if ($this->_model !== null) { return Module::sendRecoveryEmail($this->_model); } return false; }
/** * @param string $attribute * @param array $params */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { if (!$this->_user->validatePassword($this->{$attribute})) { $this->addError($attribute, Module::t('module', 'ERROR_WRONG_CURRENT_PASSWORD')); } } }
/** * @param string $attribute * @param array $params */ public function validateIsSent($attribute, $params) { if (!$this->hasErrors() && ($user = $this->getUser())) { if (User::isPasswordResetTokenValid($user->{$attribute}, $this->_timeout)) { $this->addError($attribute, Module::t('module', 'ERROR_TOKEN_IS_SENT')); } } }
/** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, Module::t('module', 'ERROR_WRONG_LOGIN_OR_PASSWORD')); } } }
/** * Activate a new user page. * * @param string $token Activation token. * * @return mixed View */ public function run($token) { $model = Yii::createObject($this->modelClass, ['token' => $token]); if ($model->validate() && $model->activate()) { $this->trigger('success', new Event(['data' => Module::t('model', 'You successfully activated your account.')])); } else { $this->trigger('danger', new Event(['data' => Module::t('model', 'Account activation failed.')])); } return $this->controller->goHome(); }
/** * Sends an email with a link, for resetting the password. * * @return boolean whether the email was send */ public function sendEmail() { if ($user = $this->getUser()) { $user->generatePasswordResetToken(); if ($user->save()) { return Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/passwordReset'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])->setTo($this->email)->setSubject(Module::t('module', 'PASSWORD_RESET_FOR {appName}', ['appName' => Yii::$app->name]))->send(); } } return false; }
/** * Find the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return User the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { /** @var \app\modules\user\models\User $user */ $user = $this->module->model("User"); $user = $user::findOne($id); if ($user) { return $user; } throw new NotFoundHttpException('The requested page does not exist.'); }
/** * Creates a form model given a token. * * @param string $token * @param array $config * @throws \yii\base\InvalidParamException if token is empty or not valid */ public function __construct($token, $config = []) { if (empty($token) || !is_string($token)) { throw new InvalidParamException(Module::t('app', 'EMAIL_CONFIRM_CONSTRUCT_BLANK_OR_STRING_TOKEN')); } $this->_user = User::findByEmailConfirmToken($token); if (!$this->_user) { throw new InvalidParamException(Module::t('app', 'EMAIL_CONFIRM_CONSTRUCT_WRONG_TOKEN')); } parent::__construct($config); }
public function actionPassword() { $user = $this->findModel(); $model = new PasswordChangeForm($user); if ($model->load(Yii::$app->request->post()) && $model->changePassword()) { Yii::$app->getSession()->setFlash('success', Module::t('app', 'FLASH_PASSWORD_CHANGE_SUCCESS')); return $this->redirect(['index']); } else { return $this->render('password', ['model' => $model]); } }
public function actionPasswordReset() { $model = new PasswordResetForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->resetPasword()) { Yii::$app->getSession()->setFlash('success', Module::t('module', 'FLASH_PASSWORD_RESET_EMAIL')); return $this->goHome(); } else { Yii::$app->getSession()->setFlash('error', Module::t('module', 'FLASH_PASSWORD_RESET_ERROR')); } } return $this->render('passwordReset', ['model' => $model]); }
/** * Validates the username and password. * This method serves as the inline validation for password. */ public function validatePassword() { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError('password', Module::t('module', 'ERROR_WRONG_USERNAME_OR_PASSWORD')); } elseif ($user && $user->status == User::STATUS_BLOCKED) { $this->addError('username', Module::t('module', 'ERROR_PROFILE_BLOCKED')); } elseif ($user && $user->status == User::STATUS_WAIT) { $this->addError('username', Module::t('module', 'ERROR_PROFILE_NOT_CONFIRMED')); } } }
public function actionActivate($token) { try { $model = new EmailConfirmForm($token); } catch (InvalidParamException $e) { throw new BadRequestHttpException($e->getMessage()); } if ($model->confirmEmail()) { Yii::$app->getSession()->setFlash('success', Module::t('app', 'FLASH_ACTIVATE_TRUE')); } else { Yii::$app->getSession()->setFlash('error', Module::t('app', 'FLASH_ACTIVATE_FALSE')); } return $this->goHome(); }
/** * Get user based on email and/or username * @return \app\modules\user\models\User|null */ public function getUser() { // check if we need to get user if ($this->user === false) { // build query based on email and/or username login properties $user = $this->module->model("User"); $user = $user::find(); if ($this->module->loginEmail) { $user->orWhere(["email" => $this->username]); } if ($this->module->loginUsername) { $user->orWhere(["username" => $this->username]); } $this->user = $user->one(); } return $this->user; }
/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->status = User::STATUS_WAIT; $user->generateAuthKey(); $user->generateEmailConfirmToken(); if ($user->save()) { Yii::$app->mailer->compose(['text' => '@app/modules/user/mails/emailConfirm'], ['user' => $user])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($this->email)->setSubject(Module::t('module', 'EMAIL_CONFIRMATION_FOR {appName}', ['appName' => Yii::$app->name]))->send(); } return $user; } return null; }
/** * Send forgot email * @return bool */ public function sendEmail() { if (!$this->validate()) { return false; } /** @var \app\modules\user\models\UserToken $userToken */ $user = $this->getUser(); $userToken = $this->module->model("UserToken"); // calculate type based on user status if ($user->status == $user::STATUS_INACTIVE) { $type = $userToken::TYPE_EMAIL_ACTIVATE; } else { $type = $userToken::TYPE_EMAIL_CHANGE; } // generate userToken and send email confirmation $userToken = $userToken::generate($user->id, $type); return $user->sendEmailConfirmation($userToken); }
/** * Update user page. * * @param integer $id User ID * * @return mixed View */ public function actionUpdate($id) { $user = $this->findModel($id); $user->setScenario('admin-update'); $profile = $user->profile; $statusArray = User::statusLabels(); if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) { if ($user->validate() && $profile->validate()) { $user->populateRelation('profile', $profile); if (!$user->save(false)) { Yii::$app->session->setFlash('danger', Module::t('admin', 'Failed update user')); } return $this->refresh(); } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile)); } } return $this->render('update', ['user' => $user, 'profile' => $profile, 'roleArray' => [], 'statusArray' => $statusArray]); }
/** * Resend email confirmation token page. */ public function run() { $model = Yii::createObject($this->modelClass); $post = Yii::$app->request->post(); if ($model->load($post)) { if ($model->validate()) { if ($model->resend()) { $this->trigger('success', new Event(['data' => Module::t('model', 'On the specified email address was sent a letter with an activation code for new account.')])); return $this->controller->goHome(); } else { $this->trigger('danger', new Event(['data' => Module::t('model', 'Failed send email with activation code. Please try again later.')])); return $this->controller->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render(compact('model')); }
/** * Request password recovery page. */ public function run() { $model = Yii::createObject($this->modelClass); $post = Yii::$app->request->post(); if ($model->load($post)) { if ($model->validate()) { if ($model->recovery()) { $this->trigger('success', new Event(['data' => Module::t('model', 'You successfully recovered your account.')])); return $this->controller->goHome(); } else { $this->trigger('success', new Event(['data' => Module::t('model', 'Account recovery failed.')])); return $this->controller->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render(compact('model')); }
/** * Confirm password recovery request page. * * @param string $token Confirmation token * * @return mixed View */ public function run($token) { $model = Yii::createObject($this->modelClass, ['token' => $token]); if (!$model->isValidToken()) { $this->trigger('danger', new Event(['data' => Module::t('model', 'Invalid recovery code.')])); return $this->controller->goHome(); } if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if ($model->recovery()) { $this->trigger('success', new Event(['data' => Module::t('model', 'Success! Password was changed.')])); return $this->controller->goHome(); } else { $this->trigger('danger', new Event(['data' => Module::t('model', 'Failed reset password. Try again later.')])); return $this->controller->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render(compact('model')); }
/** * Reset password */ public function actionReset($token) { /** @var \app\modules\user\models\User $user */ /** @var \app\modules\user\models\UserToken $userToken */ // get user token and check expiration $userToken = $this->module->model("UserToken"); $userToken = $userToken::findByToken($token, $userToken::TYPE_PASSWORD_RESET); if (!$userToken) { return $this->render('reset', ["invalidToken" => true]); } // get user and set "reset" scenario $success = false; $user = $this->module->model("User"); $user = $user::findOne($userToken->user_id); $user->setScenario("reset"); // load post data and reset user password if ($user->load(Yii::$app->request->post()) && $user->save()) { // delete userToken and set success = true $userToken->delete(); $success = true; } return $this->render('reset', compact("user", "success")); }
public function actionPasswordReset($token) { try { $model = new PasswordResetForm($token, $this->module->passwordResetTokenExpire); } catch (InvalidParamException $e) { throw new BadRequestHttpException($e->getMessage()); } if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) { Yii::$app->getSession()->setFlash('success', Module::t('module', 'FLASH_PASSWORD_RESET_SUCCESS')); return $this->goHome(); } return $this->render('passwordReset', ['model' => $model]); }