Не проходит активация аккаунта?

Модель User
spoiler
<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property integer $where_to_register
 * @property integer $role
 * @property integer $status
 * @property string $surname
 * @property string $name
 * @property string $email
 * @property string $password_hash
 * @property string $auth_key
 * @property string $secret_key
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends ActiveRecord implements IdentityInterface
{
    const ROLE_ADMIN = 1;
    const ROLE_MODER = 2;
    const ROLE_USER = 3;

    const STATUS_NOT_ACTIVE = 0;
    const STATUS_ACTIVE = 1;

    const REG_INFO_PORTAL = 1;
    const REG_SPORT_PIT = 2;
    const REG_SPORT_EQUIP = 3;

    static $roles = [
        self::ROLE_ADMIN => 'Администратор',
        self::ROLE_MODER => 'Модератор',
        self::ROLE_USER => 'Пользователь',
    ];

    public $password;
    public $repeat_password;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'surname', 'email', 'password', 'repeat_password'], 'filter', 'filter' => 'trim'],
            [['name', 'surname', 'email', 'password', 'repeat_password'], 'required'],
            [['email', 'password'], 'required'],
            ['email', 'email'],
            [['name', 'surname'], 'string', 'max' => 255],
            ['password', 'string', 'min' => 6, 'max' => 255],
            ['password', 'required', 'on' => 'create'],
            ['repeat_password', 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли не совпадают'],
            ['email', 'unique', 'message' => 'Эта почта уже зарегистрирована'],
            ['secret_key', 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'where_to_register' => Yii::t('app', 'Откуда регистрация'),
            'role' => Yii::t('app', 'Роль'),
            'status' => Yii::t('app', 'Статус'),
            'surname' => Yii::t('app', 'Фамилия'),
            'name' => Yii::t('app', 'Имя'),
            'email' => Yii::t('app', 'E-mail'),
            'password_hash' => Yii::t('app', 'Пароль'),
            'auth_key' => Yii::t('app', 'Auth Key'),
            'secret_key' => Yii::t('app', 'Секретный ключ'),
            'created_at' => Yii::t('app', 'Дата создания'),
            'updated_at' => Yii::t('app', 'Дата обновления'),
        ];
    }

    /**
     * Поведения
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className()
        ];
    }

//    public function getCabinet()
//    {
//        return $this->hasOne(Cabinet::className(), ['user_id' => 'id']);
//    }

    /**
     * Обновления Имени и Фамилии пользователя
     *
     * @return bool
     */
    public function updateUser()
    {
        $user = ($user = User::findOne(Yii::$app->user->id)) ? $user : new User();

        $user->name = $this->name;
        $user->surname = $this->surname;

        return $user->save() ? true : false;
    }

    /**
     * Поиск по почте
     */
    public static function findByEmail($email)
    {
        return static::findOne([
            'email' => $email
        ]);
    }

    /**
     * Найти по секретному ключу
     *
     * @param $key
     * @return null|static
     */
    public static function findBySecretKey($key)
    {
        if (!static::isSecretKeyExpire($key)) {
            return null;
        }
        return static::findOne([
            'secret_key' => $key,
        ]);
    }

    /**
     * Генерирования секретного ключа
     */
    public function generateSecretKey()
    {
        $this->secret_key = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Удаления секретного ключа
     */
    public function removeSecretKey()
    {
        $this->secret_key = null;
    }

    /**
     * @param $key
     * @return bool
     */
    public static function isSecretKeyExpire($key)
    {
        if (empty($key)) {
            return false;
        }
        $expire = Yii::$app->params['secretKeyExpire'];
        $parts = explode('_', $key);
        $timestamp = (int)end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @param $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     *
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
        $this->save();
    }

    /**
     * Валидация пароля
     *
     * @param $password
     * @return bool
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Нахождения идентичности
     *
     * @param $id
     * @return static
     */
    public static function findIdentity($id)
    {
        return static::findOne([
            'id' => $id,
            'status' => self::STATUS_ACTIVE
        ]);
    }

    /**
     * Нахождения идентичности по доступному токену
     *
     * @param $token
     * @param null $type
     * @return static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * Получения id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @param $authKey
     * @return bool
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }

    /*---------------------------------------------------*/

    /**
     * Получения роля юзера по id
     * @return bool|mixed
     */
    public static function getUserRoleById()
    {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        return null !== ($user = self::findOne(['id' => Yii::$app->user->id])) ? $user->role : false;
    }

    /**
     * Получения имени по роли юзера
     *
     * @return mixed
     */
    public static function getNameRoleUser()
    {
        $role = self::findOne(['id' => Yii::$app->user->id])->role;
        return self::$roles[$role];
    }

}


frontend/UserController
spoiler
public function actionActivateAccount($key)
    {
        try {
            $user = new AccountActivation($key);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($user->activateAccount()) {
            Yii::$app->session->setFlash('success', 'Активация прошла успешно!');
        } else {
            Yii::$app->session->setFlash('error', 'Ошибка активации!');
            Yii::error('Ошибка при активации.');
        }

        return $this->redirect(Url::to(['user/sign-in']));
    }


Модель Signup
spoiler
public function reg()
    {
        $user = new User();
        $user->name = $this->name;
        $user->surname = $this->surname;
        $user->role = User::ROLE_USER;
        $user->email = $this->email;
        $user->status = $this->status;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        if ($this->scenario == 'emailActivation')
            $user->generateSecretKey();
        return $user->save(false) ? $user : null;
    }


AccountActivation
spoiler
namespace common\models;

use Yii;
use yii\base\InvalidParamException;
use yii\base\Model;

/**
 * @property string name
 */
class AccountActivation extends Model
{
    /**
     * @var $user \common\models\User
     */

    private $_user;

    public function __construct($key, $config = [])
    {
        if (empty($key) || !is_string($key))
            throw new InvalidParamException('Ключ не может быть пустым!');
        $this->_user = User::findBySecretKey($key);
        if (!$this->_user)
            throw new InvalidParamException('Не верный ключ!');
        parent::__construct($config);
    }

    /**
     * Активация аккаунта
     *
     * @return bool
     */
    public function activateAccount()
    {
        $user = $this->_user;
        $user->status = User::STATUS_ACTIVE;
        $user->removeSecretKey();
        return $user->save();
    }

  • Вопрос задан
  • 141 просмотр
Решения вопроса 1
Скорее всего не проходит валидация при сохранеии юзера, возвращается ложь, что флэшит сообщение об ошибке
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы