Current section

Files

Jump to
mpx lib mpx authentication mpx_authentication_body.ex
Raw

lib/mpx/authentication/mpx_authentication_body.ex

defmodule Mpx.Authentication.Body do
@moduledoc """
Defines types and functions for dealing with authentication body and parameters.
"""
import Mpx.Config
@username Application.get_env(:mpx, :mp_username)
@password Application.get_env(:mpx, :mp_password)
@client_id Application.get_env(:mpx, :mp_client_id)
@client_secret Application.get_env(:mpx, :mp_client_secret)
@typedoc """
What is included in a post request when authenticating
"""
@type t :: [username: String.t, password: String.t, client_id: String.t, client_secret: String.t] | [client_id: String.t, client_secret: String.t]
@doc """
Build a x-www-form-urlencoded query string to send in the authentication request to MP
If called with an empty list, it will look in the configuration for:
```
config :mpx,
mp_username: "user",
mp_password: "password",
mp_client_id: "client",
mp_client_secret: "shhh"
```
If called with just the client_id and client_secret, we assume that you are trying
tos authorize a client, so the grant_type is specified as client_credentials
## Examples
iex>Mpx.Authentication.Body.get_auth_body(username: "user", password: "pass", client_id: "client", client_secret: "secret")
"username=user&password=pass&client_id=client&client_secret=secret&grant_type=password"
iex>Mpx.Authentication.Body.get_auth_body([]) #pulls data from the configuration
"username=user&password=password&client_id=client&client_secret=shhh&grant_type=password"
iex>Mpx.Authentication.Body.get_auth_body(client_id: "client", client_secret: "password")
"client_id=client&client_secret=password&grant_type=client_credentials"
"""
@spec get_auth_body(t | nil) :: String.t
def get_auth_body(client_id: client_id, client_secret: client_secret) do
["client_id=#{client_id}",
"&client_secret=#{client_secret}",
"&grant_type=client_credentials"]
|> Enum.join
end
def get_auth_body(username: username, password: password, client_id: client_id, client_secret: client_secret) do
["username=#{URI.encode_www_form(username)}",
"&password=#{URI.encode_www_form(password)}",
"&client_id=#{URI.encode(client_id)}",
"&client_secret=#{URI.encode_www_form(client_secret)}",
"&grant_type=password"]
|> Enum.join
end
def get_auth_body([]) do
get_auth_body(username: from_config(:mp_username, @username),
password: from_config(:mp_password, @password),
client_id: from_config(:mp_client_id, @client_id),
client_secret: from_config(:mp_client_secret, @client_secret))
end
def get_auth_body(opts), do: raise "Wrong arguments passed to authenticate. Please setup your configuration correctly or pass a keyword list in the with username, password, client_id and client_secret"
end