您的位置:首页 > 编程语言 > PHP开发

yii 实现 用户验证和rbdc

2012-03-31 20:00 316 查看
添加文件 controllers/AdminController.php 加入动作index

public function actionIndex() {

$username = @$_POST['username'];
$password = @$_POST['password'];

if (@$username && @$password) {

$identity = new AdminIdentity($username, $password);
if ($identity->authenticate()){
Yii::app()->user->login($identity,3600*24*7);}
else
echo $identity->errorMessage;
}
$this->render('login');
}

//添加规则

public function accessRules()

{
return array(
array('allow',
'actions'=>array('admin','comment'),
'roles'=>array('administrator'),
),
array('deny',
'actions'=>array('comment'),
'users'=>array('*'),
),
);
}


添加 components/AdminIdentity.php 文件

class AdminIdentity extends CUserIdentity {

private $_id;

public function authenticate() {

$record = Admin::model()->findByAttributes(array('username' => $this->username));

if ($record === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if ($record->password !== $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else {
$this->_id = $record->id;
$this->setState('title', $record->title);
$this->errorCode = self::ERROR_NONE;

$auth = Yii::app()->authManager;
if (!$auth->isAssigned($record->role, $this->_id)) { {
if ($auth->assign($record->role, $this->_id)) {//给用户分配角色
Yii::app()->authManager->save(); //保存到auth.php
}
}
}
}

return !$this->errorCode;
}

public function getId() {
return $this->_id;
}

}


添加 data/auth.php 文件

<?php
return array (
'anonymous' =>
array (
'type' => 2,
'description' => 'Can only read a post',
'bizRule' => '',
'data' => '',
),
'authenticated' =>
array (
'type' => 2,
'description' => 'Can post a comment',
'bizRule' => '',
'data' => '',
),
'administrator' =>
array (
'type' => 2,
'description' => 'Can read a post and post a comment',
'bizRule' => '',
'data' => '',
'children' =>
array (
0 => 'anonymous',
1 => 'authenticated',
),
'assignments' =>
array (
1 =>
array (
'bizRule' => NULL,
'data' => NULL,
),
),
),
);
?>


修改 config/main.php 在 components 下 添加

'authManager' => array(
  'defaultRoles' => array('anonymous'), //设置默认角色
),

  'user' => array(
    'loginUrl' => array('admin/index'), //设置未登录跳转的页面
  ),

最后在view页面添加一个表单即可

<form action="" method="post">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" value="login" />

</form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: