If you have a menu “Admin tasks” and different admin tasks (like 10) that you could separately assign to each user, but there are users who don’t have any admin tasks, how would you deal with “Hiding admin menu” for those users?
I was thinking of 3 ways:
1) Javascript, check if Admin menu is empty and then hide it.
2) Check for all permissions in Admin menu, with a counter, and show it if counter > 0. And then also re-check the permissions for each item to show.
3) Save all permissions in associative array. Test all and assign ‘ true’ to granted items. When building the menu, have a function that tests if there is at least one permission granted. I wouldn’t need to re-check permissions against DB, just against the array for each item.
Is there any better way?
1
You haven’t specified neither the template engine you use, nor the framework, so it’s difficult to be more specific, but usually, template engines let you display specific HTML for a list, and a different HTML if the list contains nothing. In Django, for example, the syntax is the following:
<ul>
{% for task in administrative_tasks %}
<li>{{ task.name }}</li>
{% empty %}
<li>You should be an administrator to access the tasks.</li>
{% endfor %}
</ul>
Note: you added “security” tag to your question. Displaying or not a link reserved to administrators on a web page has nothing to do with security. If you need to be sure that non-administrators cannot access a specific resource, you should check their permissions during the request and return 401 Unauthorized or 403 Forbidden accordingly.
2
Id depends. Do we have users that are not admin and can’t have admin tasks? Then it’s option 3) because the logic for displaying any admin-associated things should not even be called.
If we have admins with an empty task list, then Option 1) is correct/best. Option 2) would have the drawback that if it comes, that you later want to port it to another environment with different view and you want to show an empty admin-task-menu (for whatsoever reason) you have a problem. It is about how data are displayed not what data are to be displayed and that would be CSS or if CSS is not sufficient then CSS with javascript support.