Skip to content

Instantly share code, notes, and snippets.

@alanpeabody
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save alanpeabody/b567bbdbcd6ad8c5ab4d to your computer and use it in GitHub Desktop.

Select an option

Save alanpeabody/b567bbdbcd6ad8c5ab4d to your computer and use it in GitHub Desktop.
Plug 101 - Part 2
defmodule Authenticate do
import Plug.Conn
def call(conn, _opts) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] -> authenticate(conn, token)
_ -> reject(conn, "Bearer token missing")
end
end
defp authenticate(conn, token) do
case User.find_by_token(token) do
nil -> reject(conn, "Invalid token - user not found")
user -> assign(conn, :current_user, user)
end
end
defp reject(conn, reason) do
conn
|> send_resp(401, reason)
|> halt
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment