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 reset, 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 has not clicked on the confirmation email message yet.
- The user requests password reset instructions and gets them via email.
- The user successfully follows the password reset instructions.
- The user tries to click on the confirmation email, but it is no longer
  valid.

By scoping the deletion to only `reset_password` tokens, the bug is gone
and the confirm token will still be valid regardless of the abovementioned
process.
  • Loading branch information
roberto-aguilar committed Feb 14, 2024
1 parent ab3351a commit 6bb80a9
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 6bb80a9

Please sign in to comment.