PasswordResetToken.ex 1.19 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

Haelwenn's avatar
Haelwenn committed
10
  alias Pleroma.PasswordResetToken
11
12
  alias Pleroma.Repo
  alias Pleroma.User
Roger Braun's avatar
Roger Braun committed
13
14

  schema "password_reset_tokens" do
href's avatar
href committed
15
    belongs_to(:user, User, type: Pleroma.FlakeId)
lain's avatar
lain committed
16
17
    field(:token, :string)
    field(:used, :boolean, default: false)
Roger Braun's avatar
Roger Braun committed
18
19
20
21
22

    timestamps()
  end

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

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

    Repo.insert(token)
  end

  def used_changeset(struct) do
Thog's avatar
Thog committed
35
    struct
Roger Braun's avatar
Roger Braun committed
36
37
38
39
40
41
    |> cast(%{}, [])
    |> put_change(:used, true)
  end

  def reset_password(token, data) do
    with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}),
minibikini's avatar
minibikini committed
42
         %User{} = user <- User.get_cached_by_id(token.user_id),
Thog's avatar
Thog committed
43
         {:ok, _user} <- User.reset_password(user, data),
Roger Braun's avatar
Roger Braun committed
44
45
46
47
48
49
50
         {:ok, token} <- Repo.update(used_changeset(token)) do
      {:ok, token}
    else
      _e -> {:error, token}
    end
  end
end