api specs
This commit is contained in:
51
phoenix/lib/shooting_event_phx/auth.ex
Normal file
51
phoenix/lib/shooting_event_phx/auth.ex
Normal file
@@ -0,0 +1,51 @@
|
||||
defmodule ShootingEventPhx.Auth do
|
||||
@moduledoc false
|
||||
alias ShootingEventPhx.Auth.SessionStore
|
||||
|
||||
def admin_user, do: System.get_env("ADMIN_USER", "datwyler")
|
||||
def admin_pass, do: System.get_env("ADMIN_PASS", "datwyler")
|
||||
|
||||
def verify_admin(username, password) do
|
||||
u = username |> to_string() |> String.trim()
|
||||
p = password |> to_string() |> String.trim()
|
||||
|
||||
if u == "" or p == "" do
|
||||
false
|
||||
else
|
||||
secure_compare(u, admin_user()) and secure_compare(p, admin_pass())
|
||||
end
|
||||
end
|
||||
|
||||
def bearer_token(conn) do
|
||||
conn
|
||||
|> Plug.Conn.get_req_header("authorization")
|
||||
|> List.first()
|
||||
|> parse_bearer_token()
|
||||
end
|
||||
|
||||
def admin_request?(conn) do
|
||||
case bearer_token(conn) do
|
||||
nil -> false
|
||||
token -> SessionStore.validate_token(token)
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_bearer_token(nil), do: nil
|
||||
|
||||
defp parse_bearer_token(header) do
|
||||
value = String.trim(header || "")
|
||||
|
||||
if String.starts_with?(String.downcase(value), "bearer ") do
|
||||
token = value |> String.slice(7..-1//1) |> String.trim()
|
||||
if token == "", do: nil, else: token
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp secure_compare(left, right) do
|
||||
Plug.Crypto.secure_compare(left, right)
|
||||
rescue
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user