2018-12-23 13:04:54 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2022-02-25 23:11:42 -07:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2018-12-23 13:04:54 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2017-10-19 09:37:24 -06:00
|
|
|
defmodule Pleroma.PasswordResetToken do
|
|
|
|
use Ecto.Schema
|
|
|
|
|
2017-11-18 18:22:07 -07:00
|
|
|
import Ecto.Changeset
|
2017-10-19 09:37:24 -06:00
|
|
|
|
2019-02-09 08:16:26 -07:00
|
|
|
alias Pleroma.PasswordResetToken
|
2019-03-04 19:52:23 -07:00
|
|
|
alias Pleroma.Repo
|
|
|
|
alias Pleroma.User
|
2017-10-19 09:37:24 -06:00
|
|
|
|
|
|
|
schema "password_reset_tokens" do
|
2019-09-18 08:54:31 -06:00
|
|
|
belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
|
2018-03-30 07:01:53 -06:00
|
|
|
field(:token, :string)
|
|
|
|
field(:used, :boolean, default: false)
|
2017-10-19 09:37:24 -06:00
|
|
|
|
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_token(%User{} = user) do
|
2018-03-30 07:01:53 -06:00
|
|
|
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
|
2017-10-19 09:37:24 -06:00
|
|
|
|
|
|
|
token = %PasswordResetToken{
|
|
|
|
user_id: user.id,
|
|
|
|
used: false,
|
|
|
|
token: token
|
|
|
|
}
|
|
|
|
|
|
|
|
Repo.insert(token)
|
|
|
|
end
|
|
|
|
|
|
|
|
def used_changeset(struct) do
|
2017-11-18 18:22:07 -07:00
|
|
|
struct
|
2017-10-19 09:37:24 -06:00
|
|
|
|> cast(%{}, [])
|
|
|
|
|> put_change(:used, true)
|
|
|
|
end
|
|
|
|
|
2019-06-24 13:01:56 -06:00
|
|
|
@spec reset_password(binary(), map()) :: {:ok, User.t()} | {:error, binary()}
|
2017-10-19 09:37:24 -06:00
|
|
|
def reset_password(token, data) do
|
|
|
|
with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}),
|
2020-11-19 04:27:06 -07:00
|
|
|
false <- expired?(token),
|
2019-04-22 01:20:43 -06:00
|
|
|
%User{} = user <- User.get_cached_by_id(token.user_id),
|
2017-11-18 18:22:07 -07:00
|
|
|
{:ok, _user} <- User.reset_password(user, data),
|
2017-10-19 09:37:24 -06:00
|
|
|
{:ok, token} <- Repo.update(used_changeset(token)) do
|
|
|
|
{:ok, token}
|
|
|
|
else
|
|
|
|
_e -> {:error, token}
|
|
|
|
end
|
|
|
|
end
|
2020-11-19 04:27:06 -07:00
|
|
|
|
|
|
|
def expired?(%__MODULE__{inserted_at: inserted_at}) do
|
|
|
|
validity = Pleroma.Config.get([:instance, :password_reset_token_validity], 0)
|
|
|
|
|
|
|
|
now = NaiveDateTime.utc_now()
|
|
|
|
|
|
|
|
difference = NaiveDateTime.diff(now, inserted_at)
|
|
|
|
|
|
|
|
difference > validity
|
|
|
|
end
|
2017-10-19 09:37:24 -06:00
|
|
|
end
|