accounts/api/models/authentication/ConfirmEmailForm.php

61 lines
1.8 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
2019-07-26 19:34:57 +05:30
use api\components\User\AuthenticationResult;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\models\Account;
2019-07-26 19:34:57 +05:30
use common\models\AccountSession;
use common\models\EmailActivation;
2019-07-26 19:34:57 +05:30
use Webmozart\Assert\Assert;
use Yii;
class ConfirmEmailForm extends ApiForm {
public $key;
public function rules(): array {
return [
['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION],
];
}
/**
* @CollectModelMetrics(prefix="signup.confirmEmail")
2019-07-26 19:34:57 +05:30
* @return AuthenticationResult|bool
* @throws \Throwable
*/
public function confirm() {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
/** @var \common\models\confirmations\RegistrationConfirmation $confirmModel */
$confirmModel = $this->key;
$account = $confirmModel->account;
$account->status = Account::STATUS_ACTIVE;
2019-07-26 19:34:57 +05:30
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
2019-07-26 19:34:57 +05:30
Assert::true($account->save(), 'Unable activate user account.');
$session = new AccountSession();
$session->account_id = $account->id;
$session->setIp(Yii::$app->request->userIP);
$session->generateRefreshToken();
Assert::true($session->save(), 'Cannot save account session model');
$token = Yii::$app->user->createJwtAuthenticationToken($account, $session);
$jwt = Yii::$app->user->serializeToken($token);
$transaction->commit();
2019-07-26 19:34:57 +05:30
return new AuthenticationResult($account, $jwt, $session);
}
}