Meji Meji - 1 month ago 15
reST (reStructuredText) Question

What's the alternative of before_filter from Rails in Phoenix/Elixir?

In my Phoenix application, I have a pipe and scope "api"

pipeline :api do
plug(:accepts, ["json"])
end


scope "/api" .....
# .....
end


How can I protect it by an API Key which is passed through a special header? That is, I'd like something like this:

defmodule MyApp.MyController do
use MyApp.Web, :controller

:before_filter :authenticate_user_by_api_key!


def authenticate_user_by_api_key!(conn, params) do
# check if a header exists and key is valid
end
end


I'm planning on validating a header. How can I do that without relying on any third-party libraries?

Also. If I wanted to use a module instead of a single function, how would I do that?

Answer

Local Plug

If it's a local method, you can simply use the plug construct within the controller.

defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug :authenticate_user_by_api_key!


  defp authenticate_user_by_api_key!(conn, params) do
    # Authenticate or something
  end
end

See this answer and read more about Plugs here.


Module Plug

If you'd like to call the function from a Module, your module must export the init/1 and call/2 methods:

defmodule MyApp.Plugs.Authentication do
  import Plug.Conn

  def init(default), do: default

  def call(conn, default) do
    # Check header for API Key
  end
end

And use it like this in your controller:

defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug MyApp.Plugs.Authentication

  # Controller Methods
end

Read the Phoenix Guide on Module Plugs for more details.

Comments