Hash :
2e8a3d5b
Author :
Date :
2016-02-18T09:27:48
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
defmodule Mix.Tasks.Ovh do
@moduledoc ~S"""
A mix task that generates the hubic application refresh token on the user's behalf.
## Steps
- The user needs to set up an ovh account at https://www.ovh.co.uk/ and retrieve a username (nic-handle) and password.
- Then the user is prompted to do some activations.
- Upon completion of activations, the user needs to create an application in the ovh website.
- Then the user can create an application at `https://eu.api.ovh.com/createApp/` or
alternatively the user can use this mix task to generate the application:
## Example
Create an app with access to all apis:
```shell
mix ovh
--login=<username>
--password=<password>
```
Uses defaults:
```
app name - ex_ovh,
app description - ex_ovh,
redirect_uri - "",
api_version - "1.0",
endpoint - "ovh-eu"
```
## Example
Create an app with access to all apis with specific app name and description:
```shell
mix ovh
--login=<username>
--password=<password>
--appname='My app'
--appdesc='my app for api'
```
Uses defaults:
```
redirect_uri - "",
api_version - "1.0",
endpoint - "ovh-eu"
```
## Example
Create an app with access to all apis with specific everything:
```shell
mix ovh
--login=<username>
--password=<password>
--appname='My app'
--appdesc='my app for api'
--endpoint=ovh-eu
--apiversion=1.0
--redirect_uri='http://localhost:4000/',
--accessrules='get-[/*]::put-[/me,/cdn]::post-[/me,/cdn]::delete-[]'
```
A note on access rules:
The default for access rules will give your ovh application access to *all* of the api calls.
More than likely this is not a good idea. To limit the number of api endpoints available, generate access
rules using the commandline arguments as seen in the example above.
## Shell Output
A map is printed to the shell as follows:
```elixir
%{
application_key: "<app_key>",
application_secret: "<app_secret>",
consumer_key: "<consumer_secret>",
endpoint: "ovh-eu",
api_version: "1.0"
}
```
- This map can then be manually added by the user to the `config/prod.secret.exs` file
```
config :test_os, TestOs.ExOvh,
ovh: %{
application_key: "<app_key>",
application_secret: "<app_secret>",
consumer_key: "<consumer_secret>",
endpoint: "ovh-eu",
api_version: "1.0"
},
hubic: :nil
```
- Then the ovh configuration is complete. Start up the app and the ovh wrapper is ready.
"""
use Mix.Task
alias ExOvh.Ovh.Defaults
alias ExOvh.Ovh.Auth
import ExOvh.Query.Ovh.Webstorage, only: [get_all_webstorage: 0]
@shortdoc "Create a new app and new credentials for accessing ovh api"
@default_headers %{ "Content-Type": "application/json; charset=utf-8" }
@timeout 10_000
defp endpoint(config), do: Defaults.endpoints()[config[:endpoint]]
defp access_rules(config), do: config[:access_rules]
defp api_version(config), do: config[:api_version]
defp app_secret(config), do: config[:application_secret]
defp app_key(config), do: config[:application_key]
defp default_create_app_uri(config), do: endpoint(config) <> "createApp/"
defp consumer_key_uri(config), do: endpoint(config) <> api_version(config) <> "/auth/credential/"
##########################
# 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?("Do you want to proceed?") do
Application.start(:ibrowse, :permanent)
Application.start(:httpotion, :permanent)
opts_map = parse_args(args)
options = get_credentials(opts_map)
message = "
%{
application_key: \"#{options.application_key}\",
application_secret: \"#{options.application_secret}\",
consumer_key: \"#{options.consumer_key}\",
endpoint: \"#{options.endpoint}\",
api_version: \"#{options.api_version}\"
}
"
Mix.Shell.IO.info(message)
end
end
##########################
# Private
#########################
defp parse_args(args) do
{opts, _, _} = OptionParser.parse(args)
Og.log_return(opts, :debug)
{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()
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, %{}}
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_endpoint({opts, acc}) do
endpoint = Keyword.get(opts, :endpoint, :nil)
if endpoint === :nil do
endpoint = "ovh-eu"
end
{opts, Map.merge(acc, %{ endpoint: endpoint }) }
end
defp parsers_api_version({opts, acc}) do
api_version = Keyword.get(opts, :apiversion, :nil)
if api_version === :nil do
api_version = "1.0"
end
{opts, Map.merge(acc, %{ api_version: api_version }) }
end
defp parsers_redirect_uri({opts, acc}) do
redirect_uri = Keyword.get(opts, :redirecturi, :nil)
if redirect_uri === :nil do
redirect_uri = ""
end
{opts, Map.merge(acc, %{ redirect_uri: redirect_uri }) }
end
defp parsers_app_name({opts, acc}) do
application_name = Keyword.get(opts, :appname, :nil)
if application_name === :nil do
application_name = "ex_ovh"
end
{opts, Map.merge(acc, %{ application_name: application_name }) }
end
defp parsers_app_desc({opts, acc}) do
application_description = Keyword.get(opts, :appdesc, :nil)
if application_description === :nil do
application_description = "ex_ovh"
end
{opts, Map.merge(acc, %{ application_description: application_description }) }
end
defp parsers_access_rules({opts, acc}) do
access_rules = Keyword.get(opts, :accessrules, :nil)
if access_rules === :nil do
access_rules = Defaults.access_rules()
else
access_rules = access_rules
|> String.split("::")
|> 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)
options = [ timeout: @timeout ]
default_create_app_uri(opts_map)
%HTTPotion.Response{body: resp_body, headers: headers, status_code: status_code} =
HTTPotion.request(:get, default_create_app_uri(opts_map), options)
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)
uri = Defaults.endpoints()[opts_map.endpoint] <> "createApp/"
resp = HTTPotion.request(:post, uri, [body: req_body, headers: ["Content-Type": "application/x-www-form-urlencoded"]])
error_msg1 = "There is already an application with that name for that Account ID"
cond do
String.contains?(resp.body, error_msg1) ->
raise error_msg1
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)
body = %{ accessRules: access_rules, redirection: redirect_uri }
# {method, uri, options} = Auth.ovh_prepare_request(ExOvh, query, %{})
options = %{ body: Poison.encode!(body), headers: Map.merge(@default_headers, %{ "X-Ovh-Application": app_key(opts_map) } ), timeout: @timeout }
|> Og.log_return(:debug)
Og.log_return(consumer_key_uri(opts_map), :debug)
Og.log_return(options, :debug)
body = HTTPotion.request(:post, consumer_key_uri(opts_map), options) |> Map.get(:body) |> Poison.decode!()
{Map.get(body, "consumerKey"), Map.get(body, "validationUrl")}
end
defp bind_consumer_key_to_app({ck, validation_url}, opts_map) do
HTTPotion.request(:get, validation_url) |> Map.get(: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
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)
{acc, _index, _max} =
Enum.reduce(inputs, {"", 1, Enum.count(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"} 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"
end
param = name_val <> "=" <> 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_ck_binding_request(req_body, validation_url, ck) do
Og.context(__ENV__, :debug)
resp = HTTPotion.request(:post, validation_url, [body: req_body, headers: ["Content-Type": "application/x-www-form-urlencoded"]])
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") ->
raise error_msg2
String.contains?(resp.body, "Your token is now valid, you can use it in your application") ->
ck
true ->
raise error_msg1
end
end
defp get_credentials(opts_map) do
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
end