Skip to content

Instantly share code, notes, and snippets.

@edubkendo
Forked from j-mcnally/gist:196bc5eaf055e8eb5184
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edubkendo/16967b2dd12daabdc95c to your computer and use it in GitHub Desktop.
Save edubkendo/16967b2dd12daabdc95c to your computer and use it in GitHub Desktop.
defmodule Koncur.AuthenticationPlug do
alias Plug.Conn
alias Phoenix.Status
alias Phoenix.Controller.Errors
alias Poison, as: JSON
import Phoenix.Controller.Connection
import Plug.Conn
import Ecto.Query, only: [from: 2]
def init(opts), do: opts
def call(conn, _), do: authenticate(conn)
def authenticate(conn) do
auth_header = Conn.get_req_header(conn, "authorization")
auth_header = to_string(auth_header)
parts = String.split(auth_header, " ")
token_opts = to_string(Enum.at(parts, 1))
parts = String.split(token_opts, ",")
option = Enum.find parts, fn(n) ->
parts = String.split(to_string(n), "=")
key = Enum.at(parts, 0)
value = Enum.at(parts, 1)
key == "token"
end
token = Enum.at(String.split(to_string(option), "="), 1)
if token != "" do
query = from(u in User, where: u.github_token == ^(token), select: u)
user = Enum.at(Repo.all(query), 0)
end
user = nil
if user do
assign_private(conn, :authentication_current_user, user)
else
json(conn, 401, JSON.encode!(%{error: "Unauthorized"})) |> halt
end
end
end
defmodule Koncur.Api.V1.RepoController do
use Phoenix.Controller
alias Koncur.Router
plug Koncur.AuthenticationPlug
def index(conn, _params) do
user = conn.private[:authentication_current_user]
my_repos = [%{id: 1, name: "Test Repo"}]
json conn, JSON.encode!(%{repos: my_repos})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment