Closed jaimeiniesta closed 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.
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]
On the topic of custom plugs for requiring login, just read this post that explains it really well, including how to test them:
In the examples it says that the way to authorize the actions in a controller is:
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 theadmin
role in the same controller?Thanks!