SysUser.php 2.53 KB
<?php

namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use app\ht\helpers\Password;
use common\models\SysUserProfile as SysUserProfileModel;
use domain\DBHelper;

/**
 * 系统用户(后台管理用户)
 * This is the model class for table "{{%sys_user}}".
 */
class SysUser extends ActiveRecord implements IdentityInterface
{
    /**
     * @var string Plain password. Used for model validation.
     */
    public $password;

    /*
     * 后台超级管理员用户ID
     */
    const ROOT_ID = 1;

    /**
     * 获取带数据库前缀的表名
     * @return string
     */
    public static function tableNameWithDbPrefix()
    {
        $dbName = DBHelper::getDbName(self::getDb());
        return $dbName . '.sys_user';
    }

    public static function tableName()
    {
        return '{{%sys_user}}';
    }

    /** @inheritdoc */
    public function getId()
    {
        return $this->getAttribute('id');
    }

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


    /** @inheritdoc */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /** @inheritdoc */
    public function validateAuthKey($authKey)
    {
        return $this->getAttribute('auth_key') == $authKey;
    }

    /**
     * Resets password.
     *
     * @param  string $password
     * @return bool
     */
    public function resetPassword($password)
    {
        return (bool) $this->updateAttributes(['password_hash' => Password::hash($password)]);
    }

    /** @inheritdoc */
    public function beforeSave($insert)
    {
        if ($insert) {
            $this->setAttribute('auth_key', Yii::$app->security->generateRandomString());
        }

        if (!empty($this->password)) {
            $this->setAttribute('password_hash', Password::hash($this->password));
            $this->setAttribute('password', $this->password);
        }

        return parent::beforeSave($insert);
    }


    /** @inheritdoc */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /** @inheritdoc */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getProfile()
    {
        return $this->hasOne(SysUserProfileModel::className(), ['sys_user_id' => 'id']);
    }
}