问题
I have several models, for which I want to show some common icons for action links (new, details, edit, delete) and some specific ones for certain models only; these iconlinks must only be showed when the user has permission to perform the action. Permissions are decided by roles, but I'd like to abstract them, so that the explicit needed roles are written in one place only.
I'd also like to use the same logic to show icons and to "protect" action methods, so that if Foo
role used to be needed to edit lolcatz, and now I want to change it to Bar
role, I only have to change one thing.
There are many ways to implement this, and I'm unsure on how to proceed.
I could write a ModelAction
class, responsible for deciding permissions, link, icon, text for a single action, and some ModelActionsCollection
to gather all possible actions for a single model, so that I can write a parent class and several descending ones.
My doubts:
how should I associate models with
ModelActionsCollection
? Should I use a hash or some static class, likeSomeStaticClass.GetModelActionsCollection(someModel)
? ortypeof(someModel)
, or"className"
or what?how should I decorate methods? should I write something like:
[MyAuthorize("action", "model")] public ActionResult action(...)
or something else?
is it okay to access to the current authenticated user directly inside these classes' methods, or should they receive user as parameter?
what namespace this classes belong to? are they models? helpers? or what?
and, finally: has anybody already done all this in a reusable way?
回答1:
We do exactly this
Decorate your action with a permission type flag and a string for the icon in css e.g. [ActionModelPermission(typeof(ContactModel), PermissionTypes.Create | PermissionTypes.Edit, "typeIcon typeContact")]
The ActionModelPermission, PermissionTypes and ContactModel are all classes in our project.
Then we have our own ActionLink helper which finds the method from a lambda supplied and does the permission check, and builds the link with the appropriate css class on it
来源:https://stackoverflow.com/questions/1453329/permissions-aware-icon-action-links-for-all-models-how