1
0
Fork 1
mirror of https://akkoma.dev/AkkomaGang/akkoma.git synced 2024-11-18 10:59:17 +00:00
akkoma/lib/pleroma/password_reset_token.ex

52 lines
1.3 KiB
Elixir
Raw Normal View History

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