Есть таблица в базе данных пользователей с полем ролей administrator, moderator, user, guest.
В каком файле прописывать class WebUser из раздела рецепты RBAC и описание ролей?
Я делаю action login на первой странице своего проекта (файл login.php в views):
Код: Выделить всё
<?=CHtml::form(); ?>
<?=CHtml::errorSummary($form); ?><br>
<table id="form2" border="0" width="400" cellpadding="10" cellspacing="10">
<tr>
<td width="150"><?=CHtml::activeLabel($form, 'username'); ?></td>
<td><?=CHtml::activeTextField($form, 'username') ?></td>
</tr>
<tr>
<td><?=CHtml::activeLabel($form, 'password'); ?></td>
<td><?=CHtml::activePasswordField($form, 'password') ?></td>
<tr>
<tr>
<td></td>
<td><?=CHtml::submitButton('Enter', array('id' => "submit")); ?></td>
</tr>
</table>
<?=CHtml::endForm(); ?>
Код: Выделить всё
<?php
class BaseController extends CController {
public $defaultAction='login';
function init(){
// Для гостей у нас и так роль по умолчанию guest.
if(!Yii::app()->user->isGuest){
// Связываем роль, заданную в БД с идентификатором пользователя,
// возвращаемым UserIdentity.getId().
Yii::app()->authManager->assign(Yii::app()->user->role, Yii::app()->user->id);
}
}
public function actionLogin()
{
$form = new WebUser();
if (!Yii::app()->user->isGuest) {
throw new CException('Vi zaregestrirovanni!');
} else {
if (!empty($_POST['WebUser'])) {
$form->attributes = $_POST['WebUser'];
if($form->validate('login')) {
$this->redirect(array('show'));
}
}
$this->render('login', array('form' => $form));
}
}
public function actionShow()
{
if(Yii::app()->user->checkAccess('administrator')){
echo "hello, I'm administrator";
}
}
}
Код: Выделить всё
<?php
class WebUser extends CWebUser {
private $_model = null;
function getRole() {
if($user = $this->getModel()){
// в таблице User есть поле role
return $user->role;
}
}
private function getModel(){
if($this->_model === null){
$this->_model = User::model()->findByPk($this->id);
}
return $this->_model;
}
public function rules()
{
return array(
array('username, password', 'required'),
array('password', 'authenticate', 'on' => 'login'),
);
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$identity= new UserIdentity($this->username, $this->password);
$identity->authenticate();
switch($identity->errorCode)
{
case UserIdentity::ERROR_NONE: {
Yii::app()->user->login($identity, 0);
break;
}
case UserIdentity::ERROR_USERNAME_INVALID: {
$this->addError('username','!');
break;
}
case UserIdentity::ERROR_PASSWORD_INVALID: {
$this->addError('password','!!');
break;
}
}
}
}
}