geo-therminator/lib/geo_therminator/pump_api/auth/api.ex

58 lines
1.5 KiB
Elixir

defmodule GeoTherminator.PumpAPI.Auth.API do
alias GeoTherminator.PumpAPI.HTTP
alias GeoTherminator.PumpAPI.Auth
require Logger
@spec auth(String.t(), String.t()) :: {:ok, Auth.User.t()} | :error
def auth(username, password) do
url = Application.get_env(:geo_therminator, :api_auth_url)
req =
HTTP.req(:post, url, [], %{
username: username,
password: password
})
with {:ok, response} <- Finch.request(req, HTTP),
200 <- response.status,
{:ok, json} <- Jason.decode(response.body),
{:ok, valid_to, _} = DateTime.from_iso8601(json["tokenValidToUtc"]) do
token = %Auth.Token{
token: json["token"],
token_valid_to: valid_to
}
{:ok,
%Auth.User{
user_name: json["userName"],
email: json["email"],
first_name: json["firstName"],
last_name: json["lastName"],
culture: json["culture"],
eula_accepted: json["eulaAccepted"],
is_authenticated: json["isAuthenticated"],
time_zone: json["timeZone"],
token: token
}}
else
_ -> :error
end
end
@spec installations_info(Auth.User.t()) :: [Auth.InstallationInfo.t()]
def installations_info(user) do
url = Application.get_env(:geo_therminator, :api_installations_url)
req = HTTP.authed_req(user, :get, url)
{:ok, response} = Finch.request(req, HTTP)
json = Jason.decode!(response.body)
Enum.map(json["items"], fn item ->
%Auth.InstallationInfo{
id: item["id"]
}
end)
end
end