update
This commit is contained in:
parent
e2967f68b2
commit
ef2a6c41b4
39 changed files with 2349 additions and 30 deletions
39
lib/zoeyscomputer_web/plugs/api_authentication.ex
Normal file
39
lib/zoeyscomputer_web/plugs/api_authentication.ex
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
defmodule ZoeyscomputerWeb.Plugs.ApiAuthentication do
|
||||
alias Zoeyscomputer.ApiKeys
|
||||
import Plug.Conn
|
||||
|
||||
def init(opts), do: opts
|
||||
|
||||
def call(conn, _opts) do
|
||||
case get_auth_token(conn) do
|
||||
nil ->
|
||||
handle_unauthorized(conn)
|
||||
|
||||
token ->
|
||||
case ApiKeys.authenticate_api_key(token) do
|
||||
nil ->
|
||||
handle_unauthorized(conn)
|
||||
|
||||
user ->
|
||||
conn
|
||||
|> assign(:current_user, user)
|
||||
|> assign(:authenticated_with_api_key, true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp get_auth_token(conn) do
|
||||
case get_req_header(conn, "authorization") do
|
||||
["Bearer " <> token] -> token
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_unauthorized(conn) do
|
||||
conn
|
||||
|> put_status(:unauthorized)
|
||||
|> Phoenix.Controller.put_view(ZoeyscomputerWeb.ErrorJSON)
|
||||
|> Phoenix.Controller.render(:"401")
|
||||
|> halt()
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue