Skip to content

Instantly share code, notes, and snippets.

@afreeland
Last active December 20, 2015 04:29
Show Gist options
  • Save afreeland/6071150 to your computer and use it in GitHub Desktop.
Save afreeland/6071150 to your computer and use it in GitHub Desktop.
C#: Bitshift Permission
public class Permission
{
public class Access
{
public Permission.View.Customer Customer { get; set; }
public Permission.View.Inventory Inventory { get; set; }
public Permission.View.Order Order { get; set; }
}
public class View
{
public enum Order : byte
{
None = 0,
Orders = 1 << 0, // 00000001 (1)
Drafted = 1 << 1, // 00000010 (2)
Create = 1 << 2 // 00000100 (4)
}
public enum Inventory : byte
{
None = 0,
Items = 1 << 0, // 00000001 (1)
Import = 1 << 1 // 00000010 (2)
}
public enum Customer : byte
{
None = 0,
Customers = 1 << 0, // 00000001 (1)
AddCustomer = 1 << 1 // 00000010 (2)
}
}
public static bool HasPermission(byte userPermission, byte permissionsToCheck)
{
// If userPermission contains the permissionsToCheck, it will return permissionsToCheck
// Otherwise it will return 0 .. which could correspond to a enum of None = 0
return ((userPermission & permissionsToCheck) == permissionsToCheck);
}
}
// Checking Permission against user Permission
bool hasPermission = Permission.HasPermission((byte)_userPermissions, (byte)Permission.View.Order.Orders);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment