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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?