I have a Windows authenticated MVC application with a repository layer. All interaction by the controller with the database is done through the repository. Each controller has a reference to the repository:
public class PostController : Controller
{
private Repository db = new Repository();
[HttpPost]
public ActionResult DeletePost(int id)
{
// Authorize that the user is allowed to delete this post...
db.DeletePost(id);
}
}
My question is whether there is a good way to move my authorization logic into the repository layer. I’d like the Repository.DeletePost() function to refuse to delete posts that were not created by the authenticated user. The problem is that my repository does not know who the authenticated user is. The controller knows (via Controller.User).
Passing the Controller.User into the Repository constructor doesn’t work, because the Controller.User is apparently not defined at the time when the constructor is called.
How can I inform the Repository of who the authenticated user is? Would it be best to just construct the Repository within each action? Or is it a bad idea to handle it in the repository layer?
Good suggestions from both @BigDaddy and @ChrisPratt.
I ended up solving this by creating a base controller, similar to this answer. My base controller class looks like:
All of my controllers inherit from this class, and have built-in access to a lazy-loaded
Repositorythat has a reference to the currently authenticated user.