geo-therminator/lib/geo_therminator/pump_api/auth/api.ex
2021-11-07 11:01:39 +02:00

60 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()) :: Auth.User.t()
def auth(username, password) do
url = Application.get_env(:geo_therminator, :api_auth_url)
req =
HTTP.req(:post, url, [], %{
username: username,
password: password
})
{:ok, response} = Finch.request(req, HTTP)
if response.status != 200 do
raise "Request error #{response.status}: #{inspect(response.body)}"
end
json = Jason.decode!(response.body)
{:ok, valid_to, _} = DateTime.from_iso8601(json["tokenValidToUtc"])
token = %Auth.Token{
token: json["token"],
token_valid_to: valid_to
}
%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
}
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["installations"], fn item ->
%Auth.InstallationInfo{
id: item["id"]
}
end)
end
end