Merge remote-tracking branch 'pleroma/develop' into cycles-html
[akkoma] / lib / pleroma / password_reset_token.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.PasswordResetToken do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9
10 alias Pleroma.PasswordResetToken
11 alias Pleroma.Repo
12 alias Pleroma.User
13
14 schema "password_reset_tokens" do
15 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
16 field(:token, :string)
17 field(:used, :boolean, default: false)
18
19 timestamps()
20 end
21
22 def create_token(%User{} = user) do
23 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
24
25 token = %PasswordResetToken{
26 user_id: user.id,
27 used: false,
28 token: token
29 }
30
31 Repo.insert(token)
32 end
33
34 def used_changeset(struct) do
35 struct
36 |> cast(%{}, [])
37 |> put_change(:used, true)
38 end
39
40 @spec reset_password(binary(), map()) :: {:ok, User.t()} | {:error, binary()}
41 def reset_password(token, data) do
42 with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}),
43 false <- expired?(token),
44 %User{} = user <- User.get_cached_by_id(token.user_id),
45 {:ok, _user} <- User.reset_password(user, data),
46 {:ok, token} <- Repo.update(used_changeset(token)) do
47 {:ok, token}
48 else
49 _e -> {:error, token}
50 end
51 end
52
53 def expired?(%__MODULE__{inserted_at: inserted_at}) do
54 validity = Pleroma.Config.get([:instance, :password_reset_token_validity], 0)
55
56 now = NaiveDateTime.utc_now()
57
58 difference = NaiveDateTime.diff(now, inserted_at)
59
60 difference > validity
61 end
62 end