diff --git a/.credo.exs b/.credo.exs index b1df08b..baf0930 100644 --- a/.credo.exs +++ b/.credo.exs @@ -161,7 +161,7 @@ order: ~w/shortdoc moduledoc behaviour use import alias require module_attribute defstruct callback/a ]}, - {Credo.Check.Consistency.MultiAliasImportRequireUse, []}, + {Credo.Check.Consistency.MultiAliasImportRequireUse, false}, {Credo.Check.Consistency.UnusedVariableNames, false}, {Credo.Check.Design.DuplicatedCode, []}, {Credo.Check.Readability.AliasAs, false}, diff --git a/config/test.exs b/config/test.exs index c4cdf07..d8c42d0 100644 --- a/config/test.exs +++ b/config/test.exs @@ -1,5 +1,8 @@ use Mix.Config +# Only in tests, remove the complexity from the password hashing algorithm +config :bcrypt_elixir, :log_rounds, 1 + # Configure your database # # The MIX_TEST_PARTITION environment variable can be used diff --git a/lib/elixir_search_extractor/accounts.ex b/lib/elixir_search_extractor/accounts.ex new file mode 100644 index 0000000..e10dba2 --- /dev/null +++ b/lib/elixir_search_extractor/accounts.ex @@ -0,0 +1,163 @@ +defmodule ElixirSearchExtractor.Accounts do + @moduledoc """ + The Accounts context. + """ + + import Ecto.Query, warn: false + alias ElixirSearchExtractor.Repo + alias ElixirSearchExtractor.Accounts.{User, UserToken} + + ## Database getters + + @doc """ + Gets a user by email. + + ## Examples + + iex> get_user_by_email("foo@example.com") + %User{} + + iex> get_user_by_email("unknown@example.com") + nil + + """ + def get_user_by_email(email) when is_binary(email) do + Repo.get_by(User, email: email) + end + + @doc """ + Gets a user by email and password. + + ## Examples + + iex> get_user_by_email_and_password("foo@example.com", "correct_password") + %User{} + + iex> get_user_by_email_and_password("foo@example.com", "invalid_password") + nil + + """ + def get_user_by_email_and_password(email, password) + when is_binary(email) and is_binary(password) do + user = Repo.get_by(User, email: email) + if User.valid_password?(user, password), do: user + end + + @doc """ + Gets a single user. + + Raises `Ecto.NoResultsError` if the User does not exist. + + ## Examples + + iex> get_user!(123) + %User{} + + iex> get_user!(456) + ** (Ecto.NoResultsError) + + """ + def get_user!(id), do: Repo.get!(User, id) + + ## User registration + + @doc """ + Registers a user. + + ## Examples + + iex> register_user(%{field: value}) + {:ok, %User{}} + + iex> register_user(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def register_user(attrs) do + %User{} + |> User.registration_changeset(attrs) + |> Repo.insert() + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking user changes. + + ## Examples + + iex> change_user_registration(user) + %Ecto.Changeset{data: %User{}} + + """ + def change_user_registration(%User{} = user, attrs \\ %{}) do + User.registration_changeset(user, attrs, hash_password: false) + end + + ## Settings + @doc """ + Returns an `%Ecto.Changeset{}` for changing the user password. + + ## Examples + + iex> change_user_password(user) + %Ecto.Changeset{data: %User{}} + + """ + def change_user_password(user, attrs \\ %{}) do + User.password_changeset(user, attrs, hash_password: false) + end + + @doc """ + Updates the user password. + + ## Examples + + iex> update_user_password(user, "valid password", %{password: ...}) + {:ok, %User{}} + + iex> update_user_password(user, "invalid password", %{password: ...}) + {:error, %Ecto.Changeset{}} + + """ + def update_user_password(user, password, attrs) do + changeset = + user + |> User.password_changeset(attrs) + |> User.validate_current_password(password) + + Ecto.Multi.new() + |> Ecto.Multi.update(:user, changeset) + |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all)) + |> Repo.transaction() + |> case do + {:ok, %{user: user}} -> {:ok, user} + {:error, :user, changeset, _} -> {:error, changeset} + end + end + + ## Session + + @doc """ + Generates a session token. + """ + def generate_user_session_token(user) do + {token, user_token} = UserToken.build_session_token(user) + Repo.insert!(user_token) + token + end + + @doc """ + Gets the user with the given signed token. + """ + def get_user_by_session_token(token) do + {:ok, query} = UserToken.verify_session_token_query(token) + Repo.one(query) + end + + @doc """ + Deletes the signed token with the given context. + """ + def delete_session_token(token) do + Repo.delete_all(UserToken.token_and_context_query(token, "session")) + :ok + end +end diff --git a/lib/elixir_search_extractor/accounts/user.ex b/lib/elixir_search_extractor/accounts/user.ex new file mode 100644 index 0000000..1a64d74 --- /dev/null +++ b/lib/elixir_search_extractor/accounts/user.ex @@ -0,0 +1,125 @@ +defmodule ElixirSearchExtractor.Accounts.User do + use Ecto.Schema + import Ecto.Changeset + + @derive {Inspect, except: [:password]} + schema "users" do + field :name, :string + field :email, :string + field :password, :string, virtual: true + field :hashed_password, :string + field :confirmed_at, :naive_datetime + + timestamps() + end + + @doc """ + A user changeset for registration. + + It is important to validate the length of both email and password. + Otherwise databases may truncate the email without warnings, which + could lead to unpredictable or insecure behaviour. Long passwords may + also be very expensive to hash for certain algorithms. + + ## Options + + * `:hash_password` - Hashes the password so it can be stored securely + in the database and ensures the password field is cleared to prevent + leaks in the logs. If password hashing is not needed and clearing the + password field is not desired (like when using this changeset for + validations on a LiveView form), this option can be set to `false`. + Defaults to `true`. + """ + def registration_changeset(user, attrs, opts \\ []) do + user + |> cast(attrs, [:email, :name, :password]) + |> validate_confirmation(:password, message: "does not match password") + |> validate_email() + |> validate_name() + |> validate_password(opts) + end + + defp validate_email(changeset) do + changeset + |> validate_required([:email]) + |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") + |> validate_length(:email, max: 80) + |> unsafe_validate_unique(:email, ElixirSearchExtractor.Repo) + |> unique_constraint(:email) + end + + defp validate_name(changeset) do + changeset + |> validate_required([:name]) + |> validate_length(:name, min: 5, max: 80) + end + + defp validate_password(changeset, opts) do + changeset + |> validate_required([:password]) + |> validate_length(:password, min: 6, max: 30) + |> maybe_hash_password(opts) + end + + defp maybe_hash_password(changeset, opts) do + hash_password? = Keyword.get(opts, :hash_password, true) + password = get_change(changeset, :password) + + if hash_password? && password && changeset.valid? do + changeset + |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) + |> delete_change(:password) + else + changeset + end + end + + @doc """ + A user changeset for changing the password. + + ## Options + + * `:hash_password` - Hashes the password so it can be stored securely + in the database and ensures the password field is cleared to prevent + leaks in the logs. If password hashing is not needed and clearing the + password field is not desired (like when using this changeset for + validations on a LiveView form), this option can be set to `false`. + Defaults to `true`. + """ + def password_changeset(user, attrs, opts \\ []) do + user + |> cast(attrs, [:password]) + |> validate_confirmation(:password, message: "does not match password") + |> validate_password(opts) + end + + @doc """ + Verifies the password. + + If there is no user or the user doesn't have a password, we call + `Bcrypt.no_user_verify/0` to avoid timing attacks. + """ + def valid_password?( + %ElixirSearchExtractor.Accounts.User{hashed_password: hashed_password}, + password + ) + when is_binary(hashed_password) and byte_size(password) > 0 do + Bcrypt.verify_pass(password, hashed_password) + end + + def valid_password?(_, _) do + Bcrypt.no_user_verify() + false + end + + @doc """ + Validates the current password otherwise adds an error to the changeset. + """ + def validate_current_password(changeset, password) do + if valid_password?(changeset.data, password) do + changeset + else + add_error(changeset, :current_password, "is not valid") + end + end +end diff --git a/lib/elixir_search_extractor/accounts/user_token.ex b/lib/elixir_search_extractor/accounts/user_token.ex new file mode 100644 index 0000000..b1d2da4 --- /dev/null +++ b/lib/elixir_search_extractor/accounts/user_token.ex @@ -0,0 +1,58 @@ +defmodule ElixirSearchExtractor.Accounts.UserToken do + use Ecto.Schema + import Ecto.Query + + @rand_size 32 + + @session_validity_in_days 60 + + schema "users_tokens" do + field :token, :binary + field :context, :string + field :sent_to, :string + belongs_to :user, ElixirSearchExtractor.Accounts.User + + timestamps(updated_at: false) + end + + @doc """ + Generates a token that will be stored in a signed place, + such as session or cookie. As they are signed, those + tokens do not need to be hashed. + """ + def build_session_token(user) do + token = :crypto.strong_rand_bytes(@rand_size) + + {token, + %ElixirSearchExtractor.Accounts.UserToken{token: token, context: "session", user_id: user.id}} + end + + @doc """ + Checks if the token is valid and returns its underlying lookup query. + + The query returns the user found by the token. + """ + def verify_session_token_query(token) do + query = + from token in token_and_context_query(token, "session"), + join: user in assoc(token, :user), + where: token.inserted_at > ago(@session_validity_in_days, "day"), + select: user + + {:ok, query} + end + + @doc """ + Returns the given token with the given context. + """ + def token_and_context_query(token, context) do + from ElixirSearchExtractor.Accounts.UserToken, where: [token: ^token, context: ^context] + end + + @doc """ + Gets all tokens for the given user for the given contexts. + """ + def user_and_contexts_query(user, :all) do + from t in ElixirSearchExtractor.Accounts.UserToken, where: t.user_id == ^user.id + end +end diff --git a/lib/elixir_search_extractor_web/controllers/user_auth.ex b/lib/elixir_search_extractor_web/controllers/user_auth.ex new file mode 100644 index 0000000..61284c2 --- /dev/null +++ b/lib/elixir_search_extractor_web/controllers/user_auth.ex @@ -0,0 +1,149 @@ +defmodule ElixirSearchExtractorWeb.UserAuth do + import Plug.Conn + import Phoenix.Controller + + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractorWeb.Router.Helpers, as: Routes + + # Make the remember me cookie valid for 60 days. + # If you want bump or reduce this value, also change + # the token expiry itself in UserToken. + @max_age 60 * 60 * 24 * 60 + @remember_me_cookie "_elixir_search_extractor_web_user_remember_me" + @remember_me_options [sign: true, max_age: @max_age, same_site: "Lax"] + + @doc """ + Logs the user in. + + It renews the session ID and clears the whole session + to avoid fixation attacks. See the renew_session + function to customize this behaviour. + + It also sets a `:live_socket_id` key in the session, + so LiveView sessions are identified and automatically + disconnected on log out. The line can be safely removed + if you are not using LiveView. + """ + def log_in_user(conn, user, params \\ %{}) do + token = Accounts.generate_user_session_token(user) + user_return_to = get_session(conn, :user_return_to) + + conn + |> renew_session() + |> put_session(:user_token, token) + |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}") + |> maybe_write_remember_me_cookie(token, params) + |> redirect(to: user_return_to || signed_in_path(conn)) + end + + defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do + put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options) + end + + defp maybe_write_remember_me_cookie(conn, _token, _params) do + conn + end + + # This function renews the session ID and erases the whole + # session to avoid fixation attacks. If there is any data + # in the session you may want to preserve after log in/log out, + # you must explicitly fetch the session data before clearing + # and then immediately set it after clearing, for example: + # + # defp renew_session(conn) do + # preferred_locale = get_session(conn, :preferred_locale) + # + # conn + # |> configure_session(renew: true) + # |> clear_session() + # |> put_session(:preferred_locale, preferred_locale) + # end + # + defp renew_session(conn) do + conn + |> configure_session(renew: true) + |> clear_session() + end + + @doc """ + Logs the user out. + + It clears all session data for safety. See renew_session. + """ + def log_out_user(conn) do + user_token = get_session(conn, :user_token) + user_token && Accounts.delete_session_token(user_token) + + if live_socket_id = get_session(conn, :live_socket_id) do + ElixirSearchExtractorWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{}) + end + + conn + |> renew_session() + |> delete_resp_cookie(@remember_me_cookie) + |> redirect(to: "/") + end + + @doc """ + Authenticates the user by looking into the session + and remember me token. + """ + def fetch_current_user(conn, _opts) do + {user_token, conn} = ensure_user_token(conn) + user = user_token && Accounts.get_user_by_session_token(user_token) + assign(conn, :current_user, user) + end + + defp ensure_user_token(conn) do + if user_token = get_session(conn, :user_token) do + {user_token, conn} + else + conn = fetch_cookies(conn, signed: [@remember_me_cookie]) + + if user_token = conn.cookies[@remember_me_cookie] do + {user_token, put_session(conn, :user_token, user_token)} + else + {nil, conn} + end + end + end + + @doc """ + Used for routes that require the user to not be authenticated. + """ + def redirect_if_user_is_authenticated(conn, _opts) do + if conn.assigns[:current_user] do + conn + |> redirect(to: signed_in_path(conn)) + |> halt() + else + conn + end + end + + @doc """ + Used for routes that require the user to be authenticated. + + If you want to enforce the user email is confirmed before + they use the application at all, here would be a good place. + """ + def require_authenticated_user(conn, _opts) do + if conn.assigns[:current_user] do + conn + else + conn + |> put_flash(:error, "You must log in to access this page.") + |> maybe_store_return_to() + |> redirect(to: Routes.user_session_path(conn, :new)) + |> halt() + end + end + + defp maybe_store_return_to(%{method: "GET"} = conn) do + put_session(conn, :user_return_to, current_path(conn)) + end + + defp maybe_store_return_to(conn), do: conn + + defp signed_in_path(_conn), do: "/" +end diff --git a/lib/elixir_search_extractor_web/controllers/user_registration_controller.ex b/lib/elixir_search_extractor_web/controllers/user_registration_controller.ex new file mode 100644 index 0000000..28d6899 --- /dev/null +++ b/lib/elixir_search_extractor_web/controllers/user_registration_controller.ex @@ -0,0 +1,24 @@ +defmodule ElixirSearchExtractorWeb.UserRegistrationController do + use ElixirSearchExtractorWeb, :controller + + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractor.Accounts.User + alias ElixirSearchExtractorWeb.UserAuth + + def new(conn, _params) do + changeset = Accounts.change_user_registration(%User{}) + render(conn, "new.html", changeset: changeset) + end + + def create(conn, %{"user" => user_params}) do + case Accounts.register_user(user_params) do + {:ok, user} -> + conn + |> put_flash(:info, "User created successfully.") + |> UserAuth.log_in_user(user) + + {:error, %Ecto.Changeset{} = changeset} -> + render(conn, "new.html", changeset: changeset) + end + end +end diff --git a/lib/elixir_search_extractor_web/controllers/user_session_controller.ex b/lib/elixir_search_extractor_web/controllers/user_session_controller.ex new file mode 100644 index 0000000..1ae7fbc --- /dev/null +++ b/lib/elixir_search_extractor_web/controllers/user_session_controller.ex @@ -0,0 +1,26 @@ +defmodule ElixirSearchExtractorWeb.UserSessionController do + use ElixirSearchExtractorWeb, :controller + + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractorWeb.UserAuth + + def new(conn, _params) do + render(conn, "new.html", error_message: nil) + end + + def create(conn, %{"user" => user_params}) do + %{"email" => email, "password" => password} = user_params + + if user = Accounts.get_user_by_email_and_password(email, password) do + UserAuth.log_in_user(conn, user, user_params) + else + render(conn, "new.html", error_message: "Invalid email or password") + end + end + + def delete(conn, _params) do + conn + |> put_flash(:info, "Logged out successfully.") + |> UserAuth.log_out_user() + end +end diff --git a/lib/elixir_search_extractor_web/controllers/user_settings_controller.ex b/lib/elixir_search_extractor_web/controllers/user_settings_controller.ex new file mode 100644 index 0000000..d847866 --- /dev/null +++ b/lib/elixir_search_extractor_web/controllers/user_settings_controller.ex @@ -0,0 +1,34 @@ +defmodule ElixirSearchExtractorWeb.UserSettingsController do + use ElixirSearchExtractorWeb, :controller + + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractorWeb.UserAuth + + plug :assign_password_changesets + + def edit(conn, _params) do + render(conn, "edit.html") + end + + def update(conn, %{"action" => "update_password"} = params) do + %{"current_password" => password, "user" => user_params} = params + user = conn.assigns.current_user + + case Accounts.update_user_password(user, password, user_params) do + {:ok, user} -> + conn + |> put_flash(:info, "Password updated successfully.") + |> put_session(:user_return_to, Routes.user_settings_path(conn, :edit)) + |> UserAuth.log_in_user(user) + + {:error, changeset} -> + render(conn, "edit.html", password_changeset: changeset) + end + end + + defp assign_password_changesets(conn, _opts) do + user = conn.assigns.current_user + + assign(conn, :password_changeset, Accounts.change_user_password(user)) + end +end diff --git a/lib/elixir_search_extractor_web/router.ex b/lib/elixir_search_extractor_web/router.ex index bcce258..468c932 100644 --- a/lib/elixir_search_extractor_web/router.ex +++ b/lib/elixir_search_extractor_web/router.ex @@ -1,12 +1,15 @@ defmodule ElixirSearchExtractorWeb.Router do use ElixirSearchExtractorWeb, :router + import ElixirSearchExtractorWeb.UserAuth + pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers + plug :fetch_current_user end # coveralls-ignore-start @@ -16,12 +19,6 @@ defmodule ElixirSearchExtractorWeb.Router do # coveralls-ignore-stop - scope "/", ElixirSearchExtractorWeb do - pipe_through :browser - - get "/", PageController, :index - end - # Other scopes may use custom stacks. # scope "/api", ElixirSearchExtractorWeb do # pipe_through :api @@ -44,4 +41,29 @@ defmodule ElixirSearchExtractorWeb.Router do # coveralls-ignore-stop end end + + ## Authentication routes + + scope "/", ElixirSearchExtractorWeb do + pipe_through [:browser, :require_authenticated_user] + + get "/", PageController, :index + get "/users/settings", UserSettingsController, :edit + put "/users/settings", UserSettingsController, :update + end + + scope "/", ElixirSearchExtractorWeb do + pipe_through [:browser, :redirect_if_user_is_authenticated] + + get "/users/register", UserRegistrationController, :new + post "/users/register", UserRegistrationController, :create + get "/users/log_in", UserSessionController, :new + post "/users/log_in", UserSessionController, :create + end + + scope "/", ElixirSearchExtractorWeb do + pipe_through [:browser] + + delete "/users/log_out", UserSessionController, :delete + end end diff --git a/lib/elixir_search_extractor_web/templates/page/index.html.eex b/lib/elixir_search_extractor_web/templates/page/index.html.eex index e4378f7..f9e551b 100644 --- a/lib/elixir_search_extractor_web/templates/page/index.html.eex +++ b/lib/elixir_search_extractor_web/templates/page/index.html.eex @@ -1,29 +1,7 @@ -

Welcome to Phoenix!

+

Dashboard!

-
- - - - - -
-
HOME
-
PROFILE
-
MESSAGE
-
SETTINGS
-
- -
+ diff --git a/lib/elixir_search_extractor_web/templates/user_registration/new.html.eex b/lib/elixir_search_extractor_web/templates/user_registration/new.html.eex new file mode 100644 index 0000000..54542e1 --- /dev/null +++ b/lib/elixir_search_extractor_web/templates/user_registration/new.html.eex @@ -0,0 +1,33 @@ +

Open an account!

+ +<%= form_for @changeset, Routes.user_registration_path(@conn, :create), fn f -> %> + <%= if @changeset.action do %> +
+

Oops, something went wrong! Please check the errors below.

+
+ <% end %> + + <%= label f, :name %> + <%= text_input f, :name, required: true %> + <%= error_tag f, :name %> + +<%= label f, :email %> + <%= email_input f, :email, required: true %> + <%= error_tag f, :email %> + + <%= label f, :password %> + <%= password_input f, :password, required: true %> + <%= error_tag f, :password %> + + <%= label f, :password_confirmation, "Confirm password" %> + <%= password_input f, :password_confirmation, required: true %> + <%= error_tag f, :password_confirmation %> + +
+ <%= submit "Register" %> +
+<% end %> + +

+ <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> +

diff --git a/lib/elixir_search_extractor_web/templates/user_session/new.html.eex b/lib/elixir_search_extractor_web/templates/user_session/new.html.eex new file mode 100644 index 0000000..ed2532b --- /dev/null +++ b/lib/elixir_search_extractor_web/templates/user_session/new.html.eex @@ -0,0 +1,27 @@ +

Log in to Extractor!

+ +<%= form_for @conn, Routes.user_session_path(@conn, :create), [as: :user], fn f -> %> + <%= if @error_message do %> +
+

<%= @error_message %>

+
+ <% end %> + + <%= label f, :email %> + <%= email_input f, :email, required: true %> + + <%= label f, :password %> + <%= password_input f, :password, required: true %> + + <%= label f, :remember_me, "Keep me logged in for 60 days" %> + <%= checkbox f, :remember_me %> + +
+ <%= submit "Log in" %> +
+<% end %> + +

+ <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> + <%#= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %> +

diff --git a/lib/elixir_search_extractor_web/templates/user_settings/edit.html.eex b/lib/elixir_search_extractor_web/templates/user_settings/edit.html.eex new file mode 100644 index 0000000..3fe9f41 --- /dev/null +++ b/lib/elixir_search_extractor_web/templates/user_settings/edit.html.eex @@ -0,0 +1,29 @@ +

Settings

+ +

Change password

+ +<%= form_for @password_changeset, Routes.user_settings_path(@conn, :update), fn f -> %> + <%= if @password_changeset.action do %> +
+

Oops, something went wrong! Please check the errors below.

+
+ <% end %> + + <%= hidden_input f, :action, name: "action", value: "update_password" %> + + <%= label f, :password, "New password" %> + <%= password_input f, :password, required: true %> + <%= error_tag f, :password %> + + <%= label f, :password_confirmation, "Confirm new password" %> + <%= password_input f, :password_confirmation, required: true %> + <%= error_tag f, :password_confirmation %> + + <%= label f, :current_password, for: "current_password_for_password" %> + <%= password_input f, :current_password, required: true, name: "current_password", id: "current_password_for_password" %> + <%= error_tag f, :current_password %> + +
+ <%= submit "Change password" %> +
+<% end %> diff --git a/lib/elixir_search_extractor_web/views/user_registration_view.ex b/lib/elixir_search_extractor_web/views/user_registration_view.ex new file mode 100644 index 0000000..bc4e156 --- /dev/null +++ b/lib/elixir_search_extractor_web/views/user_registration_view.ex @@ -0,0 +1,3 @@ +defmodule ElixirSearchExtractorWeb.UserRegistrationView do + use ElixirSearchExtractorWeb, :view +end diff --git a/lib/elixir_search_extractor_web/views/user_session_view.ex b/lib/elixir_search_extractor_web/views/user_session_view.ex new file mode 100644 index 0000000..bcbf0c0 --- /dev/null +++ b/lib/elixir_search_extractor_web/views/user_session_view.ex @@ -0,0 +1,3 @@ +defmodule ElixirSearchExtractorWeb.UserSessionView do + use ElixirSearchExtractorWeb, :view +end diff --git a/lib/elixir_search_extractor_web/views/user_settings_view.ex b/lib/elixir_search_extractor_web/views/user_settings_view.ex new file mode 100644 index 0000000..eafdd3f --- /dev/null +++ b/lib/elixir_search_extractor_web/views/user_settings_view.ex @@ -0,0 +1,3 @@ +defmodule ElixirSearchExtractorWeb.UserSettingsView do + use ElixirSearchExtractorWeb, :view +end diff --git a/mix.exs b/mix.exs index 9ad8117..ac19b24 100644 --- a/mix.exs +++ b/mix.exs @@ -40,6 +40,7 @@ defmodule ElixirSearchExtractor.MixProject do # Type `mix help deps` for examples and options. defp deps do [ + {:bcrypt_elixir, "~> 2.0"}, {:wallaby, "~> 0.28.0", [only: :test, runtime: false]}, {:sobelow, "~> 0.11.1", [only: [:dev, :test], runtime: false]}, {:exvcr, "~> 0.12.3", [only: :test]}, @@ -61,7 +62,8 @@ defmodule ElixirSearchExtractor.MixProject do {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, - {:nimble_template, "~> 3.0", only: :dev, runtime: false} + {:nimble_template, "~> 3.0", only: :dev, runtime: false}, + {:phx_gen_auth, "~> 0.7", only: :dev, runtime: false} ] end diff --git a/mix.lock b/mix.lock index 573467a..e98c67c 100644 --- a/mix.lock +++ b/mix.lock @@ -1,6 +1,8 @@ %{ + "bcrypt_elixir": {:hex, :bcrypt_elixir, "2.3.0", "6cb662d5c1b0a8858801cf20997bd006e7016aa8c52959c9ef80e0f34fb60b7a", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "2c81d61d4f6ed0e5cf7bf27a9109b791ff216a1034b3d541327484f46dd43769"}, "bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm", "7af5c7e09fe1d40f76c8e4f9dd2be7cebd83909f31fee7cd0e9eadc567da8353"}, "certifi": {:hex, :certifi, "2.6.1", "dbab8e5e155a0763eea978c913ca280a6b544bfa115633fa20249c3d396d9493", [:rebar3], [], "hexpm", "524c97b4991b3849dd5c17a631223896272c6b0af446778ba4675a1dff53bb7e"}, + "comeonin": {:hex, :comeonin, "5.3.2", "5c2f893d05c56ae3f5e24c1b983c2d5dfb88c6d979c9287a76a7feb1e1d8d646", [:mix], [], "hexpm", "d0993402844c49539aeadb3fe46a3c9bd190f1ecf86b6f9ebd71957534c95f04"}, "connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"}, "cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"}, "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.3.1", "ebd1a1d7aff97f27c66654e78ece187abdc646992714164380d8a041eda16754", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "3a6efd3366130eab84ca372cbd4a7d3c3a97bdfcfb4911233b035d117063f0af"}, @@ -11,6 +13,7 @@ "dialyxir": {:hex, :dialyxir, "1.1.0", "c5aab0d6e71e5522e77beff7ba9e08f8e02bad90dfbeffae60eaf0cb47e29488", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "07ea8e49c45f15264ebe6d5b93799d4dd56a44036cf42d0ad9c960bc266c0b9a"}, "ecto": {:hex, :ecto, "3.6.1", "7bb317e3fd0179ad725069fd0fe8a28ebe48fec6282e964ea502e4deccb0bd0f", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "cbb3294a990447b19f0725488a749f8cf806374e0d9d0dffc45d61e7aeaf6553"}, "ecto_sql": {:hex, :ecto_sql, "3.6.1", "8774dc3fc0ff7b6be510858b99883640f990c0736b8ab54588f9a0c91807f909", [:mix], [{:db_connection, "~> 2.2", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.6.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.4.0 or ~> 0.5.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.15.0 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "66f35c3f2d5978b6bffebd1e6351ab8c9d6b68650d62abd1ab8d149de40e0779"}, + "elixir_make": {:hex, :elixir_make, "0.6.2", "7dffacd77dec4c37b39af867cedaabb0b59f6a871f89722c25b28fcd4bd70530", [:mix], [], "hexpm", "03e49eadda22526a7e5279d53321d1cced6552f344ba4e03e619063de75348d9"}, "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, "ex_machina": {:hex, :ex_machina, "2.7.0", "b792cc3127fd0680fecdb6299235b4727a4944a09ff0fa904cc639272cd92dc7", [:mix], [{:ecto, "~> 2.2 or ~> 3.0", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_sql, "~> 3.0", [hex: :ecto_sql, repo: "hexpm", optional: true]}], "hexpm", "419aa7a39bde11894c87a615c4ecaa52d8f107bbdd81d810465186f783245bf8"}, "exactor": {:hex, :exactor, "2.2.4", "5efb4ddeb2c48d9a1d7c9b465a6fffdd82300eb9618ece5d34c3334d5d7245b1", [:mix], [], "hexpm", "1222419f706e01bfa1095aec9acf6421367dcfab798a6f67c54cf784733cd6b5"}, @@ -39,6 +42,7 @@ "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.3.1", "9eba6ad16bd80c45f338b2059c7b255ce30784d76f4181304e7b78640e5a7513", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "f3ae26b5abb85a1cb2bc8bb199e29fbcefb34259e469b31fe0c6323f2175a5ef"}, "phoenix_live_view": {:hex, :phoenix_live_view, "0.15.5", "153f15022ff03162201cfbd3de73115f3a6e868bc8a3c07b86a8e984de6a57e2", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.5.7", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 0.5", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "00c80cf27365bdeb44c694b1dc8cf950b4b26141307df340d39a9be47d8dc1ef"}, "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.0.0", "a1ae76717bb168cdeb10ec9d92d1480fec99e3080f011402c0a2d68d47395ffb", [:mix], [], "hexpm", "c52d948c4f261577b9c6fa804be91884b381a7f8f18450c5045975435350f771"}, + "phx_gen_auth": {:hex, :phx_gen_auth, "0.7.0", "2e10e9527b6b71abbfbb4601c7dc4aa4fb9f2db6f9a6be457c468b7f2b0f6319", [:mix], [{:phoenix, "~> 1.5.2", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "b9dc3e3b866e67c5db8f00f4a2adb28fc8636e794f78600e35aba0e55bdac209"}, "plug": {:hex, :plug, "1.11.1", "f2992bac66fdae679453c9e86134a4201f6f43a687d8ff1cd1b2862d53c80259", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "23524e4fefbb587c11f0833b3910bfb414bf2e2534d61928e920f54e3a1b881f"}, "plug_cowboy": {:hex, :plug_cowboy, "2.5.0", "51c998f788c4e68fc9f947a5eba8c215fbb1d63a520f7604134cab0270ea6513", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "5b2c8925a5e2587446f33810a58c01e66b3c345652eeec809b76ba007acde71a"}, "plug_crypto": {:hex, :plug_crypto, "1.2.2", "05654514ac717ff3a1843204b424477d9e60c143406aa94daf2274fdd280794d", [:mix], [], "hexpm", "87631c7ad914a5a445f0a3809f99b079113ae4ed4b867348dd9eec288cecb6db"}, diff --git a/priv/repo/migrations/20210525092336_create_users_auth_tables.exs b/priv/repo/migrations/20210525092336_create_users_auth_tables.exs new file mode 100644 index 0000000..947767f --- /dev/null +++ b/priv/repo/migrations/20210525092336_create_users_auth_tables.exs @@ -0,0 +1,28 @@ +defmodule ElixirSearchExtractor.Repo.Migrations.CreateUsersAuthTables do + use Ecto.Migration + + def change do + execute "CREATE EXTENSION IF NOT EXISTS citext", "" + + create table(:users) do + add :email, :citext, null: false + add :name, :string, null: false + add :hashed_password, :string, null: false + add :confirmed_at, :naive_datetime + timestamps() + end + + create unique_index(:users, [:email]) + + create table(:users_tokens) do + add :user_id, references(:users, on_delete: :delete_all), null: false + add :token, :binary, null: false + add :context, :string, null: false + add :sent_to, :string + timestamps(updated_at: false) + end + + create index(:users_tokens, [:user_id]) + create unique_index(:users_tokens, [:context, :token]) + end +end diff --git a/test/elixir_search_extractor/accounts_test.exs b/test/elixir_search_extractor/accounts_test.exs new file mode 100644 index 0000000..0e56813 --- /dev/null +++ b/test/elixir_search_extractor/accounts_test.exs @@ -0,0 +1,266 @@ +defmodule ElixirSearchExtractor.AccountsTest do + use ElixirSearchExtractor.DataCase + + import ElixirSearchExtractor.AccountsFixtures + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractor.Accounts.{User, UserToken} + + describe "get_user_by_email/1" do + test "does not return the user if the email does not exist" do + refute Accounts.get_user_by_email("unknown@example.com") + end + + test "returns the user if the email exists" do + %{id: id} = user = user_fixture() + assert %User{id: ^id} = Accounts.get_user_by_email(user.email) + end + end + + describe "get_user_by_email_and_password/2" do + test "does not return the user if the email does not exist" do + refute Accounts.get_user_by_email_and_password("unknown@example.com", "hello world!") + end + + test "does not return the user if the password is not valid" do + user = user_fixture() + refute Accounts.get_user_by_email_and_password(user.email, "invalid") + end + + test "returns the user if the email and password are valid" do + %{id: id} = user = user_fixture() + + assert %User{id: ^id} = + Accounts.get_user_by_email_and_password(user.email, valid_user_password()) + end + end + + describe "get_user!/1" do + test "raises if id is invalid" do + assert_raise Ecto.NoResultsError, fn -> + Accounts.get_user!(-1) + end + end + + test "returns the user with the given id" do + %{id: id} = user = user_fixture() + assert %User{id: ^id} = Accounts.get_user!(user.id) + end + end + + describe "register_user/1" do + test "requires name, email and password to be set" do + {:error, changeset} = Accounts.register_user(%{}) + + assert %{ + password: ["can't be blank"], + name: ["can't be blank"], + email: ["can't be blank"] + } = errors_on(changeset) + end + + test "validates email and password when given" do + {:error, changeset} = + Accounts.register_user(%{ + email: "not valid", + name: "bad", + password: "bad", + password_confirmation: "not matching" + }) + + assert %{ + email: ["must have the @ sign and no spaces"], + name: ["should be at least 5 character(s)"], + password: ["should be at least 6 character(s)"], + password_confirmation: ["does not match password"] + } = 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, name: too_long, password: too_long}) + + assert "should be at most 80 character(s)" in errors_on(changeset).email + assert "should be at most 80 character(s)" in errors_on(changeset).name + assert "should be at most 30 character(s)" in errors_on(changeset).password + end + + test "validates email uniqueness" do + %{email: email} = user_fixture() + {:error, changeset} = Accounts.register_user(%{email: email}) + assert "has already been taken" in errors_on(changeset).email + + # Now try with the upper cased email too, to check that email case is ignored. + {:error, uppercase_email_changeset} = Accounts.register_user(%{email: String.upcase(email)}) + assert "has already been taken" in errors_on(uppercase_email_changeset).email + end + + test "registers users with a hashed password" do + email = unique_user_email() + {:ok, user} = Accounts.register_user(valid_user_attributes(email: email)) + + assert user.email == email + assert is_binary(user.hashed_password) + assert is_nil(user.confirmed_at) + assert is_nil(user.password) + end + end + + describe "change_user_registration/2" do + test "returns a changeset" do + assert %Ecto.Changeset{} = changeset = Accounts.change_user_registration(%User{}) + assert changeset.required == [:password, :name, :email] + end + + test "allows fields to be set" do + email = unique_user_email() + name = valid_user_name() + password = valid_user_password() + + changeset = + Accounts.change_user_registration( + %User{}, + valid_user_attributes(name: name, email: email, password: password) + ) + + assert changeset.valid? + assert get_change(changeset, :email) == email + assert get_change(changeset, :name) == name + assert get_change(changeset, :password) == password + assert is_nil(get_change(changeset, :hashed_password)) + end + end + + describe "change_user_password/2" do + test "returns a user changeset" do + assert %Ecto.Changeset{} = changeset = Accounts.change_user_password(%User{}) + assert changeset.required == [:password] + end + + test "allows fields to be set" do + changeset = + Accounts.change_user_password(%User{}, %{ + "password" => "new valid password" + }) + + assert changeset.valid? + assert get_change(changeset, :password) == "new valid password" + assert is_nil(get_change(changeset, :hashed_password)) + end + end + + describe "update_user_password/3" do + setup do + %{user: user_fixture()} + end + + test "validates password", %{user: user} do + {:error, changeset} = + Accounts.update_user_password(user, valid_user_password(), %{ + password: "bad", + password_confirmation: "another" + }) + + assert %{ + password: ["should be at least 6 character(s)"], + password_confirmation: ["does not match password"] + } = errors_on(changeset) + end + + test "validates maximum values for password for security", %{user: user} do + too_long = String.duplicate("db", 100) + + {:error, changeset} = + Accounts.update_user_password(user, valid_user_password(), %{password: too_long}) + + assert "should be at most 30 character(s)" in errors_on(changeset).password + end + + test "validates current password", %{user: user} do + {:error, changeset} = + Accounts.update_user_password(user, "invalid", %{password: valid_user_password()}) + + assert %{current_password: ["is not valid"]} = errors_on(changeset) + end + + test "updates the password", %{user: user} do + {:ok, user} = + Accounts.update_user_password(user, valid_user_password(), %{ + password: "new valid password" + }) + + assert is_nil(user.password) + assert Accounts.get_user_by_email_and_password(user.email, "new valid password") + end + + test "deletes all tokens for the given user", %{user: user} do + _ = Accounts.generate_user_session_token(user) + + {:ok, _} = + Accounts.update_user_password(user, valid_user_password(), %{ + password: "new valid password" + }) + + refute Repo.get_by(UserToken, user_id: user.id) + end + end + + describe "generate_user_session_token/1" do + setup do + %{user: user_fixture()} + end + + test "generates a token", %{user: user} do + token = Accounts.generate_user_session_token(user) + assert user_token = Repo.get_by(UserToken, token: token) + assert user_token.context == "session" + + # Creating the same token for another user should fail + assert_raise Ecto.ConstraintError, fn -> + Repo.insert!(%UserToken{ + token: user_token.token, + user_id: user_fixture().id, + context: "session" + }) + end + end + end + + describe "get_user_by_session_token/1" do + setup do + user = user_fixture() + token = Accounts.generate_user_session_token(user) + %{user: user, token: token} + end + + test "returns user by token", %{user: user, token: token} do + assert session_user = Accounts.get_user_by_session_token(token) + assert session_user.id == user.id + end + + test "does not return user for invalid token" do + refute Accounts.get_user_by_session_token("oops") + end + + test "does not return user for expired token", %{token: token} do + {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) + refute Accounts.get_user_by_session_token(token) + end + end + + describe "delete_session_token/1" do + test "deletes the token" do + user = user_fixture() + token = Accounts.generate_user_session_token(user) + assert Accounts.delete_session_token(token) == :ok + refute Accounts.get_user_by_session_token(token) + end + end + + describe "inspect/2" do + test "does not include password" do + refute inspect(%User{password: "123456"}) =~ "password: \"123456\"" + end + end +end diff --git a/test/elixir_search_extractor_web/controllers/page_controller_test.exs b/test/elixir_search_extractor_web/controllers/page_controller_test.exs index 4ab2e36..77e4517 100644 --- a/test/elixir_search_extractor_web/controllers/page_controller_test.exs +++ b/test/elixir_search_extractor_web/controllers/page_controller_test.exs @@ -1,8 +1,15 @@ defmodule ElixirSearchExtractorWeb.PageControllerTest do use ElixirSearchExtractorWeb.ConnCase - test "GET /", %{conn: conn} do - conn = get(conn, "/") - assert html_response(conn, 200) =~ "Welcome to Phoenix!" + import ElixirSearchExtractor.AccountsFixtures + + setup do + %{user: user_fixture()} + end + + test "GET /", %{conn: conn, user: user} do + conn = conn |> log_in_user(user) |> get(Routes.user_session_path(conn, :new)) + home_url = get(conn, "/") + assert html_response(home_url, 200) =~ "Dashboard!" end end diff --git a/test/elixir_search_extractor_web/controllers/user_auth_test.exs b/test/elixir_search_extractor_web/controllers/user_auth_test.exs new file mode 100644 index 0000000..2f083e5 --- /dev/null +++ b/test/elixir_search_extractor_web/controllers/user_auth_test.exs @@ -0,0 +1,173 @@ +defmodule ElixirSearchExtractorWeb.UserAuthTest do + use ElixirSearchExtractorWeb.ConnCase, async: true + + import ElixirSearchExtractor.AccountsFixtures + alias ElixirSearchExtractor.Accounts + alias ElixirSearchExtractorWeb.UserAuth + + @remember_me_cookie "_elixir_search_extractor_web_user_remember_me" + + setup %{conn: conn} do + conn = + conn + |> Map.replace!(:secret_key_base, ElixirSearchExtractorWeb.Endpoint.config(:secret_key_base)) + |> init_test_session(%{}) + + %{user: user_fixture(), conn: conn} + end + + describe "log_in_user/3" do + test "stores the user token in the session", %{conn: conn, user: user} do + conn = UserAuth.log_in_user(conn, user) + assert token = get_session(conn, :user_token) + assert get_session(conn, :live_socket_id) == "users_sessions:#{Base.url_encode64(token)}" + assert redirected_to(conn) == "/" + assert Accounts.get_user_by_session_token(token) + end + + test "clears everything previously stored in the session", %{conn: conn, user: user} do + conn = conn |> put_session(:to_be_removed, "value") |> UserAuth.log_in_user(user) + refute get_session(conn, :to_be_removed) + end + + test "redirects to the configured path", %{conn: conn, user: user} do + conn = conn |> put_session(:user_return_to, "/hello") |> UserAuth.log_in_user(user) + assert redirected_to(conn) == "/hello" + end + + test "writes a cookie if remember_me is configured", %{conn: conn, user: user} do + conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"}) + assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie] + + assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie] + assert signed_token != get_session(conn, :user_token) + assert max_age == 5_184_000 + end + end + + describe "logout_user/1" do + test "erases session and cookies", %{conn: conn, user: user} do + user_token = Accounts.generate_user_session_token(user) + + conn = + conn + |> put_session(:user_token, user_token) + |> put_req_cookie(@remember_me_cookie, user_token) + |> fetch_cookies() + |> UserAuth.log_out_user() + + refute get_session(conn, :user_token) + refute conn.cookies[@remember_me_cookie] + assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie] + assert redirected_to(conn) == "/" + refute Accounts.get_user_by_session_token(user_token) + end + + test "broadcasts to the given live_socket_id", %{conn: conn} do + live_socket_id = "users_sessions:abcdef-token" + ElixirSearchExtractorWeb.Endpoint.subscribe(live_socket_id) + + conn + |> put_session(:live_socket_id, live_socket_id) + |> UserAuth.log_out_user() + + assert_receive %Phoenix.Socket.Broadcast{ + event: "disconnect", + topic: "users_sessions:abcdef-token" + } + end + + test "works even if user is already logged out", %{conn: conn} do + conn = conn |> fetch_cookies() |> UserAuth.log_out_user() + refute get_session(conn, :user_token) + assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie] + assert redirected_to(conn) == "/" + end + end + + describe "fetch_current_user/2" do + test "authenticates user from session", %{conn: conn, user: user} do + user_token = Accounts.generate_user_session_token(user) + conn = conn |> put_session(:user_token, user_token) |> UserAuth.fetch_current_user([]) + assert conn.assigns.current_user.id == user.id + end + + test "authenticates user from cookies", %{conn: conn, user: user} do + logged_in_conn = + conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"}) + + user_token = logged_in_conn.cookies[@remember_me_cookie] + %{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie] + + conn = + conn + |> put_req_cookie(@remember_me_cookie, signed_token) + |> UserAuth.fetch_current_user([]) + + assert get_session(conn, :user_token) == user_token + assert conn.assigns.current_user.id == user.id + end + + test "does not authenticate if data is missing", %{conn: conn, user: user} do + _ = Accounts.generate_user_session_token(user) + conn = UserAuth.fetch_current_user(conn, []) + refute get_session(conn, :user_token) + refute conn.assigns.current_user + end + end + + describe "redirect_if_user_is_authenticated/2" do + test "redirects if user is authenticated", %{conn: conn, user: user} do + conn = conn |> assign(:current_user, user) |> UserAuth.redirect_if_user_is_authenticated([]) + assert conn.halted + assert redirected_to(conn) == "/" + end + + test "does not redirect if user is not authenticated", %{conn: conn} do + conn = UserAuth.redirect_if_user_is_authenticated(conn, []) + refute conn.halted + refute conn.status + end + end + + describe "require_authenticated_user/2" do + test "redirects if user is not authenticated", %{conn: conn} do + conn = conn |> fetch_flash() |> UserAuth.require_authenticated_user([]) + assert conn.halted + assert redirected_to(conn) == Routes.user_session_path(conn, :new) + assert get_flash(conn, :error) == "You must log in to access this page." + end + + test "stores the path to redirect to on GET", %{conn: conn} do + halted_conn_with_path = + %{conn | request_path: "/foo", query_string: ""} + |> fetch_flash() + |> UserAuth.require_authenticated_user([]) + + assert halted_conn_with_path.halted + assert get_session(halted_conn_with_path, :user_return_to) == "/foo" + + halted_conn_with_query = + %{conn | request_path: "/foo", query_string: "bar=baz"} + |> fetch_flash() + |> UserAuth.require_authenticated_user([]) + + assert halted_conn_with_query.halted + assert get_session(halted_conn_with_query, :user_return_to) == "/foo?bar=baz" + + halted_conn_with_method = + %{conn | request_path: "/foo?bar", method: "POST"} + |> fetch_flash() + |> UserAuth.require_authenticated_user([]) + + assert halted_conn_with_method.halted + refute get_session(halted_conn_with_method, :user_return_to) + end + + test "does not redirect if user is authenticated", %{conn: conn, user: user} do + conn = conn |> assign(:current_user, user) |> UserAuth.require_authenticated_user([]) + refute conn.halted + refute conn.status + end + end +end diff --git a/test/elixir_search_extractor_web/controllers/user_registration_controller_test.exs b/test/elixir_search_extractor_web/controllers/user_registration_controller_test.exs new file mode 100644 index 0000000..f7cade7 --- /dev/null +++ b/test/elixir_search_extractor_web/controllers/user_registration_controller_test.exs @@ -0,0 +1,57 @@ +defmodule ElixirSearchExtractorWeb.UserRegistrationControllerTest do + use ElixirSearchExtractorWeb.ConnCase, async: true + + import ElixirSearchExtractor.AccountsFixtures + + describe "GET /users/register" do + test "renders registration page", %{conn: conn} do + conn = get(conn, Routes.user_registration_path(conn, :new)) + response = html_response(conn, 200) + assert response =~ "

Open an account!

" + end + + test "redirects if already logged in", %{conn: conn} do + conn = conn |> log_in_user(user_fixture()) |> get(Routes.user_registration_path(conn, :new)) + assert redirected_to(conn) == "/" + end + end + + describe "POST /users/register" do + @tag :capture_log + test "creates account and logs the user in", %{conn: conn} do + email = unique_user_email() + + conn = + post(conn, Routes.user_registration_path(conn, :create), %{ + "user" => valid_user_attributes(email: email) + }) + + assert get_session(conn, :user_token) + assert redirected_to(conn) =~ "/" + + # Now do a logged in request and assert on the menu + login_conn = get(conn, "/") + response = html_response(login_conn, 200) + assert response =~ "User created successfully." + end + + test "render errors for invalid data", %{conn: conn} do + conn = + post(conn, Routes.user_registration_path(conn, :create), %{ + "user" => %{ + "name" => "Test", + "email" => "with spaces", + "password" => "short", + "password_confirmation" => "does not match" + } + }) + + response = html_response(conn, 200) + assert response =~ "

Open an account!

" + assert response =~ "should be at least 5 character" + assert response =~ "must have the @ sign and no spaces" + assert response =~ "should be at least 6 character" + assert response =~ "does not match password" + end + end +end diff --git a/test/elixir_search_extractor_web/controllers/user_session_controller_test.exs b/test/elixir_search_extractor_web/controllers/user_session_controller_test.exs new file mode 100644 index 0000000..97d90b0 --- /dev/null +++ b/test/elixir_search_extractor_web/controllers/user_session_controller_test.exs @@ -0,0 +1,98 @@ +defmodule ElixirSearchExtractorWeb.UserSessionControllerTest do + use ElixirSearchExtractorWeb.ConnCase, async: true + + import ElixirSearchExtractor.AccountsFixtures + + setup do + %{user: user_fixture()} + end + + describe "GET /users/log_in" do + test "renders log in page", %{conn: conn} do + conn = get(conn, Routes.user_session_path(conn, :new)) + response = html_response(conn, 200) + assert response =~ "

Log in to Extractor!

" + assert response =~ "Log in" + assert response =~ "Register" + end + + test "redirects if already logged in", %{conn: conn, user: user} do + conn = conn |> log_in_user(user) |> get(Routes.user_session_path(conn, :new)) + assert redirected_to(conn) == "/" + end + end + + describe "POST /users/log_in" do + test "logs the user in", %{conn: conn, user: user} do + conn = + post(conn, Routes.user_session_path(conn, :create), %{ + "user" => %{"email" => user.email, "password" => valid_user_password()} + }) + + assert get_session(conn, :user_token) + assert redirected_to(conn) =~ "/" + + # Now do a logged in request and assert on the menu + login_conn = get(conn, "/") + response = html_response(login_conn, 200) + assert response =~ user.name + # assert response =~ "Settings" + assert response =~ "Log out" + end + + test "logs the user in with remember me", %{conn: conn, user: user} do + conn = + post(conn, Routes.user_session_path(conn, :create), %{ + "user" => %{ + "email" => user.email, + "password" => valid_user_password(), + "remember_me" => "true" + } + }) + + assert conn.resp_cookies["_elixir_search_extractor_web_user_remember_me"] + assert redirected_to(conn) =~ "/" + end + + test "logs the user in with return to", %{conn: conn, user: user} do + conn = + conn + |> init_test_session(user_return_to: "/foo/bar") + |> post(Routes.user_session_path(conn, :create), %{ + "user" => %{ + "email" => user.email, + "password" => valid_user_password() + } + }) + + assert redirected_to(conn) == "/foo/bar" + end + + test "emits error message with invalid credentials", %{conn: conn, user: user} do + conn = + post(conn, Routes.user_session_path(conn, :create), %{ + "user" => %{"email" => user.email, "password" => "invalid_password"} + }) + + response = html_response(conn, 200) + assert response =~ "

Log in to Extractor!

" + assert response =~ "Invalid email or password" + end + end + + describe "DELETE /users/log_out" do + test "logs the user out", %{conn: conn, user: user} do + conn = conn |> log_in_user(user) |> delete(Routes.user_session_path(conn, :delete)) + assert redirected_to(conn) == "/" + refute get_session(conn, :user_token) + assert get_flash(conn, :info) =~ "Logged out successfully" + end + + test "succeeds even if the user is not logged in", %{conn: conn} do + conn = delete(conn, Routes.user_session_path(conn, :delete)) + assert redirected_to(conn) == "/" + refute get_session(conn, :user_token) + assert get_flash(conn, :info) =~ "Logged out successfully" + end + end +end diff --git a/test/elixir_search_extractor_web/controllers/user_settings_controller_test.exs b/test/elixir_search_extractor_web/controllers/user_settings_controller_test.exs new file mode 100644 index 0000000..b2165fc --- /dev/null +++ b/test/elixir_search_extractor_web/controllers/user_settings_controller_test.exs @@ -0,0 +1,61 @@ +defmodule ElixirSearchExtractorWeb.UserSettingsControllerTest do + use ElixirSearchExtractorWeb.ConnCase, async: true + + import ElixirSearchExtractor.AccountsFixtures + alias ElixirSearchExtractor.Accounts + + setup :register_and_log_in_user + + describe "GET /users/settings" do + test "renders settings page", %{conn: conn} do + conn = get(conn, Routes.user_settings_path(conn, :edit)) + response = html_response(conn, 200) + assert response =~ "

Settings

" + end + + test "redirects if user is not logged in" do + conn = build_conn() + settings_conn = get(conn, Routes.user_settings_path(conn, :edit)) + assert redirected_to(settings_conn) == Routes.user_session_path(settings_conn, :new) + end + end + + describe "PUT /users/settings (change password form)" do + test "updates the user password and resets tokens", %{conn: conn, user: user} do + new_password_conn = + put(conn, Routes.user_settings_path(conn, :update), %{ + "action" => "update_password", + "current_password" => valid_user_password(), + "user" => %{ + "password" => "new valid password", + "password_confirmation" => "new valid password" + } + }) + + assert redirected_to(new_password_conn) == Routes.user_settings_path(conn, :edit) + assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token) + assert get_flash(new_password_conn, :info) =~ "Password updated successfully" + assert Accounts.get_user_by_email_and_password(user.email, "new valid password") + end + + test "does not update password on invalid data", %{conn: conn} do + old_password_conn = + put(conn, Routes.user_settings_path(conn, :update), %{ + "action" => "update_password", + "current_password" => "invalid", + "user" => %{ + "password" => "short", + "password_confirmation" => "does not match" + } + }) + + response = html_response(old_password_conn, 200) + assert response =~ "

Settings

" + assert response =~ "should be at least 6 character(s)" + assert response =~ "does not match password" + assert response =~ "is not valid" + + assert get_session(old_password_conn, :user_token) == get_session(conn, :user_token) + end + end +end diff --git a/test/elixir_search_extractor_web/features/authentication_page/login_page_test.exs b/test/elixir_search_extractor_web/features/authentication_page/login_page_test.exs new file mode 100644 index 0000000..9191b95 --- /dev/null +++ b/test/elixir_search_extractor_web/features/authentication_page/login_page_test.exs @@ -0,0 +1,15 @@ +defmodule ElixirSearchExtractorWeb.AuthenticationPage.LoginPageTest do + use ElixirSearchExtractorWeb.FeatureCase, async: true + + feature "view log in page", %{session: session} do + session + |> visit(Routes.user_session_path(ElixirSearchExtractorWeb.Endpoint, :new)) + |> assert_has(Query.text("Log in to Extractor!")) + end + + feature "view dashboard after successful log in", %{session: session} do + session + |> register_and_login() + |> assert_has(Query.text("Dashboard!")) + end +end diff --git a/test/elixir_search_extractor_web/features/authentication_page/signup_page_test.exs b/test/elixir_search_extractor_web/features/authentication_page/signup_page_test.exs new file mode 100644 index 0000000..8481599 --- /dev/null +++ b/test/elixir_search_extractor_web/features/authentication_page/signup_page_test.exs @@ -0,0 +1,29 @@ +defmodule ElixirSearchExtractorWeb.AuthenticationPage.SignupPageTest do + use ElixirSearchExtractorWeb.FeatureCase, async: true + + feature "view sign up page", %{session: session} do + session + |> visit(Routes.user_registration_path(ElixirSearchExtractorWeb.Endpoint, :new)) + |> assert_has(Query.text("Open an account!")) + end + + feature "view dashboard after successful sign up", %{session: session} do + session + |> signup() + |> assert_has(Query.text("Dashboard!")) + end + + defp signup(session) do + user_attributes = valid_user_attributes() + + session + |> visit(Routes.user_registration_path(ElixirSearchExtractorWeb.Endpoint, :new)) + |> fill_in(Wallaby.Query.text_field("user_name"), with: user_attributes.name) + |> fill_in(Wallaby.Query.text_field("user_email"), with: user_attributes.email) + |> fill_in(Wallaby.Query.text_field("user_password"), with: user_attributes.password) + |> fill_in(Wallaby.Query.text_field("user_password_confirmation"), + with: user_attributes.password_confirmation + ) + |> click(Wallaby.Query.button("Register")) + end +end diff --git a/test/elixir_search_extractor_web/features/home_page/view_home_page_test.exs b/test/elixir_search_extractor_web/features/home_page/view_home_page_test.exs index 3d4855e..6b169f5 100644 --- a/test/elixir_search_extractor_web/features/home_page/view_home_page_test.exs +++ b/test/elixir_search_extractor_web/features/home_page/view_home_page_test.exs @@ -1,9 +1,10 @@ defmodule ElixirSearchExtractorWeb.HomePage.ViewHomePageTest do - use ElixirSearchExtractorWeb.FeatureCase + use ElixirSearchExtractorWeb.FeatureCase, async: true feature "view home page", %{session: session} do - visit(session, Routes.page_path(ElixirSearchExtractorWeb.Endpoint, :index)) - - assert_has(session, Query.text("Welcome to Phoenix!")) + session + |> register_and_login() + |> visit(Routes.page_path(ElixirSearchExtractorWeb.Endpoint, :index)) + |> assert_has(Query.text("Dashboard!")) end end diff --git a/test/elixir_search_extractor_web/features/settings_page/settings_page_test.exs b/test/elixir_search_extractor_web/features/settings_page/settings_page_test.exs new file mode 100644 index 0000000..6dfd9c4 --- /dev/null +++ b/test/elixir_search_extractor_web/features/settings_page/settings_page_test.exs @@ -0,0 +1,37 @@ +defmodule ElixirSearchExtractorWeb.SettingsPage.SettingsPageTest do + use ElixirSearchExtractorWeb.FeatureCase, async: true + + feature "view settings page", %{session: session} do + session + |> register_and_login() + |> visit(Routes.user_settings_path(ElixirSearchExtractorWeb.Endpoint, :edit)) + |> assert_has(Query.text("Settings")) + end + + feature "user can change password if correct current password is given", %{session: session} do + password = "current_password" + + session + |> register_and_login(password) + |> change_password(password) + |> assert_has(Query.text("Password updated successfully.")) + end + + feature "user can not change password if incorrect current password is given", %{session: session} do + password = "invalid_current_password" + + session + |> register_and_login() + |> change_password(password) + |> assert_has(Query.text("Oops, something went wrong!")) + end + + defp change_password(session, password) do + session + |> visit(Routes.user_settings_path(ElixirSearchExtractorWeb.Endpoint, :edit)) + |> fill_in(Wallaby.Query.text_field("user_password"), with: "new_password") + |> fill_in(Wallaby.Query.text_field("user_password_confirmation"), with: "new_password") + |> fill_in(Wallaby.Query.text_field("current_password_for_password"), with: password) + |> click(Wallaby.Query.button("Change password")) + end +end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 7ccf592..2e4cb7c 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -45,4 +45,30 @@ defmodule ElixirSearchExtractorWeb.ConnCase do {:ok, conn: Phoenix.ConnTest.build_conn()} end + + @doc """ + Setup helper that registers and logs in users. + + setup :register_and_log_in_user + + It stores an updated connection and a registered user in the + test context. + """ + def register_and_log_in_user(%{conn: conn}) do + user = ElixirSearchExtractor.AccountsFixtures.user_fixture() + %{conn: log_in_user(conn, user), user: user} + end + + @doc """ + Logs the given `user` into the `conn`. + + It returns an updated `conn`. + """ + def log_in_user(conn, user) do + token = ElixirSearchExtractor.Accounts.generate_user_session_token(user) + + conn + |> Phoenix.ConnTest.init_test_session(%{}) + |> Plug.Conn.put_session(:user_token, token) + end end diff --git a/test/support/feature_case.ex b/test/support/feature_case.ex index 5f1d438..1bb1143 100644 --- a/test/support/feature_case.ex +++ b/test/support/feature_case.ex @@ -5,9 +5,32 @@ defmodule ElixirSearchExtractorWeb.FeatureCase do quote do use Wallaby.Feature + import ElixirSearchExtractor.AccountsFixtures import ElixirSearchExtractor.Factory alias ElixirSearchExtractorWeb.Router.Helpers, as: Routes + + def register_and_login(session) do + user_attributes = valid_user_attributes() + user = user_fixture(user_attributes) + + login(session, user_attributes.email, user_attributes.password) + end + + def register_and_login(session, password) do + user_attributes = valid_user_attributes(password: password, password_confirmation: password) + user = user_fixture(user_attributes) + + login(session, user_attributes.email, user_attributes.password) + end + + defp login(session, email, password) do + session + |> visit(Routes.user_session_path(ElixirSearchExtractorWeb.Endpoint, :new)) + |> fill_in(Wallaby.Query.text_field("user_email"), with: email) + |> fill_in(Wallaby.Query.text_field("user_password"), with: password) + |> click(Wallaby.Query.button("Log in")) + end end end end diff --git a/test/support/fixtures/accounts_fixtures.ex b/test/support/fixtures/accounts_fixtures.ex new file mode 100644 index 0000000..e1eb2a6 --- /dev/null +++ b/test/support/fixtures/accounts_fixtures.ex @@ -0,0 +1,34 @@ +defmodule ElixirSearchExtractor.AccountsFixtures do + @moduledoc """ + This module defines test helpers for creating + entities via the `ElixirSearchExtractor.Accounts` context. + """ + + def valid_user_name, do: "Test User" + def unique_user_email, do: "user#{System.unique_integer()}@example.com" + def valid_user_password, do: "hello world!" + + def valid_user_attributes(attrs \\ %{}) do + Enum.into(attrs, %{ + email: unique_user_email(), + name: valid_user_name(), + password: valid_user_password(), + password_confirmation: valid_user_password() + }) + end + + def user_fixture(attrs \\ %{}) do + {:ok, user} = + attrs + |> valid_user_attributes() + |> ElixirSearchExtractor.Accounts.register_user() + + user + end + + def extract_user_token(fun) do + {:ok, captured} = fun.(&"[TOKEN]#{&1}[TOKEN]") + [_, token, _] = String.split(captured.body, "[TOKEN]") + token + end +end