schrockwell / bodyguard

Simple authorization conventions for Phoenix apps

Home Page:https://hexdocs.pm/bodyguard/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

permit! not raising a Bodyguard.NotAuthorizedError

abitdodgy opened this issue · comments

I'm getting a different error than what I expect when I use permit!:

defmodule MyAppWeb.Admin.LinkController do
  action_fallback MyAppWeb.FallbackController
  plug :set_and_authorize_post when not action in [:scrape]

  def set_and_authorize_post(%{params: %{"post_id" => post_id}} = conn, _) do
    post = Media.get_post!(post_id)
    Bodyguard.permit!(MyApp.Media, :manage_links, conn.assigns.current_user, post)
    assign(conn, :post, post)
  end

The error is:

protocol Enumerable not implemented for %MyApp.Media.Post{__meta__: #Ecto.Schema.Metadata<:loaded, "posts">, ...

To get around this issue, I'm doing this:

  def set_and_authorize_post(%{params: %{"post_id" => post_id}} = conn, _) do
    post = Media.get_post!(post_id)
    case Bodyguard.permit?(MyApp.Media, :manage_links, conn.assigns.current_user, post) do
      true ->
        assign(conn, :post, post)
      false ->
        conn
        |> put_status(403)
        |> render(MyAppWeb.ErrorView, "403.html")
        |> halt()
    end
  end

Good catch. The problem was that permit! was expecting that post argument to be an options keyword list (something like [post: post], which is an old library requirement that I must have not removed from that function.

Anyway, I've published a fix. Please update your Bodyguard dependency to v2.2 using mix deps.update bodyguard.

That update solved it. Thanks.