Search code examples
c#asp.netenumsrolesenum-flags

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


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)?


Solution

  • 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.