Restrict an Administrator to create new users as per his allocated quota in a Multi-Tenant environment

Lately I have been working on a Multi-Tenant application using the latest MVC5 framework. The application is essentially an Ecommerce reporting and product analysis and forecasting application that can pull clients stock and sales information from different ecommerce channels like Amazon, Ebay, Groupon and Magento

Here is what the primary technology stack I’ve used in the application looks like:

  • Asp.Net MVC5
  • Asp.Net Identity Framework 2.0.1
  • Entity Framework 6.0.1
  • SQL Server 2008
  • Html5, CSS3, JQuery

So, as with any other Multi-Tenant application the application had various Subscription Levels or packages. Each Tenant can subscribe to any one Subscription Package which had a number of features. One of the features was the number of User Accounts the Tenant Administrator could create. This would vary depending on his subscription level. The Tenant Owner could request to add more user accounts to his subscription by paying a cost per user, and then that would be the user accounts limit.

So, basically there was a need for a Gated User creation process based on the Subscription Level of the Tenant and any additional users he had requested. I thought about a few approaches like:

  • Storing the Number of users allowed in the Session for a Tenant and then checking it each time I would create a user
    • The problem with this approach was that there were other features as well who’s creating was to be gated. So essentially I would need to store every feature in the session. Or store a list of features in the session. And then in the case of Users, when an additional user was requested then I would have to updated that value in the session variable as well along with updating the database. A bit that I didn’t wanted to manage
  • Setup a role for the ability to create users and remove it when they have created too many. Whenever they create a user, check to see if they meet the threshold, if they do, remove this privilege from their account.
    • This method was too cumbersome. Imagine if the admin removes a user, then if the role “CanCreateUsers” is not present, then we first add it, then do the whole process of adding entity, then if the limit reaches, then we remove this role again. And we do that on every User add and remove, plus also when an Owner requested additional user to the account. Its too much overhead and invitation to bugs

So after thinking about a few approaches I ended up using a mix of the ActionMethodSelectorAttribute and a simple HtmlHelperExtension along with an enum that described my gated actions. The code is as follows:

GatedAction enum

public enum GatedAction

ActionMethodSelectorAttribute – SubscriptionActionAttribute

public class SubscriptionActionAttribute: ActionMethodSelectorAttribute
    public GatedAction Action { get; set; }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        var tenantId = controllerContext.RouteData.GetTenantId();
        using (var context = new ApplicationDbContext())
            var tenant = context.Set<Tenant>().Include("Subscription").FirstOrDefault(t => t.Id == tenantId);
            switch (Action)
                case GatedAction.CreateUser:
                    var totalAllowedUsers = tenant.AdditionalUsersRequested + tenant.Subscription.UsersAllowed;
                    var existingUsersCount = tenant.Users.Count();
                    return (existingUsersCount <= totalAllowedUsers);
                    return false;
        return false;

GatedActionLink – HtmlHelper extension

public static MvcHtmlString GatedActionLink(this HtmlHelper helper,
    string icon,
    string text,
    string actionName,
    string controllerName,
    GatedAction action,
    RouteValueDictionary routeValues = null,
    IDictionary<string, object> htmlAttributes = null)
    ControllerBase controllerBase = string.IsNullOrEmpty(controllerName) ? helper.ViewContext.Controller : helper.GetControllerByName(controllerName);
	ControllerContext controllerContext = new ControllerContext(helper.ViewContext.RequestContext, controllerBase);
    ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType());
    ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

    htmlAttributes = htmlAttributes ?? new Dictionary<string, object>();
    if (actionDescriptor == null)
        htmlAttributes.Add("disabled", "disabled");            

    return helper.ActionLinkWithIcon(icon, text, actionName, controllerName, routeValues, htmlAttributes);

And that’s it really. Now all I have to do is to decorate my action method like this:

[SubscriptionAction(Action = GatedAction.CreateUser)]
public async Task CreateUser()

and in my view the create action link would be like:

@Html.GatedActionLink("glyphicon glyphicon-plus", "create user", "CreateUser", "Manage", GatedAction.CreateUser, new RouteValueDictionary { { "area", "Users" } }, new Dictionary { { "class", "btn btn-default btn-xs" } })

And that’s all. We are sorted. I only update my database and rest is handled by my custom filter attribute and the html helper extension.