-
-
Save edubkendo/16967b2dd12daabdc95c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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