Packages

Integrates with RAD²'s API Auth

Retired package: Security issue - Private package

Current section

Files

Jump to
rad2_auth lib rad2 auth.ex
Raw

lib/rad2/auth.ex

defmodule Rad2.Auth do
@moduledoc """
Main module, responsible to validate JWT tokens.
"""
require Logger
alias Rad2.Auth.Company
@type ok_return :: {:ok, list(Company.t())}
@type err_return :: {:error, atom()}
@target Application.get_env(:rad2_auth, :server_url)
@doc "Performs JWT validation"
@spec validate_jwt(String.t()) :: ok_return | err_return
def validate_jwt(nil),
do: {:error, :invalid_token}
def validate_jwt(token),
do: validate_jwt(Mix.env(), token)
if Mix.env() == :test do
def validate_jwt(:test, token) do
case String.split(token, ".") do
[_, _, "AUTHORIZE"] ->
{:ok, [Company.new(%{
"id" => "3d810122-c18c-45ec-b233-3b2a82311e4c",
"name" => "RADSQUARE LTDA",
"document" => "31418481000183"
})]}
_another_result ->
{:error, :unauthorized}
end
end
end
def validate_jwt(_env, token) do
headers = [
{"authorization", "bearer #{token}"}
]
target =
case System.get_env("RAD2AUTH_URL") do
nil -> "#{@target}/v1/companies"
target -> "#{target}/v1/companies"
end
case HTTPoison.get(target, headers) do
{:ok, %{status_code: 200, body: body}} ->
Jason.decode(body)
|> decode_body()
{:ok, %{status_code: 401}} ->
{:error, :unauthorized}
{:ok, %{status_code: code}} ->
Logger.error "Receive invalid response code #{code}"
{:error, :unauthorized}
{:error, %HTTPoison.Error{reason: reason}} ->
Logger.error "Error #{reason} when attempt validate token"
{:error, :communication_error}
end
end
defp decode_body({:ok, %{"entries" => companies}}) do
{:ok, Enum.map(companies, &Company.new/1)}
end
defp decode_body({:error, reason}),
do: {:error, {:json_decode, reason}}
end