2.9 KiB · text History 44bc4f7
defmodule CartosnapApp.Trips.TripInvite do
  @moduledoc """
  A link that makes its holder a member of a trip, once.

  Addressed (`email`) or not: an addressed invite is mailed to that
  address, waits on its recipient's invites page, and (because only they
  should have the link) can make an account for that address. A link-only
  invite is for handing over some other way, a group chat say.

  Only a SHA-256 of the token is stored (`token_hash`), as in the sibling
  apps. The raw token is in the virtual `token` field of the invite
  `build/2` returns and nowhere else: the link is shown then, once. A lost
  link is replaced by making another.
  """

  use Ecto.Schema
  import Ecto.Changeset

  @valid_for_days 7

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

    belongs_to :trip, CartosnapApp.Trips.Trip
    belongs_to :created_by, CartosnapApp.Accounts.User
    belongs_to :used_by, CartosnapApp.Accounts.User

    timestamps(type: :utc_datetime)
  end

  @doc """
  A new invite to `trip_id` from `user_id`, addressed to `email` (or nil),
  with its raw token in `:token`.
  """
  def build(trip_id, user_id, email \\ nil) do
    %__MODULE__{trip_id: trip_id, created_by_id: user_id}
    |> change(email: email)
    |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+\.[^@,;\s]+$/,
      message: "must be an email address"
    )
    |> validate_length(:email, max: 160)
    |> put_new_token()
    |> unique_constraint(:token_hash)
  end

  @doc """
  A new token and a fresh week for a pending invite: the link it had stops
  working. For sending it again.
  """
  def renew_changeset(%__MODULE__{} = invite), do: invite |> change() |> put_new_token()

  defp put_new_token(changeset) do
    raw = 32 |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false)

    changeset
    |> put_change(:token, raw)
    |> put_change(:token_hash, hash(raw))
    |> put_change(:expires_at, DateTime.add(DateTime.utc_now(:second), @valid_for_days, :day))
  end

  @doc "Marks the invite used by `user_id`."
  def use_changeset(invite, user_id),
    do: change(invite, used_at: DateTime.utc_now(:second), used_by_id: user_id)

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

  @doc "An address as invites keep it: trimmed and lowercased, nil when blank."
  def normalize_email(nil), do: nil

  def normalize_email(email) when is_binary(email) do
    case email |> String.trim() |> String.downcase() do
      "" -> nil
      email -> email
    end
  end

  def expired?(%__MODULE__{expires_at: at}), do: DateTime.compare(at, DateTime.utc_now()) == :lt
  def used?(%__MODULE__{used_at: at}), do: not is_nil(at)
end