summaryrefslogtreecommitdiff
path: root/lib/mix/tasks/polyjuice/login.ex
blob: 3ae12345a2f2eaecfe8182d23f7b1f3abdc358c7 (plain) (blame)
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
# Copyright 2020 Hubert Chathi <hubert@uhoreg.ca>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

defmodule Mix.Tasks.Polyjuice.Login do
  @moduledoc """
  Log in to a Matrix homeserver.

      mix polyjuice.login [opts] homeserver_url username password

  ## Command line options

  * `--storage` - Elixir code to create the storage to save the client state
    in.  If this option is not provided (or if the `--verbose` option is also
    provided), the logged in user ID, device ID and access token will be
    printed.
  * `--verbose` - print the logged in user ID, device ID and access token even
    if the `--storage` option is provided.

  """
  @shortdoc "Log in to a Matrix homeserver."
  use Mix.Task

  @impl Mix.Task
  def run(args) do
    Mix.Task.run("app.start", [])

    with {opts, [url, user_id, password]} <-
           OptionParser.parse!(args,
             strict: [
               storage: :string,
               verbose: :boolean
             ]
           ) do
      storage = opts[:storage]

      storage =
        if is_binary(storage) do
          Code.eval_string(storage) |> (fn {x, _} -> x end).()
        else
          nil
        end

      client =
        Polyjuice.Client.start_link(
          url,
          storage: storage,
          sync: false
        )

      ret = Polyjuice.Client.log_in_with_password(client, user_id, password)

      Polyjuice.Client.stop(client)

      if storage, do: Polyjuice.Client.Storage.close(storage)

      case ret do
        {:ok, %{"user_id" => user_id, "device_id" => device_id, "access_token" => access_token}} ->
          IO.puts("Login successful.")

          if opts[:verbose] || opts[:storage] == nil do
            IO.puts("User ID: #{user_id}")
            IO.puts("Device ID: #{device_id}")
            IO.puts("Access token: #{access_token}")
          end

        _ ->
          IO.puts("Login failed: #{inspect(ret)}.")
      end
    else
      _ ->
        Mix.Task.run("help", ["polyjuice.login"])
    end
  end
end