Yii 2 rbac

June 29, 2015

на основании yii2rbaccommonconfigmain.php

 dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'urlManager' => [
'class' => 'yiiweburlManager',
'enablePrettyUrl' => true,
],
'cache' => [
'class' => 'yiicachingFileCache',
],
'authManager' => [
'class' => 'yiirbacDbManager',
],
],

так использую постгрес. миграции не сработают. берем sql файл из
localhostyii2rbacvendoryiisoftyii2rbacmigrations

восстановление пошло не по плану. что ж создадим таблички сами

CREATE TABLE yii2.auth_rule (
name TEXT NOT NULL,
data TEXT,
created_at TIMESTAMP(0) WITHOUT TIME ZONE,
updated_at TIMESTAMP(0) WITHOUT TIME ZONE,
CONSTRAINT auth_rule_pkey PRIMARY KEY(name)
)
WITH (oids = false);

CREATE TABLE yii2.auth_item (
name TEXT NOT NULL,
type INTEGER,
description TEXT,
rule_name TEXT,
data TEXT,
created_at TIMESTAMP(0) WITHOUT TIME ZONE,
updated_at TIMESTAMP(0) WITHOUT TIME ZONE,
CONSTRAINT auth_item_pkey PRIMARY KEY(name),
CONSTRAINT auth_item_fk FOREIGN KEY (rule_name)
REFERENCES yii2.auth_rule(name)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE
)
WITH (oids = false);

CREATE TABLE yii2.auth_item_child (
parent TEXT NOT NULL,
child TEXT NOT NULL,
CONSTRAINT auth_item_child_idx PRIMARY KEY(child, parent),
CONSTRAINT auth_item_child_fk FOREIGN KEY (parent)
REFERENCES yii2.auth_item(name)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE,
CONSTRAINT auth_item_child_fk1 FOREIGN KEY (child)
REFERENCES yii2.auth_item(name)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE
)
WITH (oids = false);

CREATE TABLE yii2.auth_assignment (
item_name TEXT NOT NULL,
user_id INTEGER NOT NULL,
created_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT now()::timestamp without time zone,
CONSTRAINT auth_assignment_idx PRIMARY KEY(item_name, user_id),
CONSTRAINT auth_assignment_fk FOREIGN KEY (item_name)
REFERENCES yii2.auth_item(name)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE
)
WITH (oids = false);


подключаем модуль

composer require developeruz/yii2-db-rbac "dev-master"

можеи перейти на http://localhost/yii2rbac/backend/web/index.php//permit/access/role

для управления ролями.

у меня вышел косяк - не увидел таблицы в схеме пришлось править в
yii2rbacvendoryiisoftyii2rbacDbManager.php путь к базе

    public $db = 'db';
/**
* @var string the name of the table storing authorization items. Defaults to "auth_item".
*/
public $itemTable = 'yii2.';
/**
* @var string the name of the table storing authorization item hierarchy. Defaults to "auth_item_child".
*/
public $itemChildTable = 'yii2.';
/**
* @var string the name of the table storing authorization item assignments. Defaults to "auth_assignment".
*/
public $assignmentTable = 'yii2.';
/**
* @var string the name of the table storing rules. Defaults to "auth_rule".
*/
public $ruleTable = 'yii2.';

при создании роли получил ошибку что не может юникс время записать в таймстамп

поправил yii2rbacvendoryiisoftyii2rbacDbManager.php

    protected function addItem($item)
{
//$time = time();
$time = date("Y-m-d H:i:s");

для выпадающего списка ролей нужно создать модель


при создании базы удивило отсутствие айдишников. сейчас при создании списка это аукнулось. в auth_item создаю поле id, делаю его serial

На самом деле pg нормально отрабатывает если прописать так yii2rbaccommonconfigdb.php

 'yiidbConnection',
//'dsn' => 'mysql:host=localhost;dbname=localdb',
'dsn' => 'pgsql:host=*.ru;port=5432;dbname=DB_*',
'username' => '*',
'password' => '*',
'charset' => 'utf8',
'schemaMap' => [
'pgsql' => [
'class' => 'yiidbpgsqlSchema',
'defaultSchema' => 'yii2', //specify your schema here
]
],
'on afterOpen' => function ($event)
{
$event->sender->createCommand("SET search_path TO yii2")->execute();
}
];


пришлось снова поправить модель localhostyii2rbacbackendmodelsRole.php

    public static function tableName()
{
return Yii::$app->params['pgschema'] . '.auth_item';
}

yii2rbacbackendviewsuser_form.php

use yiihelpersArrayHelper;
use backendmodelsRole;

 

Html::activeDropDownList(
$model,
'id_role',
ArrayHelper::map(
Role::find()->all(), 'id', 'name'
)
)

получил


поправим localhostyii2rbacbackendmodelsMyUser.php

    public function beforeSave($insert)
{
if (!$this->isNewRecord)
{
$command = static::getDb()->createCommand("SELECT password_hash FROM yii2."user" where id =$this->id")->queryScalar();

if ($command != $this->password_hash)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($this->password_hash);
}
}
// $userId = Yii::$app->user->identity->id;
$userId = $this->id;
$command = static::getDb()->createCommand("SELECT name FROM yii2."auth_item" where id =$this->id_role")->queryScalar();
$userRole = Yii::$app->authManager->getRole($command);
Yii::$app->authManager->revokeAll($userId);
Yii::$app->authManager->assign($userRole, $this->id);

return parent::beforeSave($insert);
}


проверяем yii2rbacfrontendcontrollersSiteController.php

    public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup','about'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],

],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
// 'roles' => ['admin'],
],
[
'actions' => ['about'],
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],

];
}


если не админ то по /yii2rbac/frontend/web/index.php/site/about


yii2rbacbackendcontrollersUserController.php
добавим проверку прав в контролере пользователей


use yiifiltersAccessControl;

public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['delete'],
'rules' => [
[
'actions' => ['delete'],
'allow' => true,
'roles' => ['admin'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}


но думаю можно и просто убрать кнопки в yii2rbacbackendviewsuserindex.php

    user->identity->id;
$roles = array_keys(Yii::$app->authManager->getRolesByUser($userId));
if (in_array("admin", $roles))
{
$buttons = ['class' => 'yiigridActionColumn',
'template' => '{view} {update} {delete}',
// 'view'=>
];
}
else
{
$buttons = ['class' => 'yiigridActionColumn',
'template' => '{view}',
// 'view'=>
];
}
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yiigridSerialColumn'],

'id',
'username',
//'password_hash',
'id_role',
'comment:ntext',
// 'created_at',
// 'ban_date',
// 'status',
// 'auth_key:ntext',

$buttons

],
]); ?>



Source: des1roer.blogspot.com

Комментарии

comments powered by Disqus