Magento: How to get user role from user id - magento

I am building a custom admin extension, I need to find a user's role having it's ID, any way to do this, I've been trying to find where does magento store the info on what users are what role with no luck so far. Any help would be very appreciated.

Assuming you're talking about the users who log into the admin console, this should get you what you want.
//By ID
$id = 2;
$role_data = Mage::getModel('admin/user')->load($id)->getRole()->getData();
var_dump($role_data);
//By Username
$username = 'admin';
$role_data = Mage::getModel('admin/user')->getCollection()->addFieldToFilter('username',$username)->getFirstItem()->getRole()->getData();
var_dump($role_data);

Using this code you will get the role of current user
$admin_user_session = Mage::getSingleton('admin/session');
$adminuserId = $admin_user_session->getUser()->getUserId();
$role_data = Mage::getModel('admin/user')->load($adminuserId)->getRole()->getData();
$role_name = $role_data['role_name'];

By using this code you will get the detail of the user and also it's role data
$user = Mage::getSingleton('admin/session');
$username = $user->getUser()->getUsername();
$role_data = Mage::getModel('admin/user')->
getCollection()-addFieldToFilter('username',$username)->
getFirstItem()->getRole()->getData();
$role_name = $role_data['role_name'];

Related

How to get a list of roles with certain permission in Spatie/permission (Laravel)

I am trying to get it by same way i am getting the list of users with a certain Permission, but with role it's not working throwing me
Call to undefined method Spatie\Permission\Models\Role::roles()
The way i get list of users with a certain role:
$permission = $request->permission;
$usersWithPerms = User::permission($permission)->get();
return array("usersWithPerms"=>$usersWithPerms);
The way im trying to get roles with a certain permission:
$groupsWithPerms = Role::permission('perms_givePermToRole')->get();
return array("groupsWithPerms"=>$groupsWithPerms);
BadMethodCallException
Call to undefined method Spatie\Permission\Models\Role::roles()
get the permissions of a role
and get the roles of a permission
$permission = Permission::findOrFail(1);
$groupsWithPerms = $permission->getRoleNames();
//dd($groupsWithPerms);
$role = Role::findOrFail(1);
$groupsWithRoles = $role->getPermissionNames();
//dd($groupsWithRoles);
The only thing i get its a name but not id of the roles with a certain permission:
$permission = Permission::findOrFail($request->idPermission);
$groupsWithPerms = $permission->getRoleNames();
Where: getRoleNames() is a method from spatie package.
So this works fine but you only get the names of the roles not ids.
There is no in-built shortcut to get them in the package, but querying for them is simple enough:
//Eager load roles to get all data in just 1 query
$permission = Permission::with('roles')
->where('name', 'perms_givePermToRole')
->first();
$rolesWithPerm = $permission->roles;
//or
$rolesWithPerm = Role::whereHas('permissions', function($permissions){
$permissions->where('name', 'perms_givePermToRole');
})->get();

login a user and granting core permissions in Joomla

I am working on a project which requires some manager level access to perform tasks, so when I receive a call I forcefully logging in the request as a superuser so that it will have all permissions to complete that task. For login I am using this code:
function forceLogin($superuserId)
{
$user = JFactory::getUser($superuserId);
//Will authorize you as this user.
JPluginHelper::importPlugin('user');
$options = array();
$options['action'] = 'core.login.site';
$response = new stdClass();
$response->username = $user->username;
$response->language = '';
$response->email = $user->email;
$response->password_clear = '';
$response->fullname = '';
$result = $app->triggerEvent('onUserLogin', array((array)$response, $options));
return true;
}
By this my current login user will be superuser. Now the concern is when any extension is searching for permissions, it is still getting that current session doesn't have them and so it returns false.
One of the solutions I came around is to redirect internally after login and then proceed to other tasks, in that way the system recognizes session to be availed with all permissions. For example -
I received something in getNotification()
function getNotification()
{
//from here I log in the user
$this->forceLogin($speruserId);
//and now redirect
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_mycomponent&task=setNotification');
}
Now I proceed further request from setNotification()
function getNotification()
{
// do my work here
}
To be specific, the issue is arising in VirtueMart (e-commerce extension) in which I am creating a product from my call and while creating a product it checks vmAccess::manager('product.create') which is actually same as core.create of Joomla.
I think by redirecting session is being reset with current user and so it gets all permission. Can it be done without redirection? If yes, how?

Getting all Sentinel user related to roles

How can I get all users related to user roles by Sentinel? And how can I get all users in Sentinel? This does not work:
Sentinel::all()
You can try this to get all users related to a specific role.
$role = Sentinel::findRoleById(1);
// or findRoleBySlug('admin'); for example
$users = $role->users()->with('roles')->get();
and you can access the first user (and so on and so forth like this)
dd($users[0]['attributes']);
and to get all users you can do this:
$test = Sentinel::getUserRepository();
dd($test);

FosUser, Create a user manually

For a special case in my application, i need to register a user manually from an ajax request.
So, first i send with ajax all my datas : firstname, lastname, mail, password etc... to my controller.
For now, after that, i just do in my controller :
$firstname = $request->get('firstname');
$lastname = $request->get('lastname');
$mail = $request->get('mail');
$password = $request->get('password');
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->createUser();
$user->setUsername($firstname.$lastname);
$user->setPlainPassword($password);
$user->setEmail($mail);
$user->setFirstname($firstname);
$user->setLastname($lastname);
$userManager->updateUser($user);
But my problem, how can i validate the user before updateUser() ? I need to check manually if this email/username already exist ?
How can i do that with a better way ?
You can check if the email arealdy exists with the findUserByEmail method just before the updateUser :
$user = $this->get('fos_user.user_manager')->findUserByEmail($mail);

Magento: get roles and users

How can I get collection of all roles (System->Permission->Roles) and users which has this role?
Thanks.
To get all the Roles
$roles = Mage::getModel('admin/roles')->getCollection();
foreach($roles as $role):
echo '<br/>Role : '.$role->getId()." | ".$role->getRoleName();
endforeach;
To get the Role users
$roles_users = Mage::getResourceModel('admin/roles_user_collection');
foreach($roles_users as $roleuser):
$user = Mage::getModel('admin/user')->load($roleuser->getUserId());
echo '<br/>User : '.$user->getUsername()." | ".$user->getFirstname();
endforeach;
You can also get all role user ids with this
$roles = Mage::getModel('admin/roles')->load($roleId)->getRoleUsers();
I came across this post when I looked for a way to select all admin users belonging to a specific user role. (See this answer and this question.) The question here could be read as if Alex wants the admin users for each role. Since the answer does not sort by admin role, I would like to offer the following solution:
$usersByRole = array();
$adminRoles = Mage::getModel('admin/roles')->getCollection();
foreach($adminRoles as $adminRole) {
$adminRoleId = $adminRole->getId();
$adminRoleUserCollection = Mage::getModel('admin/role')->getCollection()
->addFieldToFilter('parent_id', ['eq'=>$adminRoleId])
->join(['user' => 'admin/user'], 'user.user_id=main_table.user_id');
$usersByRole[$adminRole->getRoleName()] = $adminRoleUserCollection;
}

Resources