mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Наведён порядок в моделях проекта
This commit is contained in:
49
api/models/authentication/ConfirmEmailForm.php
Normal file
49
api/models/authentication/ConfirmEmailForm.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\base\KeyConfirmationForm;
|
||||
use common\models\Account;
|
||||
use common\models\EmailActivation;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
|
||||
class ConfirmEmailForm extends KeyConfirmationForm {
|
||||
|
||||
public function confirm() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$confirmModel = $this->getActivationCodeModel();
|
||||
if ($confirmModel->type != EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION) {
|
||||
$confirmModel->delete();
|
||||
// TODO: вот где-то здесь нужно ещё попутно сгенерировать соответствующую ошибку
|
||||
return false;
|
||||
}
|
||||
|
||||
$transaction = Yii::$app->db->beginTransaction();
|
||||
try {
|
||||
$account = $confirmModel->account;
|
||||
$account->status = Account::STATUS_ACTIVE;
|
||||
if (!$confirmModel->delete()) {
|
||||
throw new ErrorException('Unable remove activation key.');
|
||||
}
|
||||
|
||||
if (!$account->save()) {
|
||||
throw new ErrorException('Unable activate user account.');
|
||||
}
|
||||
|
||||
$transaction->commit();
|
||||
} catch (ErrorException $e) {
|
||||
$transaction->rollBack();
|
||||
if (YII_DEBUG) {
|
||||
throw $e;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return $account->getJWT();
|
||||
}
|
||||
|
||||
}
|
122
api/models/authentication/ForgotPasswordForm.php
Normal file
122
api/models/authentication/ForgotPasswordForm.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\base\ApiForm;
|
||||
use api\traits\AccountFinder;
|
||||
use common\components\UserFriendlyRandomKey;
|
||||
use common\models\Account;
|
||||
use common\models\confirmations\ForgotPassword;
|
||||
use common\models\EmailActivation;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
class ForgotPasswordForm extends ApiForm {
|
||||
use AccountFinder;
|
||||
|
||||
public $login;
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
['login', 'required', 'message' => 'error.login_required'],
|
||||
['login', 'validateLogin'],
|
||||
['login', 'validateActivity'],
|
||||
['login', 'validateFrequency'],
|
||||
];
|
||||
}
|
||||
|
||||
public function validateLogin($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if ($this->getAccount() === null) {
|
||||
$this->addError($attribute, 'error.' . $attribute . '_not_exist');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function validateActivity($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
$account = $this->getAccount();
|
||||
if ($account->status !== Account::STATUS_ACTIVE) {
|
||||
$this->addError($attribute, 'error.account_not_activated');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function validateFrequency($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
$emailConfirmation = $this->getEmailActivation();
|
||||
if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) {
|
||||
$this->addError($attribute, 'error.email_frequency');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function forgotPassword() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$account = $this->getAccount();
|
||||
$emailActivation = $this->getEmailActivation();
|
||||
if ($emailActivation === null) {
|
||||
$emailActivation = new ForgotPassword();
|
||||
$emailActivation->account_id = $account->id;
|
||||
} else {
|
||||
$emailActivation->created_at = time();
|
||||
}
|
||||
|
||||
$emailActivation->key = UserFriendlyRandomKey::make();
|
||||
if (!$emailActivation->save()) {
|
||||
throw new ErrorException('Cannot create email activation for forgot password form');
|
||||
}
|
||||
|
||||
$this->sendMail($emailActivation);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function sendMail(EmailActivation $emailActivation) {
|
||||
/** @var \yii\swiftmailer\Mailer $mailer */
|
||||
$mailer = Yii::$app->mailer;
|
||||
$fromEmail = Yii::$app->params['fromEmail'];
|
||||
if (!$fromEmail) {
|
||||
throw new InvalidConfigException('Please specify fromEmail app in app params');
|
||||
}
|
||||
|
||||
$acceptor = $emailActivation->account;
|
||||
/** @var \yii\swiftmailer\Message $message */
|
||||
$message = $mailer->compose([
|
||||
'html' => '@app/mails/forgot-password-html',
|
||||
'text' => '@app/mails/forgot-password-text',
|
||||
], [
|
||||
'key' => $emailActivation->key,
|
||||
])
|
||||
->setTo([$acceptor->email => $acceptor->username])
|
||||
->setFrom([$fromEmail => 'Ely.by Accounts'])
|
||||
->setSubject('Ely.by Account forgot password');
|
||||
|
||||
if (!$message->send()) {
|
||||
throw new ErrorException('Unable send email with activation code.');
|
||||
}
|
||||
}
|
||||
|
||||
public function getLogin() {
|
||||
return $this->login;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return EmailActivation|null
|
||||
* @throws ErrorException
|
||||
*/
|
||||
public function getEmailActivation() {
|
||||
$account = $this->getAccount();
|
||||
if ($account === null) {
|
||||
throw new ErrorException('Account not founded');
|
||||
}
|
||||
|
||||
return $account->getEmailActivations()
|
||||
->andWhere(['type' => EmailActivation::TYPE_FORGOT_PASSWORD_KEY])
|
||||
->one();
|
||||
}
|
||||
|
||||
}
|
73
api/models/authentication/LoginForm.php
Normal file
73
api/models/authentication/LoginForm.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\base\ApiForm;
|
||||
use api\traits\AccountFinder;
|
||||
use common\models\Account;
|
||||
use Yii;
|
||||
|
||||
class LoginForm extends ApiForm {
|
||||
use AccountFinder;
|
||||
|
||||
public $login;
|
||||
public $password;
|
||||
public $rememberMe = true;
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
['login', 'required', 'message' => 'error.login_required'],
|
||||
['login', 'validateLogin'],
|
||||
|
||||
['password', 'required', 'when' => function(self $model) {
|
||||
return !$model->hasErrors();
|
||||
}, 'message' => 'error.password_required'],
|
||||
['password', 'validatePassword'],
|
||||
|
||||
['login', 'validateActivity'],
|
||||
|
||||
['rememberMe', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
public function validateLogin($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if (!$this->getAccount()) {
|
||||
$this->addError($attribute, 'error.' . $attribute . '_not_exist');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function validatePassword($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
$account = $this->getAccount();
|
||||
if (!$account || !$account->validatePassword($this->password)) {
|
||||
$this->addError($attribute, 'error.' . $attribute . '_incorrect');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function validateActivity($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
$account = $this->getAccount();
|
||||
if ($account->status !== Account::STATUS_ACTIVE) {
|
||||
$this->addError($attribute, 'error.account_not_activated');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getLogin() {
|
||||
return $this->login;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|string JWT с информацией об аккаунте
|
||||
*/
|
||||
public function login() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->getAccount()->getJWT();
|
||||
}
|
||||
|
||||
}
|
71
api/models/authentication/RecoverPasswordForm.php
Normal file
71
api/models/authentication/RecoverPasswordForm.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\base\KeyConfirmationForm;
|
||||
use common\models\EmailActivation;
|
||||
use common\validators\PasswordValidate;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
|
||||
class RecoverPasswordForm extends KeyConfirmationForm {
|
||||
|
||||
public $newPassword;
|
||||
|
||||
public $newRePassword;
|
||||
|
||||
public function rules() {
|
||||
return array_merge(parent::rules(), [
|
||||
[['newPassword', 'newRePassword'], 'required', 'message' => 'error.{attribute}_required'],
|
||||
['newPassword', PasswordValidate::class],
|
||||
['newRePassword', 'validatePasswordAndRePasswordMatch'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function validatePasswordAndRePasswordMatch($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if ($this->newPassword !== $this->newRePassword) {
|
||||
$this->addError($attribute, 'error.rePassword_does_not_match');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function recoverPassword() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$confirmModel = $this->getActivationCodeModel();
|
||||
if ($confirmModel->type !== EmailActivation::TYPE_FORGOT_PASSWORD_KEY) {
|
||||
$confirmModel->delete();
|
||||
// TODO: вот где-то здесь нужно ещё попутно сгенерировать соответствующую ошибку
|
||||
return false;
|
||||
}
|
||||
|
||||
$transaction = Yii::$app->db->beginTransaction();
|
||||
try {
|
||||
$account = $confirmModel->account;
|
||||
$account->password = $this->newPassword;
|
||||
if (!$confirmModel->delete()) {
|
||||
throw new ErrorException('Unable remove activation key.');
|
||||
}
|
||||
|
||||
if (!$account->save()) {
|
||||
throw new ErrorException('Unable activate user account.');
|
||||
}
|
||||
|
||||
$transaction->commit();
|
||||
} catch (ErrorException $e) {
|
||||
$transaction->rollBack();
|
||||
if (YII_DEBUG) {
|
||||
throw $e;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: ещё было бы неплохо уведомить пользователя о том, что его E-mail изменился
|
||||
|
||||
return $account->getJWT();
|
||||
}
|
||||
|
||||
}
|
137
api/models/authentication/RegistrationForm.php
Normal file
137
api/models/authentication/RegistrationForm.php
Normal file
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
|
||||
use api\models\base\ApiForm;
|
||||
use api\models\profile\ChangeUsernameForm;
|
||||
use common\components\UserFriendlyRandomKey;
|
||||
use common\models\Account;
|
||||
use common\models\confirmations\RegistrationConfirmation;
|
||||
use common\models\EmailActivation;
|
||||
use common\validators\LanguageValidator;
|
||||
use common\validators\PasswordValidate;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
class RegistrationForm extends ApiForm {
|
||||
|
||||
public $username;
|
||||
public $email;
|
||||
public $password;
|
||||
public $rePassword;
|
||||
public $rulesAgreement;
|
||||
public $lang;
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
[[], ReCaptchaValidator::class, 'message' => 'error.captcha_invalid', 'when' => !YII_ENV_TEST],
|
||||
['rulesAgreement', 'required', 'message' => 'error.you_must_accept_rules'],
|
||||
|
||||
['username', 'validateUsername', 'skipOnEmpty' => false],
|
||||
['email', 'validateEmail', 'skipOnEmpty' => false],
|
||||
|
||||
['password', 'required', 'message' => 'error.password_required'],
|
||||
['rePassword', 'required', 'message' => 'error.rePassword_required'],
|
||||
['password', PasswordValidate::class],
|
||||
['rePassword', 'validatePasswordAndRePasswordMatch'],
|
||||
|
||||
['lang', LanguageValidator::class],
|
||||
];
|
||||
}
|
||||
|
||||
public function validateUsername() {
|
||||
$account = new Account();
|
||||
$account->username = $this->username;
|
||||
if (!$account->validate(['username'])) {
|
||||
$this->addErrors($account->getErrors());
|
||||
}
|
||||
}
|
||||
|
||||
public function validateEmail() {
|
||||
$account = new Account();
|
||||
$account->email = $this->email;
|
||||
if (!$account->validate(['email'])) {
|
||||
$this->addErrors($account->getErrors());
|
||||
}
|
||||
}
|
||||
|
||||
public function validatePasswordAndRePasswordMatch($attribute) {
|
||||
if (!$this->hasErrors()) {
|
||||
if ($this->password !== $this->rePassword) {
|
||||
$this->addError($attribute, "error.rePassword_does_not_match");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Account|null the saved model or null if saving fails
|
||||
*/
|
||||
public function signup() {
|
||||
if (!$this->validate()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$transaction = Yii::$app->db->beginTransaction();
|
||||
try {
|
||||
$account = new Account();
|
||||
$account->uuid = Uuid::uuid4();
|
||||
$account->email = $this->email;
|
||||
$account->username = $this->username;
|
||||
$account->password = $this->password;
|
||||
$account->lang = $this->lang;
|
||||
$account->status = Account::STATUS_REGISTERED;
|
||||
if (!$account->save()) {
|
||||
throw new ErrorException('Account not created.');
|
||||
}
|
||||
|
||||
$emailActivation = new RegistrationConfirmation();
|
||||
$emailActivation->account_id = $account->id;
|
||||
$emailActivation->key = UserFriendlyRandomKey::make();
|
||||
|
||||
if (!$emailActivation->save()) {
|
||||
throw new ErrorException('Unable save email-activation model.');
|
||||
}
|
||||
|
||||
$this->sendMail($emailActivation, $account);
|
||||
|
||||
$transaction->commit();
|
||||
} catch (ErrorException $e) {
|
||||
$transaction->rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$changeUsernameForm = new ChangeUsernameForm();
|
||||
$changeUsernameForm->createTask($account->id, $account->username, null);
|
||||
|
||||
return $account;
|
||||
}
|
||||
|
||||
// TODO: подумать, чтобы вынести этот метод в какую-то отдельную конструкцию, т.к. используется и внутри NewAccountActivationForm
|
||||
public function sendMail(EmailActivation $emailActivation, Account $account) {
|
||||
/** @var \yii\swiftmailer\Mailer $mailer */
|
||||
$mailer = Yii::$app->mailer;
|
||||
$fromEmail = Yii::$app->params['fromEmail'];
|
||||
|
||||
if (!$fromEmail) {
|
||||
throw new InvalidConfigException('Please specify fromEmail app in app params');
|
||||
}
|
||||
|
||||
/** @var \yii\swiftmailer\Message $message */
|
||||
$message = $mailer->compose([
|
||||
'html' => '@app/mails/registration-confirmation-html',
|
||||
'text' => '@app/mails/registration-confirmation-text',
|
||||
], [
|
||||
'key' => $emailActivation->key,
|
||||
])
|
||||
->setTo([$account->email => $account->username])
|
||||
->setFrom([$fromEmail => 'Ely.by Accounts'])
|
||||
->setSubject('Ely.by Account registration');
|
||||
|
||||
if (!$message->send()) {
|
||||
throw new ErrorException('Unable send email with activation code.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
105
api/models/authentication/RepeatAccountActivationForm.php
Normal file
105
api/models/authentication/RepeatAccountActivationForm.php
Normal file
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
namespace api\models\authentication;
|
||||
|
||||
use api\models\base\ApiForm;
|
||||
use common\components\UserFriendlyRandomKey;
|
||||
use common\models\Account;
|
||||
use common\models\confirmations\RegistrationConfirmation;
|
||||
use common\models\EmailActivation;
|
||||
use Yii;
|
||||
use yii\base\ErrorException;
|
||||
|
||||
class RepeatAccountActivationForm extends ApiForm {
|
||||
|
||||
public $email;
|
||||
|
||||
private $emailActivation;
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
['email', 'filter', 'filter' => 'trim'],
|
||||
['email', 'required', 'message' => 'error.email_required'],
|
||||
['email', 'validateEmailForAccount'],
|
||||
['email', 'validateExistsActivation'],
|
||||
];
|
||||
}
|
||||
|
||||
public function validateEmailForAccount($attribute) {
|
||||
if (!$this->hasErrors($attribute)) {
|
||||
$account = $this->getAccount();
|
||||
if ($account === null) {
|
||||
$this->addError($attribute, "error.{$attribute}_not_found");
|
||||
} elseif ($account->status === Account::STATUS_ACTIVE) {
|
||||
$this->addError($attribute, "error.account_already_activated");
|
||||
} elseif ($account->status !== Account::STATUS_REGISTERED) {
|
||||
// TODO: такие аккаунты следует логировать за попытку к саботажу
|
||||
$this->addError($attribute, "error.account_cannot_resend_message");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function validateExistsActivation($attribute) {
|
||||
if (!$this->hasErrors($attribute)) {
|
||||
$activation = $this->getActivation();
|
||||
if ($activation !== null && !$activation->canRepeat()) {
|
||||
$this->addError($attribute, 'error.recently_sent_message');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function sendRepeatMessage() {
|
||||
if (!$this->validate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$account = $this->getAccount();
|
||||
$transaction = Yii::$app->db->beginTransaction();
|
||||
try {
|
||||
EmailActivation::deleteAll([
|
||||
'account_id' => $account->id,
|
||||
'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION,
|
||||
]);
|
||||
|
||||
$activation = new RegistrationConfirmation();
|
||||
$activation->account_id = $account->id;
|
||||
$activation->key = UserFriendlyRandomKey::make();
|
||||
if (!$activation->save()) {
|
||||
throw new ErrorException('Unable save email-activation model.');
|
||||
}
|
||||
|
||||
$regForm = new RegistrationForm();
|
||||
$regForm->sendMail($activation, $account);
|
||||
|
||||
$transaction->commit();
|
||||
} catch (ErrorException $e) {
|
||||
$transaction->rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Account|null
|
||||
*/
|
||||
public function getAccount() {
|
||||
return Account::find()
|
||||
->andWhere(['email' => $this->email])
|
||||
->one();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return EmailActivation|null
|
||||
*/
|
||||
public function getActivation() {
|
||||
if ($this->emailActivation === null) {
|
||||
$this->emailActivation = $this->getAccount()
|
||||
->getEmailActivations()
|
||||
->andWhere(['type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION])
|
||||
->one();
|
||||
}
|
||||
|
||||
return $this->emailActivation;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user