Pregunta

I would like to create a user system with roles/permissions per user. I want the list of configurable permissions to be automatically generated by using reflection. The code will scan through all assemblies looking for the attribute that defines the permissions and description of the modules (classes) or functionalities (functions) that users need to have permissions for to execute.

Now the GUI should of course not show or disable what a user isn't allowed to do. But I want to make sure that it is checked, that a user is allowed to execute a certain function/module automatically when it does.

So whenever a GUI component is enabled by error, the user clicks it, but isn't allowed to execute its function-behind, an exception is thrown.

It would be nice if there was some kind of way to automatically execute code upon entry of functions that are decorated with a specific attribute. So code can then verify if the user is allowed to execute the functionality or throw an appropriate exception otherwise.

I known I can achieve this by calling a function the first thing a function is entered. Using GetCurrentMethod to obtain MethodInfo.Attributes to determine whether this function is allowed to be executed by the user.

However, I wish it would not be necessary to add a first-line of code that does the user permission checking, but the permission would be checked automatically when the attribute is defined. Is this possible?

Or am I inventing the wheel myself and are there out-of-the box solutions to my 'problem'?

¿Fue útil?

Solución

You can do this by using aspect oriented programming e.g. with PostSharp. More about this here: http://www.postsharp.net/aspects/method-decorator

It will allow you to decorate your method with an attribute that contains an OnEntry method that will be called automatically before the actual method is called.

Note: PostSharp will analyze your assembly and change it after compilation! It will simply include the OnEntry call for you. C# itself doesn't support this behavior as far as I know. This can be a little annoying depending how complicated your build pipeline. also it could be confusing during debugging.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top