Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for doing authorization in repository layer of MVC application

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?

like image 264
Eric Avatar asked Feb 15 '13 18:02

Eric


1 Answers

Or is it a bad idea to handle it in the repository layer?

I think the Controller is a better place for your authorization. Let the repository be a gateway to the data and the controller be a gatekeeper to your application. I'd expect to see authorization/authentication logic as early in the life-cycle as possible.

like image 126
Big Daddy Avatar answered Oct 17 '22 07:10

Big Daddy