Skip to content

Commit

Permalink
Delete only password reset tokens upon success
Browse files Browse the repository at this point in the history
In the default authentication system created by the `mix phx.gen.auth`,
when a password has been successfully resetted it deletes all of the
tokens regardless of their context, however, this is problematic in the
following scenario:

- A user has been registered, which creates a token with the `confirm`
  context and account confirmation instructions delivered via email.
- The user does not click on the email message yet.
- The user request password reset instructions and gets them via email.
- The user successfully follows the password reset instructions.

With the existing implementation, all of the user tokens get deleted,
which means that the `confirm` token is gone as well, leaving an invalid
email in the user's mailbox.

By scoping the deletion to only `reset_password` tokens, the bug is gone
and the `confirm` token will still be valid regardless of the process
described above.
  • Loading branch information
roberto-aguilar committed Feb 14, 2024
1 parent ab3351a commit 7ba3de5
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion priv/templates/phx.gen.auth/context_functions.ex
Expand Up @@ -335,7 +335,7 @@
def reset_<%= schema.singular %>_password(<%= schema.singular %>, attrs) do
Ecto.Multi.new()
|> Ecto.Multi.update(:<%= schema.singular %>, <%= inspect schema.alias %>.password_changeset(<%= schema.singular %>, attrs))
|> Ecto.Multi.delete_all(:tokens, <%= inspect schema.alias %>Token.by_<%= schema.singular %>_and_contexts_query(<%= schema.singular %>, :all))
|> Ecto.Multi.delete_all(:tokens, <%= inspect schema.alias %>Token.by_<%= schema.singular %>_and_contexts_query(<%= schema.singular %>, ["reset_password"]))
|> Repo.transaction()
|> case do
{:ok, %{<%= schema.singular %>: <%= schema.singular %>}} -> {:ok, <%= schema.singular %>}
Expand Down

0 comments on commit 7ba3de5

Please sign in to comment.