What are the disadvantages of using a flags enum for permissions?

2.6k Views Asked by At

In trying to implement role based security for a web app, I have a table in the database for Permissions, Roles, Users and UserRole (i.e the assignment of users to roles).

Each role has a set of permissions. The permissions are defined as a C# flags enum with values such as 0, 1, 2, 4 and so on.

In the database the role table has a int field which stores the combined permission flags for the role. (This way we avoid having a separate Permissions table (is that good or bad?) and a one-to-many table for RolePermissions.

In the code, I check if a user has access by calculating the effective permissions for the role(s) the user is assigned to. In .NET it is pretty easy to do that by doing logical operations on the enum flags.

So my question is:

Is there a disadvantage to doing it this way (as opposed to having a Permission table and RolePermission link table (that contains 1 record for each permission given to a role)?

3

There are 3 best solutions below

1
On BEST ANSWER

Three immediate disadvantages:

  • Flags can only contain as many items as there are available bits.
  • Querying from the database now gets a little more annoying. Well, only if you are using SQL manually (a join onto the roles table to determine membership reads a lot nicer).
  • When viewing the data not as flags, is anyone going to remember what a value of 1 in the fourth bit means?

Make life easy and go with a separate list. Is assigned to in a collection could very nicely boil down to myPermissions.Contains(new Permission("CanEdit")). You could then use various conversion routines to convert hardcoded values such as enums or strings into object representations of permissions to achieve myPermissions.Contains("CanEdit") etc.

This is not to say there are performance impacts in choosing flags over separate tables and vice versa, I've no idea what sort of usage you are looking at.

1
On

The only disadvantage is that you'll end up writing more code in order to check for permissions. Having a separate table with user-roles makes it very simple to determine them.

  • Advantage: Save storage space (but who cares about this on this scenario?)
  • Disadvantage: More complexity on your code.
0
On

I used a flag enum just like you described 3 years ago in a project. My considerations:

  • Create a layer to simplify usage or you'll end up with a messy code in the front end
  • Its not intuitive for 'new developers'. If somebody else will maintain this code, be aware that he may miss the whole idea and introduce more complexity and/or bugs...

Ps.:

Each role has a set of permissions. The permissions are defined as a C# flags enum with values such as 0, 1, 2, 4 and so on.

NEVER use 0 in a flag enum...