添加文件 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>