yii 使用mysql 存储权限用户

参考链接原文有错,本文已更正

 

默认的表结构:

CREATE TABLE tbl_user (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(128) NOT NULL,
    password VARCHAR(128) NOT NULL,
    email VARCHAR(128) NOT NULL
);

 

User.php(路径 models/) 添加如下加密方法

/**
 * @return boolean validate user
 */
public function validatePassword($password, $username){
        return $this->hashPassword($password, $username) === $this->password;
}
/**
 * @return hashed value
 */

public function hashPassword($phrase, $salt = null){
        DEFINE('SALT_LENGTH', 10);
        $key = 'Gf;B&yXL|beJUf-K*PPiU{wf|@9K9j5?d+YW}?VAZOS%e2c -:11ii<}ZM?PO!96';
        if($salt == '')
                $salt = substr(hash('sha512', $key), 0, SALT_LENGTH);
        else
                $salt = substr($salt, 0, SALT_LENGTH);
        return hash('sha512', $salt . $key . $phrase);
}

 

UserController.php(路径 controllers) 更改其中的方法如下(参考链接原文中有错)

/**
 * Creates a new model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 */
public function actionCreate()
{
        $model=new User;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['User']))
        {
                $model->attributes=$_POST['User'];
                $model->password = $model->hashPassword($_POST['User']['password'], $_POST['User']['username']);
                if($model->save())
                        $this->redirect(array('view','id'=>$model->id));
                else
                        $model->password = $_POST['User']['password'];
        }

        $this->render('create',array(
                'model'=>$model,
        ));
}

 

更改"UserIdentity.php"(路径components)如下

 

public function authenticate()
{
        $username = $this->username;
        $user = User::model()->find('username=?', array($username));
        if($user === NULL)
                $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if(!$user->validatePassword($this->password, $this->username))
                $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else{
                $this->username = $user->username;
                $this->errorCode=self::ERROR_NONE;

        }
        return !$this->errorCode;
}

 

posted @ 2012-04-30 08:52  wangkangluo1  阅读(705)  评论(0编辑  收藏  举报