Display data in gridview base on rbac role in yii2 - php

How to display records in gridview in yii2 using rule created for roles, in RBAC ?
Suppose, there is two roles "admin" and "agent".
Now the requirement is;
In grid for agent, display only client which is assigned to that
agent.
For admin, grid will show all client list.

Here the example I am using this in my code
// User.php -> Model
public function getUserRolesAsArray($userId)
{
$roles = Yii::$app->authManager->getRolesByUser($userId);
if (!empty($roles)) {
foreach ($roles as $role) {
$userRole[] = $role->name;
}
return $userRole;
}
}
// view.php -> view file
[
'label' => 'Role',
'value' => $model->getUserRoles($model->id) ?? null,
],
Kindly try this i think this may be help you

It is done,
I have to create a permissions that will given to role, and based on that permission, DataProvider query is modified

Related

Laravel Spatie permissions best way to add multiple roles to check against user roles for multiple models

I'm working inside a Laravel 10 project that uses the Laravel Spatie Permissions package v5.9.1. My Laravel project is used as an API that outputs stuff to a Nuxt JS front-end, including a menu.
Super admins of my platform can create a menu, and assign menu items to it, each menu item also has a potential of being a nested menu item, this equates to having two models:
Menu
MenuItem
Ideally, I don't want to have multiple menus with potentially hundreds, if not thousands of menu items, I ideally want to check that a user's role means that they have access to view a particular menu item.
How might I do this?
Here's my current database tables of menus and menu_items
My menu is brought via a slug to my page via:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'slug' => 'required|exists:menus,slug',
]);
if ($validator->fails()) {
return new ApiValidationErrorResponse($validator->messages());
}
$menu = MenuItem::tree()
->whereRelation('menu', 'slug', $request->input('slug'))
->where('is_enabled', true)
->orderBy('display_order', 'asc')
->get()
->toTree();
if (! $menu || count($menu) <= 0) {
return new ApiSuccessResponse(null, [
'message' => 'No menu found for your company.',
], 404);
}
return new ApiSuccessResponse($menu);
}

Trying to display a user with the specific role in cakephp 2x

I am trying to display table Users, and I want it to display the user with the role "Moderator" only.
public function moderators() {
$this->set('users', $this->paginate());
$this->User->find('all', array(
'conditions' => array('User.role' => 'moderator')
));
This is my controller, and it seems that it is still displaying all data in my table.
Try to use custom query for that:
$this->User->query("select * from users where role = 'moderator';");

Yii2 ManyToMany relation - Get Client window's data

I have a small (no, not that small) probleme in my current project. Today I came across with Yii and viaTable but something is not working with it. I think something is wrong with the table linking.
My goal would be to get all the data from the client windows(Ablak)
that is connected to a user via felhasznalo2ablak table.
I have 3 tables. Felhasznalo(Users in English), Ablak(Client Window in English) and Felhasznalo2Ablak which is the via table.
Here are the table structures:
Felhasznalo(Model):
public function getWindows() {
return $this->hasMany(Ablak::className(), ['id' => 'ablak_id'])- >viaTable('felhasznalo2ablak',['felhasznalo_id','id']);
}
Ablak(Model):
public function getUsers() {
return $this->hasMany(Felhasznalo::className(), ['id' => 'felhasznalo_id'])->viaTable('felhasznalo2ablak', ['ablak_id' => 'id']);
}
And the query in the controller:
$u = Felhasznalo::findOne(Yii::$app->user->getId());
$allowedWindows = $u->getWindows();
foreach ($allowedWindows as $aw) {
print_r($aw);
}
I want to get the ralational data from Ablak table that blongs to a specific user. It works but not tha way it should. Any ideas guys?
Thank you for your answers!
Gábor
Check the link in your Felhasznalo::getWindows()
public function getWindows() {
return $this
->hasMany(Ablak::className(), ['id' => 'ablak_id'])
->viaTable('felhasznalo2ablak', ['felhasznalo_id' => 'id']);
}
Query for all "Windows"
$u = Felhasznalo::findOne(Yii::$app->user->getId());
$allowedWindows = $u->getWindows()->all();
print_r($allowedWindows);
I forget to answer my thread. So the problem was solved by adding forign keys to my database structure and after that i generated the model files with gii.

Yii2 RBAC group assignment confusion

I am trying to implement RBAC in my project by following the tutorial* on the Yii website. However I am confused when trying to implement the permissions by group.
For this example I have added a group field into the user table and have defined two groups, user (2) and admin (1).
I then created a console command which looks like this:
class RbacController extends Controller
{
public function actionInit()
{
$auth = \Yii::$app->authManager;
$rule = new \app\rbac\UserGroupRule;
$auth->add($rule);
$search = $auth->createPermission('search');
$search->description = 'Search';
$search->ruleName = $rule->name;
$auth->add($search);
$user = $auth->createRole('user');
$user->ruleName = $rule->name;
$auth->add($user);
$admin = $auth->createRole('admin');
$admin->ruleName = $rule->name;
$auth->add($admin);
$auth->addChild($admin, $user);
}
}
And I have this file: rbac/UserGroupRule.php
class UserGroupRule extends Rule
{
public $name = 'userGroup';
public function execute($user, $item, $params)
{
// return true; // force return to true for test
if(!Yii::$app->user->isGuest) {
$group = Yii::$app->user->identity->group;
if($item->name === 'search') {
return $group == 1;
}
return false;
}
}
I'm trying to test the permission with if(\Yii::$app->user->can('search')).
Firstly, I wonder why the console command is required here as I can't see where it's being used.
The $item parameter in the execute method has the value of search, but the tutorial shows that it expects this value to be role type.
Regardless of what I return in the execute method, it seems to return false.
Can anyone answer these questions?
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
I guess you have an authManager with DbManager ?
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
to init the rbac from the console just use yii rbac/init in a console (in correct project dir) then the database entries were done (before that the rbac tables should be empty)
if you haven't done yet create the tables with
yii migrate --migrationPath=#yii/rbac/migrations
$item is just the auth permission or role entry. The rule is called for every entry, if you have added a rule. In your case for permission "search" and roles "user" and "admin" the rules is executed.
your have added entries with rule checking. So if you e.g. check if the user can "search" by e.g.
if (\Yii::$app->user->can('search')) {
// can search
}
then the rule is checked or executed (which is your UserGroupRule). And in your case it would return true for admins and false for user given by the group field.
edit:
I hope you have added this to your components in your config file.
return [
// ...
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
// ...
],
];
You have created 2 roles in your rbac (user/admin) and as far as i understand your are using a group column in the User table to allocate those roles to the user. And in your code you will need to have to check the permissions or roles. So from the DB the correct Entry is selected and if a Rule is attached this rule is then executed. And this checks the current user group and returns true or false. So in your case no assignments to those roles or permissions are done. It uses the Rule to return true or false depending on the user group. But here are other extensions search for yii2admin or yii2rbac, where you can also assign user to roles/permissions etc by database entries.
I would say you should get more help where you can "chat" e.g. the yii chat which is linked on the yii homepage.

How to make roles in yii

So i am new to the yii framework and i am doing this blog style of a website trying to cover most of the features i can think off and the one I am stuck at is the having differnet user roles for example.
Lets say we have a writer and a normal logged in user and i want to make a writer when he go on the article page he can see some buttons while a normal loged in user can only see the comment button.
How do i come up with something to do this inside of the Yii Framework? and tutorials i can find on the internet?
Thank you for your time.
List all roles in User model
class User extends MyModel {
const ROLE_ADMIN = 1,
ROLE_AUTHOR = 2,
ROLE_USER = 3;
Also add role field to user (in database and in model).
In components/UserIdentity.php add some methods
public function isAuthor() {
return !empty($this->user) && $this->user->role == User::ROLE_AUTHOR;
}
public function isGuest(){
return empty($this->user);
}
Also, I recommend to add this method to User model:
public function getRole($role = null) {
$roles = [
self::ROLE_ADMIN => 'Admin',
self::ROLE_AUTHOR => 'Author',
self::ROLE_USER => 'User',
];
if (!is_null($role)) {
return isset($roles[$role]) ? $roles[$role] : 'Unknown role';
}
return $roles;
}
Hello thank you for the help that other people gave me but I have a found a a simple guide which i understood very easily and its very nice to use. you can find the tutorial in the following Link . Thank you For you help guys!

Categories