Last active
December 20, 2015 04:29
-
-
Save afreeland/6071150 to your computer and use it in GitHub Desktop.
C#: Bitshift Permission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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