Last active
August 29, 2015 14:12
-
-
Save mahizsas/08b3916d3b34965ff887 to your computer and use it in GitHub Desktop.
Sample Permissions in memory
This file contains hidden or 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
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Security.Principal; | |
namespace GhettoPermissions | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); | |
if(user.CanPerform<Product>(Permissions.Action.Read)) | |
{ | |
Console.WriteLine("You can do eeet!"); | |
} | |
else | |
{ | |
Console.WriteLine("YOU SHALL NOT BASSS!"); | |
} | |
Console.ReadKey(); | |
} | |
} | |
public class Product | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public decimal Cost { get; set; } | |
} | |
public static class Permissions | |
{ | |
public enum Action | |
{ | |
Create, | |
Read, | |
Update, | |
Delete | |
} | |
private static class Roles | |
{ | |
public const string Developer = "Developers"; | |
public const string User = "User"; | |
public const string FinancialAnalyst = "FinancialAnalyst"; | |
public const string FinancialSupervisor = "FinancialSupervisor"; | |
public const string Auditor = "Auditor"; | |
public const string Administrator = "Administrator"; | |
} | |
public static bool CanPerform<T>(this IPrincipal principal, Action action) | |
{ | |
if (principal == null) return false; | |
var roles = from permission in PermissionSets | |
where permission.Key == typeof(T) | |
where permission.Value.ContainsKey(action) | |
from items in permission.Value[action] | |
select items; | |
return roles.Any(principal.IsInRole); | |
} | |
private static readonly IDictionary<Type, IDictionary<Action, IEnumerable<string>>> PermissionSets | |
= new ConcurrentDictionary<Type, IDictionary<Action, IEnumerable<string>>>( | |
new Dictionary<Type, IDictionary<Action, IEnumerable<string>>> | |
{ | |
{ typeof (Product), new Dictionary<Action, IEnumerable<string>> { | |
{ Action.Create, new[] { Roles.FinancialAnalyst, Roles.FinancialSupervisor }}, | |
{ Action.Read, new[] { Roles.User, Roles.Developer }}, | |
{ Action.Update, new[] { Roles.FinancialSupervisor }}, | |
{ Action.Delete, new[] { Roles.Administrator }}, | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment