3.4 KiB · text History 8445167
defmodule CartosnapApp.Accounts.Invite do
  @moduledoc """
  A single-use registration invite, as the sibling apps. While registration
  is closed (`CartosnapApp.Accounts.registration_open?/0`, the default),
  `/users/register` only takes a visitor carrying a valid invite: one of
  these in the URL, or a trip invite (`CartosnapApp.Trips.TripInvite`).

  An invite may be addressed to an `email`. Then the link is for that
  person only: the account is made for that address, already confirmed
  (holding the link stands in for the confirmation email), and they're
  signed in. An unaddressed invite proves nothing about an address: whoever
  holds it picks an email and confirms it by magic link, as with open
  registration.

  With NEIAM on and `OIDC_PROVISION=invite_only`, an invite is also how a
  first NEIAM login gets an account (`CartosnapAppWeb.InviteController`).

  Only a SHA-256 of the token is stored (`token_hash`). The raw token is in
  the link alone, and on the struct (the virtual `token`) only as it comes
  back from creating or rotating, which is the one time to show the link.
  """
  use Ecto.Schema
  import Ecto.Changeset

  alias CartosnapApp.Accounts.User

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "user_invites" do
    field :token, :string, virtual: true, redact: true
    field :token_hash, :binary, redact: true
    field :note, :string
    field :email, :string
    field :expires_at, :utc_datetime
    field :consumed_at, :utc_datetime

    belongs_to :created_by, User
    belongs_to :consumed_by, User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def create_changeset(invite, attrs) do
    invite
    |> cast(attrs, [:note, :email, :created_by_id, :expires_at])
    |> update_change(:email, &(&1 |> String.trim() |> String.downcase()))
    |> put_new_token()
    |> validate_length(:note, max: 200)
    |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
      message: "must have the @ sign and no spaces"
    )
    |> validate_length(:email, max: 160)
    |> unique_constraint(:token_hash)
  end

  @doc """
  Stamps the invite as consumed by the given user. Idempotent: a second
  call returns the same record without re-stamping.
  """
  def consume_changeset(invite, %User{id: user_id}) do
    if invite.consumed_at,
      do: change(invite),
      else: change(invite, consumed_at: DateTime.utc_now(:second), consumed_by_id: user_id)
  end

  @doc "A new token, so every earlier link to this invite stops working."
  def rotate_token_changeset(invite), do: invite |> change() |> put_new_token()

  @doc "A new link token: `{raw, hash}`. Only the hash is stored."
  def build_token do
    raw = :crypto.strong_rand_bytes(24) |> Base.url_encode64(padding: false)
    {raw, hash_token(raw)}
  end

  @doc "The stored form of a link token."
  def hash_token(raw) when is_binary(raw), do: :crypto.hash(:sha256, raw)

  @doc "True when the invite can still be used: not consumed (or revoked), not expired."
  @spec active?(%__MODULE__{}) :: boolean()
  def active?(%__MODULE__{consumed_at: nil, expires_at: nil}), do: true

  def active?(%__MODULE__{consumed_at: nil, expires_at: %DateTime{} = exp}),
    do: DateTime.after?(exp, DateTime.utc_now())

  def active?(_), do: false

  defp put_new_token(changeset) do
    {raw, hash} = build_token()
    changeset |> put_change(:token, raw) |> put_change(:token_hash, hash)
  end
end