2019-03-14 14:00:34 +00:00
|
|
|
defmodule Mobilizon.Service.Users.ResetPassword do
|
2018-07-04 12:29:17 +00:00
|
|
|
@moduledoc false
|
|
|
|
|
2019-09-07 23:49:56 +00:00
|
|
|
alias Mobilizon.Email.Mailer
|
2018-10-11 15:37:39 +00:00
|
|
|
alias Mobilizon.Email.User, as: UserEmail
|
2019-03-14 14:00:34 +00:00
|
|
|
alias Mobilizon.Service.Users.Tools
|
2019-09-07 23:49:56 +00:00
|
|
|
alias Mobilizon.Storage.Repo
|
|
|
|
alias Mobilizon.Users
|
|
|
|
alias Mobilizon.Users.User
|
|
|
|
|
|
|
|
require Logger
|
2018-07-04 12:29:17 +00:00
|
|
|
|
|
|
|
@doc """
|
|
|
|
Check that the provided token is correct and update provided password
|
|
|
|
"""
|
2018-07-27 08:45:35 +00:00
|
|
|
@spec check_reset_password_token(String.t(), String.t()) :: tuple
|
2018-07-04 12:29:17 +00:00
|
|
|
def check_reset_password_token(password, token) do
|
2019-03-05 16:23:05 +00:00
|
|
|
with %User{} = user <- Users.get_user_by_reset_password_token(token),
|
2018-08-24 09:34:00 +00: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 09:30:27 +00:00
|
|
|
{:ok, user}
|
2018-07-04 12:29:17 +00:00
|
|
|
else
|
2018-11-27 16:54:54 +00:00
|
|
|
{:error, %Ecto.Changeset{errors: [password: {"registration.error.password_too_short", _}]}} ->
|
2019-01-21 14:08:22 +00:00
|
|
|
{:error,
|
|
|
|
"The password you have choosen is too short. Please make sure your password contains at least 6 charaters."}
|
2018-11-27 16:54:54 +00:00
|
|
|
|
2018-11-28 16:16:23 +00:00
|
|
|
_err ->
|
2019-01-21 14:08:22 +00: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 12:29:17 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Send the email reset password, if it's not too soon since the last send
|
|
|
|
"""
|
2018-07-27 08:45:35 +00:00
|
|
|
@spec send_password_reset_email(User.t(), String.t()) :: tuple
|
2018-07-04 12:29:17 +00:00
|
|
|
def send_password_reset_email(%User{} = user, locale \\ "en") do
|
2018-11-06 09:30:27 +00:00
|
|
|
with :ok <- Tools.we_can_send_email(user, :reset_password_sent_at),
|
2018-07-27 08:45:35 +00:00
|
|
|
{:ok, %User{} = user_updated} <-
|
|
|
|
Repo.update(
|
|
|
|
User.send_password_reset_changeset(user, %{
|
2018-11-06 09:30:27 +00:00
|
|
|
"reset_password_token" => Tools.random_string(30),
|
2019-02-14 13:19:55 +00:00
|
|
|
"reset_password_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
|
2018-07-27 08:45:35 +00:00
|
|
|
})
|
|
|
|
) do
|
|
|
|
mail =
|
|
|
|
user_updated
|
|
|
|
|> UserEmail.reset_password_email(locale)
|
|
|
|
|> Mailer.deliver_later()
|
|
|
|
|
2018-07-04 12:29:17 +00:00
|
|
|
{:ok, mail}
|
|
|
|
else
|
|
|
|
{:error, reason} -> {:error, reason}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|