8000 fix: password reset form not verifying user by mwoods79 · Pull Request #99 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
5 changes: 3 additions & 2 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ http_ip = optional("PHX_IP", "::") |> ip!()
scheme = optional("PHX_SCHEME", "https")
check_origin = optional("PHX_CHECK_ORIGIN", "true") |> boolean!()

# URL port should be the standard port for the scheme (443 for https, 80 for http)
url_port = if scheme == "https", do: 443, else: 80
# In production (https), use standard port 443 (behind reverse proxy).
# In development (http), use the actual server port (e.g., 4000).
url_port = if scheme == "https", do: 443, else: port

config :huddlz, HuddlzWeb.Endpoint,
url: [host: host, port: url_port, scheme: scheme],
Expand Down
98 changes: 31 additions & 67 deletions lib/huddlz_web/live/auth_live/reset_password_confirm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,37 @@ defmodule HuddlzWeb.AuthLive.ResetPasswordConfirm do

@impl true
def mount(%{"token" => token}, _session, socket) do
# For now, we'll assume all tokens are potentially valid and let
# the form submission handle validation
# Get the password strategy for proper context
strategy = AshAuthentication.Info.strategy!(User, :password)
domain = AshAuthentication.Info.authentication_domain!(User)

# Create form for reset_password_with_token action with token pre-filled
form =
Form.for_action(User, :reset_password_with_token,
params: %{"reset_token" => token},
domain: domain,
as: "user",
id: "user-password-reset-password-with-token",
context: %{strategy: strategy, private: %{ash_authentication?: true}}
)

{:ok,
socket
|> assign(:form, to_form(form))
|> assign(:token, token)
|> assign(:token_valid, true)}
with {:ok, %{"sub" => subject}, _resource} <- AshAuthentication.Jwt.verify(token, User),
{:ok, user} <- AshAuthentication.subject_to_user(subject, User) do
form =
Form.for_update(user, :reset_password_with_token,
params: %{"reset_token" => token},
domain: domain,
as: "user",
id: "user-password-reset-password-with-token",
context: %{strategy: strategy, private: %{ash_authentication?: true}}
)

{:ok,
socket
|> assign(:form, to_form(form))
|> assign(:token, token)
|> assign(:token_valid, true)
|> assign(:trigger_action, false)}
else
_ ->
{:ok, assign(socket, token_valid: false, trigger_action: false)}
end
end

def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:token_valid, false)}
|> assign(:token_valid, false)
|> assign(:trigger_action, false)}
end

@impl true
Expand All @@ -53,6 +57,9 @@ defmodule HuddlzWeb.AuthLive.ResetPasswordConfirm do
for={@form}
phx-change="validate"
phx-submit="reset_password"
phx-trigger-action={@trigger_action}
action="/auth/user/password/reset"
method="POST"
id="reset-password-confirm-form"
>
<input
Expand Down Expand Up @@ -127,58 +134,15 @@ defmodule HuddlzWeb.AuthLive.ResetPasswordConfirm do
{:noreply, assign(socket, form: to_form(form))}
end

def handle_event("reset_password", params, socket) do
# Extract the user params from the form submission
user_params = Map.get(params, "user", %{})

# Add the reset token to the params if not present
user_params = Map.put_new(user_params, "reset_token", socket.assigns.token)

form = socket.assigns.form.source |> Form.validate(user_params)

if form.valid? do
handle_valid_form_submission(form, user_params, socket)
else
{:noreply, assign(socket, form: to_form(form))}
end
end

defp handle_valid_form_submission(form, user_params, socket) do
case Form.submit(form, params: user_params) do
{:ok, user} ->
handle_successful_reset(user, socket)

{:error, form} ->
handle_reset_error(form, socket)
end
end

defp handle_successful_reset(user, socket) do
# Generate a token for the user to sign them in
{:ok, token} = AshAuthentication.Jwt.token_for_user(user, %{"purpose" => "user"})
def handle_event("reset_password", %{"user" => params}, socket) do
params = Map.put_new(params, "reset_token", socket.assigns.token)
form = socket.assigns.form.source |> Form.validate(params)

socket =
socket
|> put_flash(:info, "Your password has successfully been reset")
|> redirect(to: "/auth/user/password/sign_in_with_token?token=#{token}")
|> assign(:form, to_form(form))
|> assign(:trigger_action, form.valid?)

{:noreply, socket}
end

defp handle_reset_error(form, socket) do
# Check if this is an invalid token error
errors = AshPhoenix.Form.errors(form)

invalid_token? =
Enum.any?(errors, fn {field, msg} ->
field == :reset_token ||
String.contains?(to_string(msg), ["invalid", "expired", "stale"])
end)

if invalid_token? do
{:noreply, assign(socket, :token_valid, false)}
else
{:noreply, assign(socket, form: to_form(form))}
end
end
end
31 changes: 28 additions & 3 deletions test/features/password_authentication.feature
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,34 @@ Feature: Password Authentication
Then I should receive a password reset email for "reset@example.com"
When I click the password reset link in the email
Then I should be on the password reset confirmation page
# Note: Full password reset flow including form submission is tested in
# test/huddlz_web/live/password_reset_full_flow_test.exs due to PhoenixTest
# limitations with phx-trigger-action JavaScript behavior
When I fill in the new password form with:
| password | NewSecurePass456! |
| password_confirmation | NewSecurePass456! |
And I submit the password reset form
Then I should see "Your password has successfully been reset"

Scenario: User can sign in with new password after reset
Given a confirmed user exists with email "resetpwd@example.com" and password "OldPassword123!"
When I visit "/reset"
And I fill in "Email" with "resetpwd@example.com" within "#reset-password-form"
And I click "Send reset instructions"
Then I should receive a password reset email for "resetpwd@example.com"
When I click the password reset link in the email
And I fill in the new password form with:
| password | NewSecurePass456! |
| password_confirmation | NewSecurePass456! |
And I submit the password reset form
Then I should see "Your password has successfully been reset"
When I am on the sign-in page
And I fill in the password sign-in form with:
| email | resetpwd@example.com |
| password | NewSecurePass456! |
And I submit the password sign-in form
Then I should be signed in

Scenario: User visits password reset with invalid token
When I visit "/reset/invalid-token-here"
Then I should see "This password reset link is invalid or has expired"

Scenario: User can access authentication pages
Given I am on the sign-in page
Expand Down
11 changes: 11 additions & 0 deletions test/features/step_definitions/password_authentication_steps.exs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,17 @@ defmodule PasswordAuthenticationSteps do
{:ok, context}
end

step "I submit the password reset form", context do
session = context[:session] || context[:conn]

session =
within(session, "#reset-password-confirm-form", fn s ->
click_button(s, "Reset password")
end)

{:ok, Map.merge(context, %{session: session, conn: session})}
end

step "I fill in the new password form with:", context do
table_rows = context[:datatable][:raw] || context[:datatable][:rows] || []
session = context[:session] || context[:conn]
Expand Down
10 changes: 5 additions & 5 deletions test/huddlz_web/live/basic_password_reset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,13 @@ defmodule HuddlzWeb.BasicPasswordResetTest do
assert_has(session, "button", text: "Reset password")
end

test "invalid token shows form but cannot reset", %{conn: conn} do
# Visit with an invalid token
test "invalid token shows error immediately", %{conn: conn} do
# Visit with an invalid token - now caught on mount
session = visit(conn, "/reset/invalid-token-123")

# The form will initially appear
assert_has(session, "h2", text: "Set new password")
assert_has(session, "input[type='password']")
# Should show the invalid state immediately
assert_has(session, "h2", text: "Invalid reset link")
assert_has(session, "*", text: "This password reset link is invalid or has expired")
end

test "password reset with non-existent email still shows success", %{conn: conn} do
Expand Down
143 changes: 134 additions & 9 deletions test/huddlz_web/live/password_reset_full_flow_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,142 @@ defmodule HuddlzWeb.PasswordResetFullFlowTest do
assert_has(session, "input[type='password']")
end

test "invalid reset link shows form initially", %{conn: conn} do
# When visiting with an invalid token, the form is shown
# but submission will fail
session = visit(conn, "/reset/invalid-token-123")
test "user can submit new password via reset form", %{conn: conn} do
# Create and confirm a user
{:ok, user} =
User
|> Ash.Changeset.for_create(:register_with_password, %{
email: "submit.reset@example.com",
password: "oldpassword123",
password_confirmation: "oldpassword123",
display_name: "Submit Reset User"
})
|> Ash.create()

# The form will initially appear
assert_has(session, "h2", text: "Set new password")
# Clear confirmation email
assert_email_sent()

# The form should have password fields
assert_has(session, "input[type='password']")
assert_has(session, "button", text: "Reset password")
# Confirm user
user
|> Ecto.Changeset.change(%{confirmed_at: DateTime.utc_now()})
|> Huddlz.Repo.update!()

# Request reset
conn
|> visit("/reset")
|> within("#reset-password-form", fn session ->
session
|> fill_in("Email", with: "submit.reset@example.com")
|> click_button("Send reset instructions")
end)

# Get the reset link from email
reset_link =
assert_email_sent(fn email ->
if email.subject == "Reset your password" do
case Regex.run(~r{<a href="([^"]+)">}, email.html_body) do
[_, url] -> url
_ -> false
end
else
false
end
end)

%{path: reset_path} = URI.parse(reset_link)

# Visit the reset link and submit the new password
session =
conn
|> visit(reset_path)
|> within("#reset-password-confirm-form", fn s ->
s
|> fill_in("New password", with: "NewSecurePass456!")
|> fill_in("Confirm new password", with: "NewSecurePass456!")
|> click_button("Reset password")
end)

# Should see only the success message (no error flash)
assert_has(session, "*", text: "Your password has successfully been reset")
refute_has(session, "*", text: "Incorrect email or password")
end

test "user can sign in with new password after reset", %{conn: conn} do
{:ok, user} =
User
|> Ash.Changeset.for_create(:register_with_password, %{
email: "newpwd.test@example.com",
password: "oldpassword123",
password_confirmation: "oldpassword123",
display_name: "New Pwd User"
})
|> Ash.create()

assert_email_sent()

user
|> Ecto.Changeset.change(%{confirmed_at: DateTime.utc_now()})
|> Huddlz.Repo.update!()

# Request reset
conn
|> visit("/reset")
|> within("#reset-password-form", fn session ->
session
|> fill_in("Email", with: "newpwd.test@example.com")
|> click_button("Send reset instructions")
end)

# Get the reset link from email
reset_link =
assert_email_sent(fn email ->
if email.subject == "Reset your password" do
case Regex.run(~r{<a href="([^"]+)">}, email.html_body) do
[_, url] -> url
_ -> false
end
else
false
end
end)

%{path: reset_path} = URI.parse(reset_link)

# Reset the password
session =
conn
|> visit(reset_path)
|> within("#reset-password-confirm-form", fn s ->
s
|> fill_in("New password", with: "BrandNewPass789!")
|> fill_in("Confirm new password", with: "BrandNewPass789!")
|> click_button("Reset password")
end)

# Verify the reset succeeded (controller processed it)
assert_has(session, "*", text: "Your password has successfully been reset")

# Sign in with the new password on a fresh connection
session =
conn
|> visit("/sign-in")
|> within("#password-sign-in-form", fn s ->
s
|> fill_in("Email", with: "newpwd.test@example.com")
|> fill_in("Password", with: "BrandNewPass789!")
|> click_button("Sign in")
end)

# Should be signed in with the new password
assert_has(session, "a", text: "Sign Out")
end

test "invalid reset link shows error immediately", %{conn: conn} do
# When visiting with an invalid token, the error is shown on mount
session = visit(conn, "/reset/invalid-token-123")

assert_has(session, "h2", text: "Invalid reset link")
assert_has(session, "*", text: "This password reset link is invalid or has expired")
end
end
end
0