2019-03-05 17:23:05 +01:00
|
|
|
defmodule Mobilizon.Users.Service.ResetPassword do
|
2018-07-04 14:29:17 +02:00
|
|
|
@moduledoc false
|
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
2019-03-05 17:23:05 +01:00
|
|
|
alias Mobilizon.Users.User
|
|
|
|
alias Mobilizon.{Mailer, Repo, Users}
|
2018-10-11 17:37:39 +02:00
|
|
|
alias Mobilizon.Email.User, as: UserEmail
|
2019-03-05 17:23:05 +01:00
|
|
|
alias Mobilizon.Users.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
|
2019-03-05 17:23:05 +01:00
|
|
|
with %User{} = user <- Users.get_user_by_reset_password_token(token),
|
2018-08-24 11:34:00 +02:00
|
|
|
{: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", _}]}} ->
|
2019-01-21 15:08:22 +01:00
|
|
|
{:error,
|
|
|
|
"The password you have choosen is too short. Please make sure your password contains at least 6 charaters."}
|
2018-11-27 17:54:54 +01:00
|
|
|
|
2018-11-28 17:16:23 +01:00
|
|
|
_err ->
|
2019-01-21 15:08:22 +01:00
|
|
|
{:error,
|
|
|
|
"The token you provided is invalid. Make sure that the URL is exactly the one provided inside the email you got."}
|
2018-07-04 14:29:17 +02:00
|
|
|
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),
|
2019-02-14 14:19:55 +01:00
|
|
|
"reset_password_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
|
2018-07-27 10:45:35 +02:00
|
|
|
})
|
|
|
|
) 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
|