1. 问答
  2. 问答详情

YII的登陆实现与验证

1个回答

0

采纳

登录用到两个方法 authenticate和login 前者处理验证 后者负责将用户信息存到session中

主要修改的是验证方法,在/protected/components/UserIdentify类中;验证模型类是/protected/models/LoginForm;

类继承链为UserIdentity--CUserIdentity--CBaseUserIdentity-->IUserIdentity)一起使用来实现实际的验证算法

class UserIdentity extends CUserIdentity
{
   private $id;
   public function authenticate()
   {
       $record = User::model()->findByAttributes(array('username' => $this->username));
       if ($record === null)
           $this->errorCode = self::ERROR_USERNAME_INVALID;
           elseif ($record->password !== crypt($this->password, $record->password))
               $this->errorCode = self::ERROR_PASSWORD_INVALID;
           else {
       $this->id = $record->id;
       $this->setState('title', $record->title);
       $this->errorCode = self::ERROR_NONE;
           }
           return !$this->errorCode;
       }
   public function getId()
   {
       return $this->id;
   }

}

authenticate()方法中,先根据用户名查找用户是否存在,然后进行密码的Hash值比对(把具体算法放入User模型的业务逻辑中) ,用户名和密码Hash值比对成功后,设置私有变量id(最终通过属性方法getId()暴露该值),使用继承自CUserIdentity的属性errorCode,方法setState()。

身份验证类的实例最终是传递给user组件的login方法的,任何通过调用CBaseUserIdentity::setState()保存的状态信息都将传递给CWebUser,而CWebUser将这些信息存放到持久存储内(如session),之后这些信息就可以类似CWebUser的属性一样被访问。例如,上面的例子中调用了$this->setState('title', $record->title),登录成功后,就可以用Yii::app()->user->title来获取该信息。

撰写答案

验证码
点击刷新