PasswordResetToken.ex 1.14 KB
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

Roger Braun's avatar
Roger Braun committed
5
6
7
defmodule Pleroma.PasswordResetToken do
  use Ecto.Schema

Thog's avatar
Thog committed
8
  import Ecto.Changeset
Roger Braun's avatar
Roger Braun committed
9
10
11
12

  alias Pleroma.{User, PasswordResetToken, Repo}

  schema "password_reset_tokens" do
lain's avatar
lain committed
13
14
15
    belongs_to(:user, User)
    field(:token, :string)
    field(:used, :boolean, default: false)
Roger Braun's avatar
Roger Braun committed
16
17
18
19
20

    timestamps()
  end

  def create_token(%User{} = user) do
lain's avatar
lain committed
21
    token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
Roger Braun's avatar
Roger Braun committed
22
23
24
25
26
27
28
29
30
31
32

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

    Repo.insert(token)
  end

  def used_changeset(struct) do
Thog's avatar
Thog committed
33
    struct
Roger Braun's avatar
Roger Braun committed
34
35
36
37
38
39
40
    |> 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
41
         {:ok, _user} <- User.reset_password(user, data),
Roger Braun's avatar
Roger Braun committed
42
43
44
45
46
47
48
         {:ok, token} <- Repo.update(used_changeset(token)) do
      {:ok, token}
    else
      _e -> {:error, token}
    end
  end
end