Sunday, April 17, 2016

ASP.NET MVC Fine Grained Identity & Access Control - Part 2

In this series I will explain how I designed a generic claims based access control system ASP.NET MVC 5 with Identity 2.0.
In Part 1, I describe my approach and the initial database design. ASP.NET MVC Fine Grained Identity & Access Control - Part 1

In this Part 2, I will start laying foundation for the whole system with all the data models and a functional UI.

So far completed coding is in the GitHub repo:

First, I need to decide what functionality the UI should have.
  1. As a super admin, I need to be able to view the application resources from the UI. Add a description and search them.
  2. As a super admin, I need to be able to manage all the users in the system.
  3. As a super admin, I need to be able to manage global permissions
  4. As a super admin, I need to be able to manage user groups and group permissions
  5. As a super admin, I need to be able to manage user groups and group permissions

So, these are the list of things I need to be able to do within the system. There can be more, depending on the requirements. But I’m just trying to present the most basic way of doing things.

I also need a way to test things out within the UI. To do that, I need to be able to login with another less privileged user and see if everything I’ve blocked, stays blocked. Typing the URI manually, must not let the user view what’s hidden.

A tree structure for the application resources will display them nicely. If I could select the user group first, and then load the already given permissions and map them into the tree with little check-boxes on it, will give me an easier way to manage permissions for the group. (see the following image from WSO2 API Manager Permission Model)

WSO2 API Manager Permission Model

I can pre-define the types of exclusive rights in the system so that I can eliminate human error. Admins can select the right/claim and assign values to them.

These are my design considerations for now. As I keep developing the system, my decisions might change.

I’m going to start with a sample MVC-5 + WebAPI enabled project with Individual user accounts.

MVC + WebAPI + Individual User Accounts
I have removed all the bootrap and JQuery JS and CSS from the sample project and linked CDN supplied libraries instead. I just wanted to keep things clean.

I have created new MVC controllers and the models from my DB design.

Note that, I didn't run the application yet. If you run it, and register, the database will be created. I just like to setup the db with everything I want first.

Connecting the data models to my ApplicationDBContext.

using System;
using System.Data.Entity;
using System.Net.Mime;
using Microsoft.Ajax.Utilities;
using Microsoft.AspNet.Identity.EntityFramework;

namespace DinkLabs.ClaimsAuth.Web.Models
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        public IDbSet<Application> Application { get; set; }
        public IDbSet<ApplicationResource> ApplicationResource { get; set; }
        public IDbSet<ResourceGlobalPermission> ResourceGlobalPermission { get; set; }
        public IDbSet<ResourceRolePermission> ResourceRolePermission { get; set; }
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)

        public static ApplicationDbContext Create()
            return new ApplicationDbContext();

The final UI looks like this.

A few menu items are still missing, I'll be adding them on  Part 3.

Sunday, April 10, 2016

Why You Should Always Use Decorator Pattern

Life get easier when you have more reusable decorators and a good dependency injector.
image credits:

Years before I choose this programming/engineering career, I always wondered, how can I make something better? How can I make it work faster or efficiently? I'm no backyard scientist or whatever so basically, it was all just thinking and speculating. Running simulations in my head, kinda. Once I started programming, I was interested in making machines talk. "Knight Rider" was my inspiration. Talking cars!!! And then, I was super interested in learning all the mechanisms behind AI. I'm a fan of AI, taking over the world or not, I always wanted to build one. For some fucked up reason, I still can't even get a simple neural-net working. Sure, copy pasting works but what's the point. I suck at math, may be that's the reason. And, as with everything in life, we come up with excuses to either postpone something or completely give up and look the other way. I just never, completely gave up, I just postponed, until I find or read about a better way. As with everything else in nature, software is always evolving. Programming languages evolve, to make our life easier. Hardware evolves to make shit happen way faster than it was a few months ago.  AI tech evolves, to make machines think better.

I had read about the pattern of decorator. To decorate is to cover something ugly with something pretty or simple. I don't wanna go into all the technical definitions as to what the decorator pattern is. but, I'll just copy it from somewhere (Wikipedia).
In object-oriented programming, the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.[1] The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.[2]
It says something about Single Responsibility Principle, one of the SOLID principles in OOP. I saw the term SOLID a few years back and then I didn't understand shit. I thought, if it works, why the fuck would I wanna break it and put all the patterns and shit into my code, and make it so complex. Well, I was obviously stupid. As with all things, I did get past some of that stupidity, evolved into someone who appreciates the better ways of doing things.

Months ago, I have put the code to measure execution time, and parameter/result logging and bunch of other cross-cutting (logging, monitoring, caching, validation etc.) Stuff in the same method, and I was a fan of God classes, even though I felt something is not right, I just went with it. Time constraints and chats and just too lazy. I had replicated/copy-pasted the same code, on many places. and when I realize I am copying the same code, I would extract a method, with an 'Func' or 'Action' type parameter, and then I would put all the god logic in that method. Something stupid like this.

public int SaveContact(Contact contact)
 var st = new Stopwatch();
 Log.InfoFormat("saving customer params: {0}", contact.Json());

 if (contact.CustomerID == 0 || contact.UserID == 0)
  throw new ArgumentException("Customer ID or User ID is missing");
  using (var repo = DataServices.DataRepository<SMSContact>(UnitType.Contacts))
   var saved = contact.ID > 0
      ? repo.Update(contact)
      : repo.Add(contact);

   return saved.ID;
  Log.InfoFormat("saving customer took: {0}ms", st.ElapsedMilliseconds);

You might think, what's so stupid about this? Well, nothing is stupid, until you have so many method, doing the same logging/measuring/caching etc. behavior. It's just too much copying going around. Imagine, someday, you come across this super cool open source execution time measurement library and you decide you want to put it in all your methods, OR imagine someday you realize that, there's too much logging going on OR you don't really need the measurements and logging at all, OR imagine someday you decide you want an extra caching layer between your API and business rules or whatever. How many methods will you have to modify. Trust me, it's a very boring task. Been there, done that. Obviously, these apply to you only if you always wanna make yourself better. If you are the kinda person who would just hack it and get it working and not look at it again, then certainly, you are making your life and the one after you very miserable.

How would I get around this endless replicating code? An abstraction like the following.

protected static T Execute<T>(Func<T> codetoExecute)
 var st = new Stopwatch();
 Log.Info(m => m("[<{0}>] Scope Begin >>>>>>>", typeof(T).Name));
 T result;
  Log.Trace( "Executing method: " + codetoExecute.Method.Name);
  result = codetoExecute.Invoke();
 catch (AuthorizationValidationException ex)
  Log.Trace("<<<<<<< Scope Error : AuthorizationValidationException >>>>>>> " + ex.Message);
  throw new FaultException<AuthorizationValidationException>(ex, ex.Message);
 catch (FaultException ex)
  Log.Trace("<<<<<<< Scope Error : FaultException >>>>>>> " + ex.Message);
 catch (Exception ex)
  Log.Error("<<<<<<< Scope Error : Exception >>>>>>> " + ex.Message, ex);
  throw new FaultException(ex.Message);
 Log.Info(m => m("<<<<<<< [<{0}>] Scope End, time took: {0}ms", typeof(T).Name, st.ElapsedMilliseconds));
 return result;

Now, we can call do our stuff like as follows.

public int SaveContact(Contact contact)
     return Execute(() =>
          // do stuff

Problems solved, no more copy pasting. I was fine with this way of coding until I came across this blog post, by the author of "Simple Injector". One day I wanted a better way of handling the hotel booking flow I was working on and I thought may be Command Query pattern or something will do the magic. I went on a quest to find out what I can do better. The great oracle, the pointed me towards this blog post. Meanwhile... on the command side of my architecture .

This article describes how a single interface can transform the design of your application to be much cleaner, and more flexible than you ever thought possible.
This headline got me hooked, I read on. And then I read all his blog posts. This was exactly what I was looking for, to a different problem. Nothing pointed me towards a better search mechanism for the problem I had. Who cares, it already works. This was something new and I wanted to try it out. Decorators!!

However, the command and query patterns described in the blog didn't quite fill my needs. Because, commands usually alter state. It doesn't return anything, while queries, doesn't change anything, it just returns whatever the shit you're looking for. I wanted a way to alter state and return shit back to me. Thus, instead of "void" why not return "T"?

There might be better ways of doing the command and query work. One possibility I can think of is do the command in a background task and query when the task is complete. I don't see the need to go into such lengths yet! maybe my POV might change, in the near future, thanks to another brilliant person.

I understand no one seem to share these code online. I had to do a lot of research to get to this point. That's what experience is all about, if everything is given to you on a silver plate, you will be just as dumb as a monkey. You need to do the worst and do your research and evolve your skills into something better.

Damn, this might be the longest blog post I've created. Sunday evenings!

So, this is how I do the decorations of my travel booking engine, especially the command side.

As you can see, the 'CreateBookingCommandHandler' is my command handler implementation. I haven't put any logging code there. nor error handling. It just deals with calling the validation provider (I use FluentValidation btw) and the 'IBookingPreProcessor' handles all the shit I do after a successful validation. And then I save the booking and return the results.

Just like the 'MeasuringCommandHandlerDecorator' I can create whatever decorator I want to use, and plug them in my injector configuration, as follows. I can turn on or off (Comment/Un-comment) any decorator I want, anytime I want and it won't even affect the system, despite the slight performance gains.

This is how I come to love having decorators throughout the system. Reach out to me if you have any questions regarding these or for any corrections I should do. Once again, as with all things, If I come across a better way of doing these, (apart from AOP), I'll update the post.