Skip to content

Instantly share code, notes, and snippets.

@mtanzi
Last active August 29, 2015 14:22
Show Gist options
  • Save mtanzi/adc66e8fdd6fc5dbd682 to your computer and use it in GitHub Desktop.
Save mtanzi/adc66e8fdd6fc5dbd682 to your computer and use it in GitHub Desktop.
Plug used inside the phoenix controller to extract the encoded credential from the `authorization` header
defmodule MyApp.Plugs.AuthHeaders do
import Plug.Conn
import Phoenix.Controller
require Logger
@doc """
This Plug extract the `authentication` header from the connnaction
and extrac the tocken containing the credentials. If the header has
ther correct format it calls the `validate` function otherwise it
will return a 401 error.
"""
def verify_user_authentication(conn) do
case get_req_header(conn, "authorization") do
[<<"Basic ", token::binary>>] -> validate(conn, token)
_ -> send_bad_request(conn)
end
end
@doc """
Validate does receive a connection and the credentials encoded in base64. it
will call `decode_credentials` to exract the data and lookup for the user
in the database. If the user is present it send a 201 with the user data,
otherwise it will return an error.
"""
defp validate(conn, token) do
[email, password] = decode_credentials(token)
user = FlycatcherPhoenix.User.authenticate(%{ "email" => email, "password" => password })
if user do
render conn, "show.json", data: user
else
send_bad_request(conn)
end
end
defp send_bad_request(conn) do
conn
|> send_resp(401, Poison.encode!(%{error: "user not authorised"}))
|> halt
end
@doc """
This is an helper to extract the credentials from the token. The data decode
is a string with the following format `email:password`. I will split the
result and retun it in a list
"""
defp decode_credentials(token) do
token
|> :base64.decode
|> String.split(":")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment