限制用户使用自己的数据


Restricting user to their own data

在我开发的网站上,我面临着限制用户使用自己数据的问题。

目前,所有用户都可以访问所有其他用户的数据。

我在网上找到了这个片段:

public function defaultScope() {
        return array(
            'condition' => 'mob_num = '.YII::app()->user->getId(), // Customer can see only his orders
        );
    }

当我的列是整数时,这很好,但如果它是字符串,它会给我以下错误:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause'. The SQL statement executed was: SELECT COUNT(*) FROM `mob_reg` `t` WHERE name = shayan 
public function authenticate()
    {
        /*$users=array(
            // username => password
            'demo'=>'demo',
            'admin'=>'admin',
        );*/
          //  $users= Auth::model()->findByPk("8951821861");
            $users = Auth::model()->findByAttributes(array('company'=>$this->username)); 
            if($users == NULL)
                $this->errorCode=self::ERROR_USERNAME_INVALID;
            else if ($users->name != $this->username)
                $this->errorCode=self::ERROR_USERNAME_INVALID;
            else if ($users->company != $this->password)
                $this->errorCode=self::ERROR_PASSWORD_INVALID;
            else if($users->company=='naga')
            {
                $this->errorCode=self::ERROR_NONE;
                $this->setState('roles', 'super');
                 $this->id=$users->company;
            }
            else {
                 $this->errorCode=self::ERROR_NONE;
                $this->setState('roles', 'normal');
                 $this->id=$users->company;
            }
            return !$this->errorCode;
    /*  if(!isset($users[$this->username]))
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        elseif($users[$this->username]!==$this->password)
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
            $this->errorCode=self::ERROR_NONE;
        return !$this->errorCode;*/
    }
        public function getid()
        {
            return $this->id;
        }

首先,我不会使用defaultScope,因为这会阻止您以后可能想要添加的其他用例,比如计算与当前用户有某种关系的其他人的统计信息,例如我最常打电话给谁等。

所以我认为,每当你查找数据时,你应该添加额外的限制,比如:

$orders = Orders::model()->findByAttributes(array('name' => user()->getid()));

如果你真的想坚持使用defaultScope,你需要正确地引用名称,使用参数是最好的方法:

public function defaultScope()
{
    return array(
        'condition' => "name=?",
        'params' => array(user()->getid()),
    );
}

当然,您不希望用户名存储在订单表中,但这是另一回事。