PasswordResetToken.ex 1001 Bytes
Newer Older
Roger Braun's avatar
Roger Braun committed
1
2
3
defmodule Pleroma.PasswordResetToken do
  use Ecto.Schema

Thog's avatar
Thog committed
4
  import Ecto.Changeset
Roger Braun's avatar
Roger Braun committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

  alias Pleroma.{User, PasswordResetToken, Repo}

  schema "password_reset_tokens" do
    belongs_to :user, User
    field :token, :string
    field :used, :boolean, default: false

    timestamps()
  end

  def create_token(%User{} = user) do
    token = :crypto.strong_rand_bytes(32) |> Base.url_encode64

    token = %PasswordResetToken{
      user_id: user.id,
      used: false,
      token: token
    }

    Repo.insert(token)
  end

  def used_changeset(struct) do
Thog's avatar
Thog committed
29
    struct
Roger Braun's avatar
Roger Braun committed
30
31
32
33
34
35
36
    |> cast(%{}, [])
    |> put_change(:used, true)
  end

  def reset_password(token, data) do
    with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}),
         %User{} = user <- Repo.get(User, token.user_id),
Thog's avatar
Thog committed
37
         {:ok, _user} <- User.reset_password(user, data),
Roger Braun's avatar
Roger Braun committed
38
39
40
41
42
43
44
         {:ok, token} <- Repo.update(used_changeset(token)) do
      {:ok, token}
    else
      _e -> {:error, token}
    end
  end
end