user_invite_token.ex 965 Bytes
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 4
# SPDX-License-Identifier: AGPL-3.0-only

HJ's avatar
HJ committed
5 6 7 8 9
defmodule Pleroma.UserInviteToken do
  use Ecto.Schema

  import Ecto.Changeset

Maksim's avatar
Maksim committed
10
  alias Pleroma.Repo
11
  alias Pleroma.UserInviteToken
HJ's avatar
HJ committed
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

  schema "user_invite_tokens" do
    field(:token, :string)
    field(:used, :boolean, default: false)

    timestamps()
  end

  def create_token do
    token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()

    token = %UserInviteToken{
      used: false,
      token: token
    }

    Repo.insert(token)
  end

  def used_changeset(struct) do
    struct
    |> cast(%{}, [])
    |> put_change(:used, true)
  end

  def mark_as_used(token) do
    with %{used: false} = token <- Repo.get_by(UserInviteToken, %{token: token}),
         {:ok, token} <- Repo.update(used_changeset(token)) do
      {:ok, token}
    else
      _e -> {:error, token}
    end
  end
end