Laravel menu based on role? - laravel

i have codeigniter background. Now, i'm learning about laravel. So, i'm in this condition (Example), I'm trying to create a webapp, which has multiple users. The UsersType A , they can access menu a, menu b & menu c and UsersType B they only can access Menu a.
Now, i'm using https://github.com/lavary/laravel-menu . Well, if it's only have two types , i can write it manually. But, what if there are five types of user or more.
When i'm using codeigniter. I create 4 table Users , UsersType , Menu & MenuAccess. You must be understand how it's work. I just, play it with query then i show it.
UsersType (Users) -> TypeId (UsersType) -> MenuId (MenuAccess) -> MenuId (Menu)
I already use google and I found this https://github.com/Zizaco/entrust but what i can see from that package. It's only give the permission on the action (input,edit & delete)
So, Can i do my codeigniter way in my laravel ? Save my routes properties than show it in my rouotes/web.php (I don't know if it possible, haven't try it yet). sorry for my english.

What I would do is put a function in the User class which checks it's own permission and then returns a view which contains the menu that user has access to.
public function menu()
{
switch($this->role) {
case 'admin':
return view('menus.admin');
[etc]
}
}
Then in the view just check if the user is logged in and show the menu:
#if Auth::check()
{{ Auth::user->menu() }}
#endif

As mentioned in the comments,it sounds like what you want is the ability to conditionally display content based on whether a user has certain permissions.
There's a number of implementations of this. Essentially what they all do is store permissions that can be granted to users, and optionally store roles that allow permissions to be assigned to a role and then users can be given that role, automatically granting them the permissions associated with that role.
I've found spatie/laravel-permission which appears to be quite good. Then, if you pass your user model into the view, you can do something like this:
#if ($user->can('edit-posts'))
<a>Edit post</a>
#endif
That should be flexible enough that it can be reused for different permissions too. If that doesn't do the trick, then it's not hard to roll your own permission system using Laravel's authorization system and you should be able to use the can() method in the same way.

Related

Creating an admin permissions section in laravel

I've created a couple of pages they are users, groups and permissions.
I would like the admin to be able to create groups and set what those groups can do via the permissions page.
So on the permissions page I would have a list of things a user could do e.g.: add content, delete content.
And if I check the add content box then the group can only add content and not delete content.
The problem I'm having is that I don't know where to go to look for information on how to go about it. I've already got my database set up and I'm thinking maybe sessions and routes is the way to go, but I'm not sure.
Frameworks is the way to go for something this complex. I'm working on a very similar project for my work (a dashboard to do different things based on User Role/Permissions) and I found it incredibly difficult to manage without the use of a framework. I would highly recommend Cartalyst/Sentry for this. It turns complex database operations like checking permissions, update permissions, creating groups etc into simple one. Here is a link to the manual:
Cartalyst/Sentry
It has a database backend already created (and modifiable) for you, so you simply follow the installation instructions and go over the documentation to get a better understanding. In your example, it would be as simple as creating a group and it's permissions:
// Define permissions (1 is allowed, 0 is not allowed)
$permissions = array('content.create' => 1, 'content.delete' => 1, etc etc...));
$group = Sentry::createGroup(array('name' => 'Admin', 'permissions' => $permissions));
Creating a user and adding them to the group:
$user = Sentry::createUser(array('email' => 'test#test.com', 'first_name' => ..., etc));
$group = Sentry::findGroupByName('Admin');
$user->addGroup($group);
And then checking their permissions during routing:
$user = Sentry::check(); // Aka get the current user.
if($user->hasAccess('content.create'){
// Continue
} else {
// Redirect to error page, etc
}
Now that's a brief overview of the system, and I assume you know how to use controllers and routes, but play around with it and I'm sure you'll come to see how powerful this Framework is when working with Laravel.
Hope that helps!
Then checking whether or not a user

Error on login for backend users with custom roles

I created custom role for some users, and I assigned role to particular user with content tree limitation. Like on this image
Problem is that when that user log in, he get error like on this image. Roles are working, so user can see his assigned content tree and work with it.
How can I solved this first screen? Even redirection on his content tree would do the job.
Thank you :)
Make sure that the user you assigned the role to, also has a basic role to access basic contribution functions. I usually have a "backoffice user" role which is assigned to every contributor (or group), which includes (without any limitation) :
user/login on the admin siteaccess
content/read on at least the root node : you need to be able to get "through" that node (and others if needed) to see the ones under it
ezoe, ezjscore, ezmultiupload, ezfind, ezie etc
content/(edit|remove|...) on contents which is owned by the user himself or its group
Hope this helps

Sentry & Laravel, getting users within a group. changing findAllUsersWithAccess to have pagination

I'm trying to find all users w/ a specific permissions list in Sentry with laravel. The problem is that Sentry::findAllUsersWithAccess() returns an array().
as stated in their github repository i pinpointed their code to be
public function findAllWithAccess($permissions)
{
return array_filter($this->findAll(), function($user) use ($permissions)
{
return $user->hasAccess($permissions);
});
}
right now, it gets all users and filter it out with users with permission list. the big problem would be when I as a developer would get the set of users, it'll show ALL users, i'm developing an app which may hold thousands of users and i only need to get users with sepcific permission lists.
With regards to that would love to use one with a ->paginate() capability.
Any thoughts how to get it without getting all the users.
Why dont you override the findAllWithAccess() method and write your own implementation, which uses mysql where instead of array_filter().
I dont know your project structure and the underlying db schema, so all i can give you atm is the link to the eloquent documentation Querying Relations (whereHas).
In case you dont know where to start: its always a good idea to look at the ServiceProvider (SentryServiceProvider, where the UserProvider, which holds the findAllWidthAccess() method, is registered). Override the registerUserProvider method and return your own implementation of the UserProvider (with the edited findAllWithAccess() method).
Hope that will point you in the right direction.
In Laravel you can do pagination manually on arrays:
$paginator = Paginator::make($items, $totalItems, $perPage);
Check the docs: http://laravel.com/docs/pagination

How to create user-specific content in Joomla! 3.0?

I need to create a User-Specific content page, I have registered users and I need to create a module/page/menu/feed or whatever that displays articles that are for only one or some users.
For example, in my site, I show to public some projects (articles redacted as some architecturing project) for example: news, finished projects, etc, some people register and can access to other content that is intended for registered users, for example: new projects that only registered clients would be interested, so far, I managed to make this work, but now, I have work that is for a specific user and he/she only can see it in his/her feed, for example: status of their project made by us, some galleries with photos of the work in progress, etc.
So, This feed must be a module/page/menu that shows articles with a specific category and for registered users. But I want to be able to post an article that is only intended for a specific user or a set of users and shows in this feed (module) or at least a whole new module that shows user-specific content without having to create a category and an access level for each user.
Is there an extension or plug-in that helps me do this?
you need to make do two things:
Make a new user-group (Users->User group) as a sub-group of
registered. Add the users that need the special permission to this
group.
Make a new access-level (Users->access-levels) and add you
new user-group to this access level
Set the access-level on the article(s) that you want to restrict access on.
The module should check the access-level before it displays it to the users, and only display the restricted articles to those that have the correct privileges.
The system don't really support what you ask for, but you could use the following setup:
Make a content-plugin (http://docs.joomla.org/J2.5:Creating_a_content_plugin). In the event onContentPrepareForm, you modify the created_by_alias-field to use it for your special user allowed to view this content article.
function onContentPrepareForm($form, $data){
// first check that context is right
// Then change the type of the field. This should allow to select
// the user when you create the article.
$form->getField('created_by_alias')->__set('type', 'user');
}
In the event onContentPrepareData, check if the data in the created_by_alias references a valid user in the user group your users shoud be in
public function onContentPrepare($context, $article, $params, $page){
// first check that context is right
//Then fetch the user data:
if(is_int($article->created_by_alias)){ // ( Optionally check if the article is in a specific category )
$db=JFactory::getDbo();
$currentuser=JFactory::getUser();
$allowedgroup=2; // the registered users group
$sql="select u.id from #__users inner join #__user_usergroup_map ug (u.id=ug.user_id) where ug.group_id={$allowedgroup}";
$db->setQuery($sql);
$user=$db->loadObject();
if($user->id==$currentuser){
$data->user=$user;
}
else{
//Unset the article content to prevent unothorized users from seeing the content.
unset($article);
}
}
Finally, create a module (http://docs.joomla.org/Creating_a_simple_module) that feeds articles for a particular user, containing at least:
$list=array();
$user=Jfactory::getUser();
if($user->id>0){
$sql="select * from #__content where created_by_alias={$user->id}";
// ( also add sql to check that the user has access,
// the article is published, the correct category etc)
$db=Jfactory::getDbo();
$db->setQuery($sql);
$list=$db->loadObjectList();
if(!count($list)) return;
}
else return;
print_r($list); // Prints the content articles
This scheme should protect unauthorized users from viewing the content of the articles ment for a specific user. The module should (after nicely outputting what you want to display) display a list of articles for the logged inn user. The module can link to the article in the normal way, and the authorized user will have access. So it should be "safe enough", and provide the functionality you need without too much hassle.
I'll try anotherone here:
You could just install a messageing system on your site. UddeIM is one such system. This will allow you to make specific content for your users. UddeIM can be configured so only administrators can send messages. There is also some modules for this component to show latest messages etc.

Modifying view based on ACL in CakePHP

I want to be able to show or hide certain elements in a view based on ACL. For instance, if a user is looking at my Users/index view, I don't want to show a 'Delete User' element if he doesn't have permission to delete users. If he does have permission to edit users, I do want to show a 'Edit User' link.
I can hack this together, but being very new to Cake I'm hoping that there is an elegant solution. The best I've done involves keeping logic in two places, so it's hell to maintain.
Thanks!
I know this is an old question now but for anyone looking for a way like I was...
In AppController::beforeFilter you can assign the ACL component to a view variable and then use it in your view:
$this->set('user', $this->Auth->user());
$this->set('acl', $this->Acl);
And then in you view just juse it like thie:
if($acl->check(array('User' => $user), 'controllers/groupd/admin_delete')) {
This is't necessarily the most correct way to do it but it does work nicely
There is no generic "elegant solution" :) I've always wanted to make such thing as well. Anyway how you could do it:
Overwrite the Html Helper in your app directory - make a copy from /cake/libs/views/helpers/html.php to /app/views/helpers/html.php and made some changes in the Html::link function.
For example you can check if the url contain action edit or delete.
The other part is to pass the proper parameters from the controller. In AppController::beforeFilter you can read the rights of the user (it's better to be cached) and to pass it in a special Auth variable to the View.
So when you have the rights in your View it's easy to modify the link. :)
As I said I haven't did it in real example, but this is the way I would do it.
There is 1 bad point in that - if the original Html helper is changed, your one will remain the same. But I believe that Html helper is mature enough so for me is not a big issue.
I do it like this in app_controller.php, although you could just as well do it in specific controllers. The view variables $usersIndexAllowed and $configureAllowed are then used in conditional statements in the view.
function beforeRender()
{
if($this->layout=='admin')
{
$usersIndexAllowed = $this->Acl->check($user,"users/index");
$configureAllowed = $this->Acl->check($user,"siteAdmins/configure");
}
$this->set(compact('usersIndexAllowed','configureAllowed'));
}
In case you don't want to mess around with overriding core helpers and you want a more automatic way of checking (without hard-coding user group names and users or setting separate link-specific variables) here's my suggestion:
Store all user permissions as session vars when the user logs in (clear on logout) and create a permissions helper to check if logged on user has permissions for a specific action.
code and example here
hope that helps
There's multiple approaches to this scenario. As Nik stated, using a helper to do the checks for you is a quick way to "outsource" the logic and centralize it for ease of use.
Actually, have a look at the AclLinkHelper - it does exactly what you're looking for, however restricted to links only.

Resources