1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
defmodule Mix.Tasks.Ovh do
@shortdoc "Create a new application and new credentials for accessing ovh api"
@moduledoc Module.concat(__MODULE__, Docs).moduledoc()
use Mix.Task
alias ExOvh.Defaults
@default_headers [{"Content-Type", "application/json; charset=utf-8"}]
@default_options [ timeout: 30000, recv_timeout: (60000 * 1) ]
@default_name "ex_ovh"
@default_description "ex_ovh application"
@default_redirect_uri ""
# Public
def run(args) do
opts_map = parse_args(args)
IO.inspect(opts_map, pretty: :true)
Mix.Shell.IO.info("")
Mix.Shell.IO.info("The details in the map above will be used to create the ovh application.")
Mix.Shell.IO.info("")
if Mix.Shell.IO.yes?("Proceed?") do
HTTPoison.start
opts_map = parse_args(args)
message = get_credentials(opts_map)
|> remove_private()
|> create_or_update_env_file()
|> print_config()
Mix.Shell.IO.info(message)
Mix.Shell.IO.info("")
Mix.Shell.IO.info("Update the environment variables and you're done''")
Mix.Shell.IO.info("")
Mix.Shell.IO.info("One way to update the environment variables is to run the command: ")
Mix.Shell.IO.info("")
Mix.Shell.IO.info("source .env")
end
end
##########################
# Private
#########################
defp parse_args(args) do
{opts, _, _} = OptionParser.parse(args)
{_opts, opts_map} = opts
|> has_required_args()
|> parsers_login()
|> parsers_password()
|> parsers_endpoint()
|> parsers_api_version()
|> parsers_redirect_uri()
|> parsers_app_name()
|> parsers_app_desc()
|> parsers_access_rules()
|> parsers_client_name()
opts_map
end
defp has_required_args(opts) do
login = Keyword.get(opts, :login, :nil)
if login == :nil do
raise "Task requires login argument"
end
password = Keyword.get(opts, :password, :nil)
if password == :nil do
raise "Task requires password argument"
end
{opts, %{}}
application_name = Keyword.get(opts, :appname, :ex_ovh)
if application_name == :nil do
raise "Task requires appname argument"
end
{opts, %{}}
end
defp parsers_login({opts, acc}), do: {opts, Map.merge(acc, %{login: Keyword.fetch!(opts, :login)}) }
defp parsers_password({opts, acc}), do: {opts, Map.merge(acc, %{ password: Keyword.fetch!(opts, :password)}) }
# defp parsers_app_name({opts, acc}), do: {opts, Map.merge(acc, %{ application_name: Keyword.fetch!(opts, :appname)}) }
defp parsers_endpoint({opts, acc}) do
endpoint = Keyword.get(opts, :endpoint, :nil)
endpoint =
case endpoint do
:nil -> "ovh-eu"
_ -> endpoint
end
{opts, Map.merge(acc, %{ endpoint: endpoint }) }
end
defp parsers_api_version({opts, acc}) do
api_version = Keyword.get(opts, :apiversion, :nil)
api_version =
case api_version do
:nil -> "1.0"
_ -> api_version
end
{opts, Map.merge(acc, %{ api_version: api_version }) }
end
defp parsers_redirect_uri({opts, acc}) do
redirect_uri = Keyword.get(opts, :redirecturi, @default_redirect_uri)
{opts, Map.merge(acc, %{ redirect_uri: redirect_uri }) }
end
defp parsers_client_name({opts, acc}) do
client_name = Keyword.get(opts, :clientname, :nil)
{opts, Map.merge(acc, %{ client_name: client_name }) }
end
defp parsers_app_name({opts, acc}) do
application_name = Keyword.get(opts, :appname, @default_name)
application_name =
case application_name do
:nil -> "ex_ovh"
_ -> application_name
end
{opts, Map.merge(acc, %{ application_name: application_name }) }
end
defp parsers_app_desc({opts, acc}) do
application_description = Keyword.get(opts, :appdescription, :nil)
application_description =
case application_description do
:nil -> Keyword.get(opts, :appname, @default_description)
_ -> application_description
end
{opts, Map.merge(acc, %{ application_description: application_description }) }
end
defp parsers_access_rules({opts, acc}) do
access_rules = Keyword.get(opts, :accessrules, :nil)
access_rules =
if access_rules == :nil do
Defaults.access_rules()
else
String.split(access_rules, "::")
|> Enum.map(fn(method_rules) ->
[method, paths] = String.split(method_rules, "-")
{method, paths}
end)
|> Enum.reduce([], fn({method, concat_paths}, acc) ->
paths = concat_paths
|> String.lstrip(?[)
|> String.strip(?]) #rstrip has a bug but fixed in master (01/02/2016)
|> String.split(",")
new_rules = Enum.filter_map(paths,
fn(path) -> path !== "" end,
fn(path) ->
%{
method: String.upcase(method),
path: path
}
end)
List.insert_at(acc, -1, new_rules)
end)
|> List.flatten()
end
{opts, Map.merge(acc, %{access_rules: access_rules}) }
end
defp get_app_create_page(opts_map) do
Og.context(__ENV__, :debug)
method = :get
uri = Defaults.endpoints()[opts_map[:endpoint]] <> Defaults.create_app_uri_suffix()
body = ""
headers = []
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
Map.get(resp, :body)
end
defp get_create_app_inputs(resp_body) do
Og.context(__ENV__, :debug)
inputs = Floki.find(resp_body, "form input")
|> List.flatten()
if Enum.any?(inputs, fn(input) -> input == [] end), do: raise "Empty input found"
inputs
end
defp build_app_request(inputs, %{login: login, password: password} = opts_map) do
Og.context(__ENV__, :debug)
{acc, _index, _max} =
Enum.reduce(inputs, {"", 1, Enum.count(inputs)}, fn({"input", input, _}, acc) ->
name = :proplists.get_value("name", input)
value = ""
case name do
"nic" ->
value = login
"password" ->
value = password
"applicationName" ->
value = opts_map.application_name
"applicationDescription" ->
value = opts_map.application_description
_ ->
raise "Unexpected input"
end
param = name <> "=" <> value
{acc, index, max} = acc
if index == max do
acc = acc <> param
else
acc = acc <> param <> "&"
end
{acc, index + 1, max}
end)
acc
end
defp send_app_request(req_body, opts_map) do
Og.context(__ENV__, :debug)
method = :post
uri = Defaults.endpoints()[opts_map[:endpoint]] <> Defaults.create_app_uri_suffix()
body = req_body
headers = [{"Content-Type", "application/x-www-form-urlencoded"}]
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
# Error checking
cond do
String.contains?(resp.body, msg = "There is already an application with that name for that Account ID") ->
raise(msg <> ", try removing the old application first using the ovh api console or just create a new one.")
String.contains?(resp.body, msg = "Invalid account/password") ->
raise(msg <> ", try adding '-ovh' to the end of the login")
String.contains?(resp.body, "Application created") ->
resp.body
true ->
raise "unknown error"
end
end
defp get_application_secret(body), do: Map.get(extract(body), "secret")
defp get_application_key(body), do: Map.get(extract(body), "key")
defp get_application_name(body), do: Map.get(extract(body), "name")
defp get_application_description(body), do: Map.get(extract(body), "description")
defp extract(body) do
Floki.find(body, "pre")
|> Enum.map(fn({"pre", [], [val]}) -> val end)
|> Enum.map(fn(ext) ->
case ext do
{key, _, [val]} ->
{key, val}
val when is_binary(val) ->
if String.length(val) > 20 do
{"secret", val}
else
{"key", val}
end
end
end)
|> Enum.into(%{})
end
defp get_consumer_key(%{access_rules: access_rules, redirect_uri: redirect_uri} = opts_map) do
Og.context(__ENV__, :debug)
method = :post
uri = Defaults.endpoints()[opts_map[:endpoint]] <> opts_map[:api_version] <> Defaults.consumer_key_suffix()
body = %{ accessRules: access_rules, redirection: redirect_uri } |> Poison.encode!()
headers = Map.merge(Enum.into(@default_headers, %{}), Enum.into([{"X-Ovh-Application", opts_map[:application_key]}], %{})) |> Enum.into([])
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
body = Poison.decode!(Map.get(resp, :body))
{Map.get(body, "consumerKey"), Map.get(body, "validationUrl")}
end
defp bind_consumer_key_to_app({ck, validation_url}, opts_map) do
Og.context(__ENV__, :debug)
method = :get
uri = validation_url
body = ""
headers = []
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
Map.get(resp, :body)
|> get_bind_ck_to_app_inputs()
|> build_ck_binding_request(opts_map)
|> send_ck_binding_request(validation_url, ck)
end
defp get_bind_ck_to_app_inputs(resp_body) do
Og.context(__ENV__, :debug)
inputs = Floki.find(resp_body, "form input") ++
Floki.find(resp_body, "form select")
|> List.flatten()
|> Enum.filter(fn({_type, input, _options}) ->
:proplists.get_value("name", input) !== "identifiant"
end)
if Enum.any?(inputs, fn(input) -> input == [] end), do: raise "Inputs should not be empty"
inputs
end
defp build_ck_binding_request(inputs, %{login: login, password: password} = _opts_map) do
Og.context(__ENV__, :debug)
Enum.reduce(inputs, "", fn({type, input, _options}, acc) ->
{name_val, value} =
cond do
type == "input" && {"name", "credentialToken"} in input ->
name_val = :proplists.get_value("name", input)
value = :proplists.get_value("value", input)
{name_val, value}
type == "input" && {"type", "password"} in input && {"placeholder", "Password"} in input ->
name_val = :proplists.get_value("name", input)
value = password
{name_val, value}
type == "input" && {"type", "text"} in input && {"placeholder", "Account ID or email address"} in input ->
name_val = :proplists.get_value("name", input)
value = login
{name_val, value}
type == "select" && {"name", "duration"} in input ->
name_val = :proplists.get_value("name", input)
value = "0"
{name_val, value}
true ->
# raise "Unexpected input"
Og.log("Ignoring unexpected input " <> inspect(input), __ENV__, :warn)
{:no_name, :no_val}
end
case {name_val, value} do
{:no_name, :no_val} -> acc
{name_val, value} -> acc <> name_val <> "=" <> value <> "&"
end
end)
|> String.trim_trailing("&")
end
defp send_ck_binding_request(req_body, validation_url, ck) do
Og.context(__ENV__, :debug)
method = :post
uri = validation_url
body = req_body
headers = [{"Content-Type", "application/x-www-form-urlencoded"}]
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
case check_for_successful_binding(resp, validation_url, ck) do
{:ok, :handle_2fa} -> handle_2fa(resp.body, validation_url, ck)
{:ok, ck} -> ck
{:error, msg} -> raise msg
end
end
def check_for_successful_binding(resp, validation_url, ck) do
Og.context(__ENV__, :debug)
error_msg1 = "Failed to bind the consumer token to the application. Please try to validate the consumer token manually at #{validation_url}"
error_msg2 = "Invalid validity period entered for the consumer token. Please try to validate the consumer token manually at #{validation_url}"
cond do
String.contains?(resp.body, "Invalid validity") -> {:error, error_msg2}
String.contains?(resp.body, "The token is now valid, it can be used in the application") -> {:ok, ck}
String.contains?(resp.body, "Your token is now valid, you can use it in your application") -> {:ok, ck}
String.contains?(resp.body, "token is now valid") -> {:ok, ck}
String.contains?(resp.body, "You have activated the double factor authentication") -> {:ok, :handle_2fa}
# presume the validation was successful if redirected to redirect uri
resp.status_code == 302 && (resp.headers |> Enum.into(%{}) |> Map.has_key?("Location")) -> {:ok, ck}
true -> {:error, "Unexpected error " <> error_msg1}
end
end
defp build_2fa_request(resp_body) do
Og.context(__ENV__, :debug)
Mix.Shell.IO.info("You have activated 2FA on your OVH account, you need to verify your account via 2FA")
Floki.find(resp_body, "form input")
|> Enum.reduce("", fn({type, input, _options}, acc) ->
{name_val, value} =
cond do
type == "input" && {"name", "sessionId"} in input ->
name_val = :proplists.get_value("name", input)
value = :proplists.get_value("value", input)
{name_val, value}
type == "input" && {"name", "credentialToken"} in input ->
name_val = :proplists.get_value("name", input)
value = :proplists.get_value("value", input)
{name_val, value}
type == "input" && {"name", "duration"} in input ->
name_val = :proplists.get_value("name", input)
value = "0"
{name_val, value}
type == "input" && {"type", "number"} in input && {"placeholder", "Code"} in input ->
name_val = :proplists.get_value("name", input)
# Get value from shell asking user for 2FA code.
value = Mix.Shell.IO.prompt("Please enter *promptly* the 2FA (2 Factor Authentication) code generated by your mobile application:")
|> String.trim()
Mix.Shell.IO.info("The code #{value} will be sent as the 2FA code")
{name_val, value}
true ->
# raise "Unexpected input"
Og.log("Ignoring unexpected input " <> inspect(input), __ENV__, :warn)
{:no_name, :no_val}
end
case {name_val, value} do
{:no_name, :no_val} -> acc
{name_val, value} -> acc <> name_val <> "=" <> value <> "&"
end
end)
|> Kernel.<>("otpMethod" <> "=" <> "totp")
end
defp handle_2fa(resp_body, validation_url, ck) do
Og.context(__ENV__, :debug)
method = :post
uri = validation_url
body = build_2fa_request(resp_body)
headers = [{"Content-Type", "application/x-www-form-urlencoded"}]
options = @default_options
resp = HTTPoison.request!(method, uri, body, headers, options)
error_msg = "function check_for_successful_binding seems to be entering an error loop"
case check_for_successful_binding(resp, validation_url, ck) do
{:ok, :handle_2fa} -> raise error_msg
{:ok, ck} -> ck
{:error, msg} -> raise "#{error_msg} - #{msg}"
end
end
defp get_credentials(opts_map) do
Og.context(__ENV__, :debug)
create_app_body = get_app_create_page(opts_map) |> get_create_app_inputs() |> build_app_request(opts_map) |> send_app_request(opts_map)
opts_map = Map.merge(opts_map, %{
application_key: get_application_key(create_app_body),
application_secret: get_application_secret(create_app_body),
application_name: get_application_name(create_app_body),
application_description: get_application_description(create_app_body)
})
ck = get_consumer_key(opts_map) |> bind_consumer_key_to_app(opts_map)
Map.merge(opts_map, %{ consumer_key: ck })
|> Map.delete(:login) |> Map.delete(:password)
end
defp remove_private(opts_map) do
opts_map |> Map.delete(:login) |> Map.delete(:password)
end
defp config_names(app_name, client_name) do
Og.context(__ENV__, :debug)
{config_header, mod_client_name} =
case app_name do
"ex_ovh" ->
{
":" <> app_name,
"EX_OVH_"
}
other ->
client_name =
case client_name do
:nil -> "OvhClient"
client_name -> client_name
end
{
":" <> app_name <> ", " <> Macro.camelize(app_name) <> "." <> client_name,
String.upcase(other) <> "_" <> Morph.to_snake_caps(client_name) <>"_"
}
end
{config_header, mod_client_name}
end
defp create_or_update_env_file(options) do
env_path = ".env"
File.exists?(env_path) || File.touch!(env_path)
existing = File.read!(env_path)
{_config_header, mod_client_name} = config_names(options.application_name, options.client_name)
existing =
case existing do
"" -> "#!/usr/bin/env bash\n"
_ -> existing
end
new = existing <>
~s"""
# updated on #{formatted_date()}
export #{mod_client_name <> "APPLICATION_KEY"}=\"#{options.application_key}\"
export #{mod_client_name <> "APPLICATION_SECRET"}="#{options.application_secret}\"
export #{mod_client_name <> "CONSUMER_KEY"}="#{options.consumer_key}\"
"""
{:ok, file} = File.open(env_path, [:write, :utf8])
IO.binwrite(file, new)
File.close(file)
options
end
defp print_config(options) do
Og.context(__ENV__, :debug)
{config_header, mod_client_name} = config_names(options.application_name, options.client_name)
~s"""
Add the following paragraph to the config.exs file(s):
config #{config_header},
ovh: [
application_key: System.get_env(\"#{mod_client_name <> "APPLICATION_KEY"}\"),
application_secret: System.get_env(\"#{mod_client_name <> "APPLICATION_SECRET"}\"),
consumer_key: System.get_env(\"#{mod_client_name <> "CONSUMER_KEY"}\"),
endpoint: \"#{options.endpoint}\",
api_version: \"#{options.api_version}\"
]
"""
end
defp formatted_date() do
{year, month, date} = :erlang.date()
Integer.to_string(date) <> "." <>
Integer.to_string(month) <> "." <>
Integer.to_string(year)
end
end