Reputation: 51
in my application I want to start with role based access control, but I dont know best practice for check if loged user has access right. On page I have some blocks where some user role can edit, but another can only view, and for third role is this block invisible.
my present code looks like this:
if (role=="admin") {
full access
} elseif (role=="user") {
only display content without editing option
} else {
// not loged or user role with limited access
no content display
}
but when I have on page 5 to 10 this blocks it is very unworkable to create a lot of this IF statements. Is there some best practice to checking user roles without using IFs?
Thanks a lot and sorry my english.
Upvotes: 0
Views: 502
Reputation: 174967
Give roles numbers:
const ACCESS_NONE = 0;
const ACCESS_USER = 1;
const ACCESS_ADMIN = 2;
const ACCESS_ROOT = 4;
Note I'm using powers of two, that way even if a user has all the accesses before a certain one, it still won't be bigger (NONE + USER + ADMIN < ROOT).
Now, all you have to do is
if ($access >= ACCESS_ADMIN) { //admin+ only content
Upvotes: 2