require "test_helper" class AuthFlowTest < ActionDispatch::IntegrationTest include ActionMailer::TestHelper test "requesting a link sends a mail, same answer for any address" do assert_enqueued_emails 1 do post "/api/auth/magic_link", params: { email: "anna@example.com", return_to: "/d/x" }, as: :json end assert_response :success assert_equal({ "ok" => true }, json) end test "mail link: GET only shows a confirm page, POST signs in and redirects" do link = MagicLink.issue!(email: "anna@example.com", return_to: "/d/123") get "/auth/verify", params: { token: link.token } assert_response :success assert_nil link.reload.used_at, "a GET (mail scanner) must not use the link" post "/auth/verify", params: { token: link.token } assert_redirected_to "/d/123" get "/api/me" assert_equal "anna@example.com", json.dig("user", "email") post "/auth/verify", params: { token: link.token } assert_response :not_found end test "code sign-in and logout" do user = create_user sign_in user get "/api/me" assert_equal user.id, json.dig("user", "id") delete "/api/auth/session" get "/api/me" assert_nil json["user"] end test "wrong code" do MagicLink.issue!(email: "anna@example.com") post "/api/auth/code", params: { email: "anna@example.com", code: "abc" }, as: :json assert_response :unprocessable_entity end test "the app page embeds the signed-in user" do sign_in create_user get "/" assert_response :success assert_includes response.body, "anna@example.com" end end