2.0 KiB · text History 1bba52e
defmodule Mix.Tasks.Invites.Create do
  @shortdoc "Create a new single-use registration invite token"

  @moduledoc """
  Mints a registration invite token and prints the full signup URL.

      mix invites.create [--note "for alice"] [--expires-in-days 7] [--base-url https://irc.skyjeep.club]

  Defaults: no expiration, no note, `PHX_HOST` or `localhost:4666` for
  the base URL.
  """

  use Mix.Task

  @impl Mix.Task
  def run(args) do
    {opts, _, _} =
      OptionParser.parse(args,
        strict: [
          note: :string,
          expires_in_days: :integer,
          base_url: :string
        ]
      )

    Mix.Task.run("app.start")

    create_opts = [note: Keyword.get(opts, :note, "")]

    create_opts =
      case Keyword.get(opts, :expires_in_days) do
        nil -> create_opts
        n -> Keyword.put(create_opts, :expires_in_seconds, n * 24 * 3600)
      end

    case OhMyExOhIrcd.Accounts.create_invite(create_opts) do
      {:ok, invite} ->
        base = Keyword.get(opts, :base_url) || default_base_url()
        Mix.shell().info("Token:  #{invite.token}")
        Mix.shell().info("URL:    #{base}/users/register?invite=#{invite.token}")
        if invite.expires_at, do: Mix.shell().info("Expires: #{invite.expires_at}")

      {:error, cs} ->
        Mix.raise("Couldn't create invite: #{inspect(cs.errors)}")
    end
  end

  defp default_base_url do
    case System.get_env("PHX_HOST") do
      nil -> "http://localhost:4666"
      host -> "https://" <> host
    end
  end
end

defmodule Mix.Tasks.Invites.List do
  @shortdoc "List active (unconsumed) invites"

  use Mix.Task

  @impl Mix.Task
  def run(_) do
    Mix.Task.run("app.start")

    case OhMyExOhIrcd.Accounts.list_active_invites() do
      [] ->
        Mix.shell().info("(no active invites)")

      invites ->
        Enum.each(invites, fn i ->
          Mix.shell().info(
            "#{String.slice(i.token, 0, 8)}…  #{i.note || ""}  expires=#{i.expires_at || "never"}"
          )
        end)
    end
  end
end