5

In my opinion this is not a duplicate of How to get current user in Asp.Net MVC.

I am trying to figure out how to access the Current User from an ASP.NET MVC Model in a manner that is easy to unit test. The models are LINQ to SQL entities that are generated by SqlMetal.

The reason I think I need to know the Current User in the Model is because I want to restrict access to certain properties / methods based on that user's privileges.

I am open to adopting an alternative design and making whatever changes are necessary to implement this in a clean, unit test friendly manner.

Community
  • 1
  • 1
Chris Shouts
  • 5,377
  • 2
  • 29
  • 40

3 Answers3

5

Managing permissions and restricting access to properties sounds like a job for the controller. The model's single responsibility is to store data, not to know about or manage users and permissions. So, in short, you don't need to get the current user in the model.

kevingessner
  • 18,559
  • 5
  • 43
  • 63
  • Not sure I agree with this. Sometimes the data to be retrieved depends on the user/role that is making the request. Will you put that logic in the controller? – Hector Correa Dec 21 '10 at 15:49
  • @Hector That logic belongs in the controller (or repository or service), whatever you call the entity that loads data. – kevingessner Dec 21 '10 at 15:56
  • The controller should be responsible for telling the model what it can do if that's what needs to be done. The model should be plain, dumb, with no logic... but I dig delegates in models a good bit. – hunter Dec 21 '10 at 16:09
  • per your advice I am moving this logic out of the Model and into a service. Thanks for your help and props for the link to c2. – Chris Shouts Dec 21 '10 at 16:56
2

I've always created new instances of my service classes for each instance of the controller. Given that, you can simply pass in the current user to the service constructor to make it available to the rest of your model. If you expose the current user as a property in your service interfaces, you can easily mock it out for testing.

MikeWyatt
  • 7,842
  • 10
  • 50
  • 71
0

I would Define a IUserService Interface with a GetUser method that would return a User Object and then define two implementations one for the actual application and one for a test scenario.

Chandu
  • 81,493
  • 19
  • 133
  • 134