How to add role to user?
Asked Answered
O

5

18

We used Yii2 framework last alpha. Role for user already created but problem is how it assign to user. Documentation is absent.

Ondrea answered 23/1, 2014 at 12:39 Comment(0)
W
15

For database version of RBAC use DbManager (quote frm: Alexufo):

use yii\rbac\DbManager;
$r=new DbManager;
$r->init();
$r->createRole("admin","Administrator");
$r->save();

$r->assign('1','admin');   //1 is user id 

Example Access rules:

<?php
namespace backend\controllers;

use yii;
use yii\web\AccessControl;
use yii\web\Controller;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        //'actions' => ['login', 'error'], // Define specific actions
                        'allow' => true, // Has access
                        'roles' => ['@'], // '@' All logged in users / or your access role e.g. 'admin', 'user'
                    ],
                    [
                        'allow' => false, // Do not have access
                        'roles'=>['?'], // Guests '?'
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render( 'index' );
    }
}
?>

Don't forget to add this to your configuration file (config/main.php):

'components' => [
    'authManager'=>array(
        'class' => 'yii\rbac\DbManager',
        'defaultRoles' => ['end-user'],
    ),
    ...
]

Tables:

drop table if exists `tbl_auth_assignment`;
drop table if exists `tbl_auth_item_child`;
drop table if exists `tbl_auth_item`;

create table `tbl_auth_item`
(
   `name`                 varchar(64) not null,
   `type`                 integer not null,
   `description`          text,
   `biz_rule`              text,
   `data`                 text,
   primary key (`name`),
   key `type` (`type`)
) engine InnoDB;

create table `tbl_auth_item_child`
(
   `parent`               varchar(64) not null,
   `child`                varchar(64) not null,
   primary key (`parent`,`child`),
   foreign key (`parent`) references `tbl_auth_item` (`name`) on delete cascade on update cascade,
   foreign key (`child`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `tbl_auth_assignment`
(
   `item_name`            varchar(64) not null,
   `user_id`              varchar(64) not null,
   `biz_rule`              text,
   `data`                 text,
   primary key (`item_name`,`user_id`),
   foreign key (`item_name`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

You can also find this information in the "yii/rbac" directory (including other SQL files). For functionality and more details:

https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md

Wizened answered 7/2, 2014 at 12:12 Comment(2)
is there a way to assign roles to users via GUI instead of hard-coding ?Smithereens
Shouldn't be $r->assign('role', 'id_user') instead $r->assign('id_user', 'role')?Salient
T
7
$user_id = 1;

$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);

$auth->assign($role, $user_id);

========================================================================= if you want to select role instead creating then

$auth = new DbManager;
$auth->init();
$role = $auth->getRole('admin');
$auth->assign($role, $user_id);

100% worked!

Toscano answered 7/7, 2014 at 17:37 Comment(0)
O
3

Solved!

================ create role ============

use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор"); 
$r->save();

=============== assign ==================

$r->assign('1','admin');   //1 is user id
Ondrea answered 23/1, 2014 at 12:43 Comment(2)
On which file and in what function this coded needs to be added ?Gigi
@Gigi In any place via Yii::$app->authManager->assign('1','admin');Teodora
G
2

A really simple way to achieve an admin role is to add this to your controller:

use yii;
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['@'],
                ],
                [
                    'allow' => !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin(),
                    'actions' => ['view', 'create', 'update', 'delete'],
                ],
            ],
        ],
    ];
}

Then add to your User model an isAdmin() which returns true for your admin user(s) and false for everyone else. Personally, I use:

public function isAdmin() {
    return Self::ROLE_ADMIN === $this->role;
}

Admittedly, this is not "by the book". But it is simple, quick and effective.

Gerardogeratology answered 17/11, 2017 at 15:23 Comment(0)
S
0
$user_id = \Yii::$app->user->id;

$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);

$auth->assign($role, $user_id);
Syriac answered 30/12, 2015 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.