简体   繁体   中英

Best practice to check user access rights in RBAC

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM