2018-12-23 21:04:54 +01:00
|
|
|
# Pleroma: A lightweight social networking server
|
2018-12-31 16:41:47 +01:00
|
|
|
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
2018-12-23 21:04:54 +01:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2017-10-19 17:37:24 +02:00
|
|
|
defmodule Pleroma.PasswordResetToken do
|
|
|
|
use Ecto.Schema
|
|
|
|
|
2017-11-19 02:22:07 +01:00
|
|
|
import Ecto.Changeset
|
2017-10-19 17:37:24 +02:00
|
|
|
|
|
|
|
alias Pleroma.{User, PasswordResetToken, Repo}
|
|
|
|
|
|
|
|
schema "password_reset_tokens" do
|
2018-03-30 15:01:53 +02:00
|
|
|
belongs_to(:user, User)
|
|
|
|
field(:token, :string)
|
|
|
|
field(:used, :boolean, default: false)
|
2017-10-19 17:37:24 +02:00
|
|
|
|
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_token(%User{} = user) do
|
2018-03-30 15:01:53 +02:00
|
|
|
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
|
2017-10-19 17:37:24 +02:00
|
|
|
|
|
|
|
token = %PasswordResetToken{
|
|
|
|
user_id: user.id,
|
|
|
|
used: false,
|
|
|
|
token: token
|
|
|
|
}
|
|
|
|
|
|
|
|
Repo.insert(token)
|
|
|
|
end
|
|
|
|
|
|
|
|
def used_changeset(struct) do
|
2017-11-19 02:22:07 +01:00
|
|
|
struct
|
2017-10-19 17:37:24 +02:00
|
|
|
|> cast(%{}, [])
|
|
|
|
|> put_change(:used, true)
|
|
|
|
end
|
|
|
|
|
|
|
|
def reset_password(token, data) do
|
|
|
|
with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}),
|
|
|
|
%User{} = user <- Repo.get(User, token.user_id),
|
2017-11-19 02:22:07 +01:00
|
|
|
{:ok, _user} <- User.reset_password(user, data),
|
2017-10-19 17:37:24 +02:00
|
|
|
{:ok, token} <- Repo.update(used_changeset(token)) do
|
|
|
|
{:ok, token}
|
|
|
|
else
|
|
|
|
_e -> {:error, token}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|