Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 29 additions & 10 deletions lib/wait_list_web/plugs/authorize.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,51 @@ defmodule WaitListWeb.Authorize do
import Phoenix.Controller
import WaitList.Authorization
alias WaitListWeb.Router.Helpers, as: Routes

def init(opts), do: opts

def call(conn, opts) do
role = conn.assigns.current_user.role
resource = Keyword.get(opts, :resource)
action = action_name(conn)

check(action, role, resource)
|> maybe_continue(conn)
end

defp maybe_continue(true, conn), do: conn

defp maybe_continue(false, conn) do
conn
|> put_flash(:error, "You're not authorized to do that!")
|> redirect(to: Routes.page_path(conn, :index))
|> halt()
end

defp check(:index, role, resource) do

# Old Code
# defp check(:index, role, resource) do
# can(role) |> read?(resource)
# end

"""
Hi Mr.Moore
I found a bug
When i use `mix phx.gen.html <Any> ` generate html/controller/view and schema.

In the `Old Code` ,if i click the `Save` button, that will have two flashes and redirect to the index page :
- "Article created successfully"
- "You're not authorized to do that!"

Because the action of `show` is missing.
"""

# New Code
defp check(action, role, resource) when action in [:show, :index] do
can(role) |> read?(resource)
end


#

defp check(action, role, resource) when action in [:new, :create] do
can(role) |> create?(resource)
end
Expand All @@ -41,5 +61,4 @@ defmodule WaitListWeb.Authorize do
end

defp check(_action, _role, _resource), do: false

end
end