2018-10-11 17:37:39 +02:00
|
|
|
defmodule Mobilizon.Actors.Service.ResetPassword do
|
2018-07-04 14:29:17 +02:00
|
|
|
@moduledoc false
|
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
2018-10-11 17:37:39 +02:00
|
|
|
alias Mobilizon.{Mailer, Repo, Actors.User}
|
|
|
|
alias Mobilizon.Email.User, as: UserEmail
|
2018-11-06 10:30:27 +01:00
|
|
|
alias Mobilizon.Actors.Service.Tools
|
2018-07-04 14:29:17 +02:00
|
|
|
|
|
|
|
@doc """
|
|
|
|
Check that the provided token is correct and update provided password
|
|
|
|
"""
|
2018-07-27 10:45:35 +02:00
|
|
|
@spec check_reset_password_token(String.t(), String.t()) :: tuple
|
2018-07-04 14:29:17 +02:00
|
|
|
def check_reset_password_token(password, token) do
|
2018-08-24 11:34:00 +02:00
|
|
|
with %User{} = user <- Repo.get_by(User, reset_password_token: token),
|
|
|
|
{:ok, %User{} = user} <-
|
|
|
|
Repo.update(
|
|
|
|
User.password_reset_changeset(user, %{
|
|
|
|
"password" => password,
|
|
|
|
"reset_password_sent_at" => nil,
|
|
|
|
"reset_password_token" => nil
|
|
|
|
})
|
|
|
|
) do
|
2018-11-06 10:30:27 +01:00
|
|
|
{:ok, user}
|
2018-07-04 14:29:17 +02:00
|
|
|
else
|
2018-11-27 17:54:54 +01:00
|
|
|
{:error, %Ecto.Changeset{errors: [password: {"registration.error.password_too_short", _}]}} ->
|
|
|
|
{:error, :password_too_short}
|
|
|
|
|
2018-11-28 17:16:23 +01:00
|
|
|
_err ->
|
2018-07-04 14:29:17 +02:00
|
|
|
{:error, :invalid_token}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Send the email reset password, if it's not too soon since the last send
|
|
|
|
"""
|
2018-07-27 10:45:35 +02:00
|
|
|
@spec send_password_reset_email(User.t(), String.t()) :: tuple
|
2018-07-04 14:29:17 +02:00
|
|
|
def send_password_reset_email(%User{} = user, locale \\ "en") do
|
2018-11-06 10:30:27 +01:00
|
|
|
with :ok <- Tools.we_can_send_email(user, :reset_password_sent_at),
|
2018-07-27 10:45:35 +02:00
|
|
|
{:ok, %User{} = user_updated} <-
|
|
|
|
Repo.update(
|
|
|
|
User.send_password_reset_changeset(user, %{
|
2018-11-06 10:30:27 +01:00
|
|
|
"reset_password_token" => Tools.random_string(30),
|
2018-07-27 10:45:35 +02:00
|
|
|
"reset_password_sent_at" => DateTime.utc_now()
|
|
|
|
})
|
|
|
|
) do
|
|
|
|
mail =
|
|
|
|
user_updated
|
|
|
|
|> UserEmail.reset_password_email(locale)
|
|
|
|
|> Mailer.deliver_later()
|
|
|
|
|
2018-07-04 14:29:17 +02:00
|
|
|
{:ok, mail}
|
|
|
|
else
|
|
|
|
{:error, reason} -> {:error, reason}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|