Best way to handle ownership of resource

Hi guys,

I am looking for a nice and generic way to check if current logged user is the owner of the resource he is trying to show / update / delete / …

In the application, every resource linked to a user has a field user_id matching the ID of the user that created it.

Is there a way to do this with a Plug ? Something that would look like :

  plug :owner_check when action in [:show]

  def show(conn, %{"id" => id}) do
    provisioned_device = Devices.get_provisioned_device!(id)
    render(conn, "show.html", provisioned_device: provisioned_device)

If logged user is owner, render the show.html page and if not, redirect to an error / 401 page.

Or should I just add a if == resource.user_id check in the show function? This doesn’t looks like really DRY and I am pretty sure there is a better way to do it but I can’t find it out.

Hello and welcome,

You might try Canada.

I use plugs to authorize user/roles, but if I need to check access with a resource, I would try to avoid loading data in the plug, and in the controller.

I have a dedicated module for this kind of authorization, which contains something like…

Authorization.check_access?(current_user, resource)

but it’s just a pure function, not a plug.