1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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: Pleroma.FlakeId)
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 %User{} = user <- User.get_cached_by_id(token.user_id),
44 {:ok, _user} <- User.reset_password(user, data),
45 {:ok, token} <- Repo.update(used_changeset(token)) do