Mortalus
Mortalus

Reputation: 10712

User Role Association per Domain Entity

I have the following structure in my DB:

DomainEntities:
 +EntityID
 +Name
 +ParentID
 +...

Users:
 +UserID
 +Username
 +...

Roles:
 +RoleID
 +Name

UserRolesAssociation:
 +RoleID
 +UserID
 +EntityID

So i want to use MVC's built in authorization attribute to filter action in my controllers that are made by different members.

I what to be able to say if user1 makes a delete action on entity1 or any entity under it i can see if he has the right role to do that and filter the action accordingly.

What would be the best practice to tackle that topic ? Should i create my own permissions engine that will provide me the answers i need or can i use the existing capabilities ?

Upvotes: 1

Views: 489

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

What would be the best practice to tackle that topic ?

A custom [Authorize] seems like a good place to implement this logic.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // the use ris not authenticated or not authorized - no need to continue
            return false;
        }

        string username = httpContext.User.Identity.Name;
        // read the entity id that this user is attempting to manipulate
        string entityId = (string)httpContext.Request.RequestContext.RouteData.Values["id"] ?? httpContext.Request["id"];

        return IsAllowed(username, entityId);
    }

    private bool IsAllowed(string username, string entityId)
    {
        // You know what to do here - hit the database and check whether
        // the current user is the owner of the entity
        throw new NotImplementedException();
    }
}

and then:

[HttpDelete]
[MyAuthorize]
public ActionResult Delete(int id)
{
    ...
}

Upvotes: 2

Related Questions