Magento: get roles and users - magento

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;
}

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();

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);

Check if Admin is Logged in Within Observer

I'm attempting to check if the administrator is logged in from an observer. The problem is that while this is easy to do when viewing the admin module, viewing the frontend is another story.
There are several similar questions, but unfortunately none of them provide a working solution for Magento 1.6.2.
I wasn't able to successfully get isLoggedIn() to return true in the admin/session class. I also found out that there is a cookie for both frontend and adminhtml, which may help.
The accepted answer in this related question seems to suggest this may not be possible:
Magento - Checking if an Admin and a Customer are logged in
Another related question, with a solution that didn't help my specific case:
Magento : How to check if admin is logged in within a module controller?
It is possible. What you need to do is switch the session data. You can do this with the following code:
$switchSessionName = 'adminhtml';
if (!empty($_COOKIE[$switchSessionName])) {
$currentSessionId = Mage::getSingleton('core/session')->getSessionId();
$currentSessionName = Mage::getSingleton('core/session')->getSessionName();
if ($currentSessionId && $currentSessionName && isset($_COOKIE[$currentSessionName])) {
$switchSessionId = $_COOKIE[$switchSessionName];
$this->_switchSession($switchSessionName, $switchSessionId);
$whateverData = Mage::getModel('mymodule/session')->getWhateverData();
$this->_switchSession($currentSessionName, $currentSessionId);
}
}
protected function _switchSession($namespace, $id = null) {
session_write_close();
$GLOBALS['_SESSION'] = null;
$session = Mage::getSingleton('core/session');
if ($id) {
$session->setSessionId($id);
}
$session->start($namespace);
}
Late Answer but if as I found it on google:
This it not possible.
Why? Because the default session name in the frontend is frontend and the session name in the backend is admin. Because of this, the session data of the admin is not available in the frontend.
have you tried this :
Mage::getSingleton('admin/session', array('name' => 'adminhtml'))->isLoggedIn();
how about this ( I am not sure it will work or not )
require_once 'app/Mage.php';
umask(0);
$apps = Mage::app('default');
Mage::getSingleton('core/session', array('name'=>'adminhtml'));
$adminSession = Mage::getSingleton('admin/session');
$adminSession->start();
if ($adminSession->isLoggedIn()) {
// check admin
}

Magento: How to get user role from user id

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'];

Magento - redirect user group after login

How can I redirect different user groups to different pages in Magento ?
what I want to do is to assign a category to each customer group to redirect the user to it on login.
Thanks a lot.
I have not tried this. I think you need to do the following on the customer_login event:
$session = Mage::getSingleton('customer/session');
$category = // A category object based on $session->getCustomerGroupId()
$session->setBeforeAuthUrl($category->getUrl());
Go to /app/code/local/MagentoPycho/Customer/controllers/AccountController.php and replace this:
$session->setBeforeAuthUrl(Mage::helper('customer')->getAccountUrl());
with this:
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
if($groupId == 5) {
$session->setBeforeAuthUrl('http://google.com');
} else {
// Set default URL to redirect customer to
$session->setBeforeAuthUrl(Mage::helper('customer')->getAccountUrl());
}
Be sure to put your Group ID instead of the "5" and your redirect URL instead of google.com.
I just tried it.
How about this for an approach:
Consider starting with an existing module such as:
http://www.magentocommerce.com/magento-connect/MagePsycho/extension/3763/custom_login_redirect
Then adding your own logic. For the group name of a customer you can try this:
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
$group = Mage::getModel ('customer/group')->load($groupId)->getCode();
If you then have your categories named as per your groups you can do a redirect to http:// + base_url + $group therfore removing the need to explicitly work out what category page to load.
In order to redirect the customer as per customer group, there is a commercial extension:
http://www.magepsycho.com/custom-login-redirect-pro.html
really worths trying. FYI many merchants are using this module for their magento sites.
Happy e-commerce!!
Regards

Resources