8e449444c3583e25a411e4d523af929625a0bda5
[akkoma] / lib / pleroma / user_invite_token.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.UserInviteToken do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9
10 alias Pleroma.{UserInviteToken, Repo}
11
12 schema "user_invite_tokens" do
13 field(:token, :string)
14 field(:used, :boolean, default: false)
15
16 timestamps()
17 end
18
19 def create_token do
20 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
21
22 token = %UserInviteToken{
23 used: false,
24 token: token
25 }
26
27 Repo.insert(token)
28 end
29
30 def used_changeset(struct) do
31 struct
32 |> cast(%{}, [])
33 |> put_change(:used, true)
34 end
35
36 def mark_as_used(token) do
37 with %{used: false} = token <- Repo.get_by(UserInviteToken, %{token: token}),
38 {:ok, token} <- Repo.update(used_changeset(token)) do
39 {:ok, token}
40 else
41 _e -> {:error, token}
42 end
43 end
44 end