doudou3213 2015-09-14 14:48
浏览 63
已采纳

如何轮流检查来自多个数据库表的用户身份验证?

I am using yii2 advanced template and have many user tables. For example Table_1, Table_2, Table_3. How can I make user authentication on different tables by turns? Like check Table_1: if !authenticated: check Table_2: if !authenticated: check Table_3: if !authenticated: denied?

I don't know how extend multiple User classes:

class User extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    ...

LoginForm class:

<?php
namespace common\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user = false;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 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, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

Controller:

public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }
  • 写回答

1条回答 默认 最新

  • dtds8802 2015-09-14 17:46
    关注

    Yes you can do.

    In LoginForm.php edit getUser() function as this

    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }
    
        //to check if user not found in first table then check in another
        if(!$this->_user){
            $this->_user = UserTwo::findByUsername($this->username);
        }
    
    
        //you can add more for more tables
    
    
        return $this->_user;
    }
    

    generate UserTwo.php model using Gii and change to following:

    <?php
    
    namespace app\models;
    
    use Yii;
    use yii\web\IdentityInterface;
    use yii\db\ActiveRecord;
    
    class UserTwo extends ActiveRecord implements IdentityInterface
    {
        public static function tableName()
        {
            return 'user_two';
        }
    
        public static function findIdentity($id)
        {
            return static::findOne(['id' => $id]);
        }
    
        public static function findIdentityByAccessToken($token, $type = null)
        {
            throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
        }
    
        public static function findByUsername($username)
        {
            return static::findOne(['username' => $username]);
        }
    
        public static function findByPasswordResetToken($token)
        {
            if (!static::isPasswordResetTokenValid($token)) {
                return null;
            }
    
            return static::findOne([
                'password_reset_token' => $token
            ]);
        }
    
        public static function isPasswordResetTokenValid($token)
        {
            if (empty($token)) {
                return false;
            }
            $expire = Yii::$app->params['user.passwordResetTokenExpire'];
            $parts = explode('_', $token);
            $timestamp = (int)end($parts);
            return $timestamp + $expire >= time();
        }
    
        public function getId()
        {
            return $this->getPrimaryKey();
        }
    
        public function getAuthKey()
        {
            return $this->auth_key;
        }
    
        public function validateAuthKey($authKey)
        {
            return $this->getAuthKey() === $authKey;
        }
    
        public function validatePassword($password)
        {
            return Yii::$app->security->validatePassword($password, $this->password_hash);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)