{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/password-reset-link-and-email","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Password Reset Link and Email\",\n  \"order\": 56,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"ueberauth\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Password Reset Link and Email\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Password reset flow\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Generate reset token\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Validate token and reset password\")), mdx(\"p\", null, \"In this lesson, we're going to cover how to send a password reset link via email. If you've skipped any lessons so far, you'll want to make sure that you've at least implemented transactional email.\"), mdx(\"h2\", null, \"Password reset flow\"), mdx(\"p\", null, \"Resetting a password is more complicated than you might expect. The way password reset works is\"), mdx(\"p\", null, \"First, create a link that allows a user to request a new password\"), mdx(\"p\", null, \"Second, create the view that for the user to submit the reset link\"), mdx(\"p\", null, \"Third, generate and send the password reset link via email\"), mdx(\"p\", null, \"Fourth, create another view that accepts a token as a query parameter and sends the new password along with the token\"), mdx(\"p\", null, \"Fifth, match the token with an existing user account\"), mdx(\"p\", null, \"Sixth, automatically log the user in if the token and new password is valid\"), mdx(\"h2\", null, \"Generate reset token\"), mdx(\"p\", null, \"The first thing we're going to do is change our backend to accept a password reset. We're going to need two additional endpoints to add this functionality.\"), mdx(\"p\", null, \"The first endpoint will be \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset-request\"), \" which will take the initial request from the frontend and will include the email address for which we want to reset the password. The second endpoint will be \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset\"), \" which will pass along the new password and a (presumably) valid token in order to reset the password of the account that made the request. Let's add those endpoints now.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nscope \\\"/api\\\", PhoenixChat do\\n  pipe_through [:api, :api_auth]\\n\\n  resources \\\"/users\\\", UserController, except: [:index, :show, :new, :edit]\\n  post \\\"/users/reset-request\\\", UserController, :reset_request, as: :reset\\n  post \\\"/users/reset\\\", UserController, :reset, as: :reset\\n\\n  ...\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"The next thing we should do is update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserController\"), \". You can see in the code above that we created two new functions, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":reset_request\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":reset\"), \", so we should define those now. We will start with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset_request\"), \", which is the function we'll call along with an email to send the reset link to the email address specified. We'll go over each line below the code block.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserController do\\n  ...\\n\\n  def reset_request(conn, %{\\\"email\\\" => email}) do\\n    user = Repo.get_by(User, email: String.downcase(email))\\n\\n    if user do\\n      user\\n      |> User.password_reset_changeset\\n      |> Repo.update!\\n      |> send_password_reset_email\\n\\n      send_resp(conn, :no_content, \\\"\\\")\\n    else\\n      send_resp(conn, :bad_request, \\\"user does not exist\\\")\\n    end\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"First, we check to see if the user exists by using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.get_by\"), \". If the user exists, we pass the user along to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"password_reset_changeset\"), \" (which we will create later) that will generate the token and store it along with our user so we can match against it later.\"), mdx(\"p\", null, \"Then we send it along to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"send_password_reset_email\"), \" function, which we will define later. If it does not exist, we send along an error.\"), mdx(\"p\", null, \"In order to store this token with our user, we need to create a new migration to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.gen.migration add_user_password_reset_fields\\n\")), mdx(\"p\", null, \"Within our new migration, we need to add two fields. One is the token that we will match against and the other is a timestamp for the last time a user changed her password.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Repo.Migrations.AddUserPasswordResetFields do\\n  use Ecto.Migration\\n\\n  def change do\\n    alter table(:users) do\\n      add :password_reset_token, :string, default: nil\\n      add :password_reset_timestamp, :datetime\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"Go ahead and run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix ecto.migrate\"), \". Now that we have our model updated, we need to create our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"password_reset_changeset\"), \". This looks similar to our other changesets except for the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_token\"), \" function, in which we will generate a token and add it to our user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndef password_reset_changeset(model, params \\\\\\\\ %{}) do\\n  model\\n  |> changeset(params)\\n  |> put_change(:password_reset_timestamp, Ecto.DateTime.utc)\\n  |> put_token(:password_reset_token)\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"Now we need to define \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_token\"), \". In the function below, we're checking to make sure the changeset is valid (recall that changesets have the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"valid?\"), \" parameter), and if it is, we call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"generate_token\"), \" (defined later) and use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_change\"), \" to add the token to our user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndef put_token(changeset, field) when field in ~w(password_reset_token)a do\\n  case changeset do\\n    %Ecto.Changeset{valid?: true} ->\\n      token = generate_token()\\n      put_change(changeset, field, token)\\n    _ ->\\n      changeset\\n  end\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"So now we need to define \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"generate_token\"), \". All we're doing is creating a 50-character random string.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndefp generate_token do\\n  50\\n  |> :crypto.strong_rand_bytes\\n  |> Base.url_encode64\\n  |> binary_part(0, 50)\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"This confuses a lot of people because it's so simple. Contrary to what you might think, there is no magic that comes with keys or tokens\\u2014they're just random numbers and letters that you match against another key or token.\"), mdx(\"p\", null, \"In our case, we are creating a token and saving it with our user. When that user requests a new password, we send along that token as a query parameter in a link via email. When that link is clicked, we search our database for matching tokens, and if we find a match, we allow the user to reset the password.\"), mdx(\"h2\", null, \"Send reset email\"), mdx(\"p\", null, \"Now that we have our token, we need to define the password reset email function, which we're calling in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset_request\"), \" function. This simply takes in the user and passes it along to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Email.password_reset_email\"), \" function, which we will also need to define.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserController do\\n  ...\\n\\n  defp send_password_reset_email(user) do\\n    user\\n    |> Email.password_reset_email\\n    |> Mailer.deliver_later\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Now we need to define the email that is sent to the user who forgot her password. Recall that we're taking in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \", which now has a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"password_reset_token\"), \" field. For now, we're going to hard-code the reset link, but eventually we would want to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email_reset_link\"), \" function to set the link based on the environment (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dev\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"prod\"), \", etc).\"), mdx(\"p\", null, \"The first thing we do is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"URI\"), \" encode the query so that it makes for a valid link, then we concatenate it with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email_reset_link\"), \". From there, we pass along the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset_link\"), \" to the email address associated with the current user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Email do\\n  ...\\n\\n  def password_reset_email(user) do\\n    query = URI.encode_query(token: user.password_reset_token)\\n    reset_link = \\\"#{email_reset_link}?#{query}\\\"\\n\\n    user\\n    |> base_email\\n    |> subject(\\\"Password Reset\\\")\\n    |> text_body(\\\"\\\"\\\"\\n      A password reset was requested, follow #{reset_link} to reset your password.\\n      If this was a mistake, please ignore this email.\\n      \\\"\\\"\\\")\\n  end\\n\\n  defp email_reset_link do\\n    # This will eventually handle for environment using\\n    # Application.get_env(PhoenixChat.Mailer)\\n    \\\"http://localhost:3000/#/reset-password\\\"\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Now, when a user clicks on the link, she will be directed a page that will allow her to set a new password.\"), mdx(\"p\", null, \"The last thing we need to do before moving to the frontend is to set up our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reset\"), \" endpoint that will actually allow our user to change her password.\"), mdx(\"p\", null, \"In this function, we're going to find the user that has the matching token (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_for_password_token\"), \"), ensure that the token is less than 48 hours old, update the password, send the user an email, and log the user in.\"), mdx(\"p\", null, \"Adding an expiration is a good idea from a security perspective because it limits the time that an account could be potentially vulnerable. That said, it's still next to impossible that someone can guess a 50-character token in their lifetime no matter how many guesses per second (see our \", mdx(\"a\", {\n    \"href\": \"https://blog.learnphoenix.io/how-long-should-i-make-my-api-key-833ebf2dc26f#.whgoujsrw\",\n    \"parentName\": \"p\"\n  }, \"blog post\"), \" for more information on collision probabilities), so leaving an account sort-of-vulnerable for 48 hours is not a big deal.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserController do\\n  ...\\n\\n  def reset(conn, %{\\\"token\\\" => token, \\\"password\\\" => password}) do\\n    case user_for_password_token(token) do\\n      user = %User{} ->\\n        user\\n        |> User.registration_changeset(%{password: password})\\n        |> Repo.update!\\n\\n        {:ok, jwt, _claims} = Guardian.encode_and_sign(user, :token)\\n\\n        send_password_change_email(user)\\n\\n        conn\\n        |> put_status(:ok)\\n        |> render(\\\"show.json\\\", user: user, web_token: jwt)\\n      nil ->\\n        conn\\n        |> put_status(:bad_request)\\n        |> render(ErrorView, \\\"error.json\\\", errors: [\\\"invalid or expired token\\\"])\\n    end\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"This should all look familiar. We are using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_for_password_token\"), \" (defined below) to match the token and sure validity, then using the existing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset\"), \" to update the password, then \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Guardian.encode_and_sign\"), \" to log the user in, just as we did before in our automatic login on signup, and finally sending the email.\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_for_password_token\"), \" function is a little bit tricky. We're creating a query that searches through our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" models and finds a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"password_reset_token\"), \" that matches the token that was passed into the function. Then, it checks to make sure that the timestamp is less than 48 hours old using \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Query.API.html#fragment/1\",\n    \"parentName\": \"p\"\n  }, \"fragment\"), \", which allows us to send database queries directly to Postgres.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\n  defp user_for_password_token(token) do\\n    query = from u in User,\\n            where: u.password_reset_token == ^token\\n              and u.password_reset_timestamp > fragment(\\\"now() - interval '48hours'\\\"),\\n            select: u\\n    Repo.one(query)\\n  end\\n\\n...\\n\")), mdx(\"p\", null, \"Now we need to define the function in which we send the confirmation email.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndefp send_password_change_email(user) do\\n  user\\n  |> Email.password_change_email\\n  |> Mailer.deliver_later\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"And finally, define the email.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndef password_change_email(user) do\\n  user\\n  |> base_email\\n  |> subject(\\\"Password Change\\\")\\n  |> text_body(\\\"Your password on Learn Phoenix has been updated recently.\\\")\\nend\\n\\n...\\n\")), mdx(\"p\", null, \"And that's it for our backend. Now we need to create the forms on our frontend and connect it to our backend.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Password Reset Link and Email Password reset flow Generate reset token Validate token and reset password In this lesson, we're going to…","frontmatter":{"title":"Password Reset Link and Email","order":56,"active":true,"free":false,"tech":["phoenix","ueberauth"]}}},"pageContext":{"slug":"password-reset-link-and-email","prevNode":{"frontmatter":{"title":"Basics of Analytics","active":true,"free":false,"order":55,"tech":null},"fields":{"slug":"basics-of-analytics"}},"nextNode":null}},"staticQueryHashes":["1723017916"]}