From ae3d7b0f4ed2eb58bb165cdf0a896352a7c843b4 Mon Sep 17 00:00:00 2001 From: Mike Cifelli <26522946+macifell@users.noreply.github.com> Date: Mon, 6 May 2024 15:16:19 -0400 Subject: [PATCH] Don't allow newlines in email addresses --- lib/recognizer/accounts/user.ex | 2 +- test/recognizer/accounts_test.exs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/recognizer/accounts/user.ex b/lib/recognizer/accounts/user.ex index a7a81b2..3126310 100644 --- a/lib/recognizer/accounts/user.ex +++ b/lib/recognizer/accounts/user.ex @@ -142,7 +142,7 @@ defmodule Recognizer.Accounts.User do defp validate_email(changeset) do changeset |> validate_required([:email]) - |> validate_format(:email, ~r/^[^\s]+@[^\s]+\.[\w]+$/, + |> validate_format(:email, ~r/\A[^\s]+@[^\s]+\.[\w]+\z/, message: "must have the @ sign, no spaces and a top level domain" ) |> validate_length(:email, max: 160) diff --git a/test/recognizer/accounts_test.exs b/test/recognizer/accounts_test.exs index f38142c..29bdc12 100644 --- a/test/recognizer/accounts_test.exs +++ b/test/recognizer/accounts_test.exs @@ -79,6 +79,18 @@ defmodule Recognizer.AccountsTest do } = errors_on(changeset) end + test "validates email does not have a preceding newline" do + {:error, changeset} = Accounts.register_user(%{email: "\nhacker@example.com"}) + + assert %{email: ["must have the @ sign, no spaces and a top level domain"]} = errors_on(changeset) + end + + test "validates email does not have a trailing newline" do + {:error, changeset} = Accounts.register_user(%{email: "hacker@example.com\n"}) + + assert %{email: ["must have the @ sign, no spaces and a top level domain"]} = errors_on(changeset) + end + test "validates maximum values for email and password for security" do too_long = String.duplicate("db", 100) {:error, changeset} = Accounts.register_user(%{email: too_long, password: too_long})