mbmihura
mbmihura

Reputation: 552

design pattern to implement a set of permissions for a user

I'm trying to figure out the correct way to implement and code the following using desing patterns, or a good object oriented solution:

There is an user class which can contains a variable set of permits, each one enables him to do different action on the application. The idea is to be able tell a certain user object to, for example delete an order, if he has any permits that enable him to do so, do it and if not, to raise an exception.

If someone has a place where to read about this, it's helpfull too. thanks

Upvotes: 6

Views: 1489

Answers (2)

Anders Abel
Anders Abel

Reputation: 69260

There are built in functions for permission in C#/.NET.

The access requirements on a function is set through the PrincipalPermissionAttribute class, or inside the code with PrincipalPermission. To prevent a method from being called unless the current user is a member of the Administrators role, the following attribute is used (sample from MSDN):

[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
static void CheckAdministrator()
{
    Console.WriteLine("User is an administrator");
}

Both these checks against the current identity of the calling thread. So what you need to do is to implement the IPrincipal interface to allow your users to be set as the thread identity. Then you can use standard .NET PrincipalPermission to check security. It works exactly as you want - if the security demand is not met, an exception is thrown.

Upvotes: 5

Zohaib
Zohaib

Reputation: 7116

If one user can have multiple permits, each permit allows different execution tasks, then you might wanna have a look at decorator pattern.

although it depends a lot on your requirements.

Upvotes: 1

Related Questions