Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Chris McCord for How to restrict access to certain routes in Phoenix?

You would use a plug in the UserController. 0.4.x has no ability for conditionally plug s, but you could achieve what you want with something like:

defmodule MyApp.UserController do  use Phoenix.Controller  plug :authenticate, :admin  plug :action  def index(conn, _) do    render conn, "index"  end  def create(conn, params) do    # do the creating  end  ...  defp authenticate(conn, :admin) do    do_auth(conn, action_name(conn))  end  defp do_auth(conn, action) when action in [:create, :update, :destroy] do    if AdminAuth.authenticated?(conn) do      conn    else      halt conn    end  end  defp do_auth(conn, _action), do: connend

The changes coming soon in 0.5 will allow easier conditional plugs, i.e.:

defmodule MyApp.UserController do  use Phoenix.Controller  plug :authenticate, :admin when action in [:create, :update, :destroy]  def index(conn, _) do    render conn, "index"  end  def create(conn, params) do    # do the creating  end  ...  defp authenticate(conn, :admin) do    if AdminAuth.authenticated?(conn) do      conn    else      halt conn    end  endend

It's a good idea to keep your controllers for public/restricted access separate, so I would add an Admin.UserController like you made reference to for the restricted functionality.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>