1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.PasswordResetToken do
10 alias Pleroma.PasswordResetToken
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)
22 def create_token(%User{} = user) do
23 token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
25 token = %PasswordResetToken{
34 def used_changeset(struct) do
37 |> put_change(:used, true)
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
53 def expired?(%__MODULE__{inserted_at: inserted_at}) do
54 validity = Pleroma.Config.get([:instance, :password_reset_token_validity], 0)
56 now = NaiveDateTime.utc_now()
58 difference = NaiveDateTime.diff(now, inserted_at)