riverrun / openmaize

No longer maintained - was an Authentication library for Plug-based applications in Elixir
Other
206 stars 30 forks source link

How to exclude certain actions from authorization? #38

Closed jaimeiniesta closed 8 years ago

jaimeiniesta commented 8 years ago

In the examples it says that the way to authorize the actions in a controller is:

def action(conn, _), do: authorize_action conn, ["user"], __MODULE__

But this would apply it to all the actions. How can we exclude some actions so no authorization is required? For example, if you have a REST resource and you want all actions authorized, except for :show?

Or, if we wanted to authorize some actions for the user role, and some for the admin role in the same controller?

Thanks!

riverrun commented 8 years ago

If you want to exclude some actions, the easiest way is to use a plug, as in this example. The id_check plug, which is defined in the Welcome.Authorize module, is only called for the show, edit and update actions.

Overriding the default action function is one way of handling authorization, but you can just use custom plugs, or, as in this example, override the action function and use a custom plug.

Please let me know if any of this is unclear or you want me to go into more detail.

jaimeiniesta commented 8 years ago

Thanks! I've defined a custom plug like this, it works great:

# controllers/auth_required.ex
defmodule MyApp.AuthRequired do
  import Plug.Conn
  import Phoenix.Controller

  def init(opts) do
    opts
  end

  def call(conn, _opts) do
    if conn.assigns.current_user do
      conn
    else
      conn
      |> put_flash(:error, "Please log in.")
      |> redirect(to: "/login")
      |> halt()
    end
  end
end

# And then inside the controller where I want to restrict the :show action...
plug MyApp.AuthRequired when not action in [:show]
jaimeiniesta commented 8 years ago

On the topic of custom plugs for requiring login, just read this post that explains it really well, including how to test them:

https://robots.thoughtbot.com/testing-elixir-plugs