{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/user-accounts-and-signup-part-2","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\": \"User Accounts and Signup: Part 2\",\n  \"order\": 13,\n  \"free\": true,\n  \"active\": true,\n  \"tech\": [\"phoenix\"]\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, \"User Accounts and Signup: Part 2\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Signup\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"CORS\")), mdx(\"p\", null, \"In this lesson, we add the ability to create a new user with a secure, hashed password. Then we set up our endpoint to handle incoming messages from our frontend so we can connect and create new users.\"), mdx(\"h2\", null, \"Sign-up\"), mdx(\"p\", null, \"Before we can sign-in, we need to sign-up. We have our user boilerplate done so now we can look at how to register new accounts.\"), mdx(\"p\", null, \"In a important part of registering a new account is picking a strong password. An even \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"more\"), \" important part of the process is securely storing that password. For this, we're going to rely on the library \", \"[Comeonin][comeonin]\", \". Before we can use it, we need to include it as a dependency in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix.exs\"), \" file; \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix.exs\"), \" is much like to NPM's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"package.json\"), \" and Bunder's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Gemfile\"), \".\"), mdx(\"p\", null, mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"Make sure your version of \", mdx(\"inlineCode\", {\n    \"parentName\": \"em\"\n  }, \"phoenix\"), \" is at least 1.2 and that your version of \", mdx(\"inlineCode\", {\n    \"parentName\": \"em\"\n  }, \"phoenix_ecto\"), \" is at least 3.0.\"), \" Several features of this app will not work if you are not on the current version.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  defp deps do\\n    [\\n      {:comeonin, \\\"~> 2.3\\\"},\\n      {:cowboy, \\\"~> 1.0\\\"},\\n      {:gettext, \\\"~> 0.11\\\"},\\n      {:phoenix, \\\"~> 1.2.0\\\"},\\n      {:phoenix_pubsub, \\\"~> 1.0\\\"},\\n      {:phoenix_ecto, \\\"~> 3.0\\\"},\\n      {:phoenix_html, \\\"~> 2.6\\\"},\\n      {:phoenix_live_reload, \\\"~> 1.0\\\", only: :dev},\\n      {:postgrex, \\\">= 0.0.0\\\"}\\n    ]\\n  end\\n\")), mdx(\"p\", null, \"In addition to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"deps/0\"), \" we need to update \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"applications/0\"), \". This is a little bit different than you might be used to, but it's still intuitive. In Phoenix/Elixir, some modules can be managed independently and need to be started along with your app. Many dependencies you add will need to be added here.\"), mdx(\"p\", null, \"The primary exceptions are libraries that rely on an existing application that you've already started. For example, some modules will use \", \"[HTTPoison][httpoison]\", \" and don't need to be started independently. We will cover that in more detail when it becomes relevant.\\nWe will cover these applications in a later lesson but for now we only need to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":comeonin\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"def application do\\n  [mod: {PhoenixChat, []},\\n    applications: [\\n      :comeonin,\\n      :cowboy,\\n      :gettext,\\n      :logger,\\n      :phoenix,\\n      :phoenix_ecto,\\n      :phoenix_html,\\n      :phoenix_pubsub,\\n      :postgrex\\n    ]]\\nend\\n\")), mdx(\"p\", null, \"Now you should run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix deps.get\"), \" to get install our dependencies:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix deps.get\\n\")), mdx(\"p\", null, \"Next, we'll revisit our model and changesets.\"), mdx(\"h2\", null, \"Registration changeset\"), mdx(\"p\", null, \"During the registration process there are some things we need to do then and only then, like validating password length and hashing our password with \", \"[Comeonin][comeonin]\", \". For these reasons we'll create a new changeset just for registrations. The first challenge we have to over come is where to store the unhashed password, thankfully we can use a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"virtual\"), \" field in our schema.\"), mdx(\"p\", null, \"Virtual fields are part of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"schema\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"struct\"), \" but their values are not persisted (saved) to our database. Using a virtual field allows us to store both the hashed and unhashed versions of the password in the same struct, making our work with changesets easier.\"), mdx(\"p\", null, \"Let's begin by updating our model in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/models/user.ex\"), \". We will start by including the virtual password field:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  schema \\\"users\\\" do\\n    field :email, :string\\n    field :encrypted_password, :string\\n    field :username, :string\\n    field :password, :string, virtual: true\\n\\n    timestamps\\n  end\\n\")), mdx(\"p\", null, \"Let's update our original \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \" function to ignore the password:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  @required_fields ~w(email username)\\n  @optional_fields ~w()\\n  ...\\n\")), mdx(\"p\", null, \"Now we can create our new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" function. For this changeset we want to require our virtual password field, validate the password length, and finally hash it using \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/comeonin/api-reference.html\",\n    \"parentName\": \"p\"\n  }, \"Comeonin\"), \". If you're not familiar with hashing, you can think of it as turning a plain-text string into a (pseudo) random string that can only be decoded if you have the right key. Let's make those changes now:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  def registration_changeset(model, params) do\\n    model\\n    |> changeset(params)\\n    |> cast(params, ~w(password), [])\\n    |> validate_length(:password, min: 6, max: 100)\\n    |> put_encrypted_pw\\n  end\\n\\n  defp put_encrypted_pw(changeset) do\\n    case changeset do\\n      %Ecto.Changeset{valid?: true, changes: %{password: pass}} ->\\n        put_change(changeset, :encrypted_password, Comeonin.Bcrypt.hashpwsalt(pass))\\n      _ ->\\n        changeset\\n    end\\n  end\\n\")), mdx(\"p\", null, \"In addition to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" function we've also created \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_encrypted_pw/1\"), \", this private function will hash our password when a changeset is valid.\"), mdx(\"p\", null, \"Before we go too much further, let's look at why we need a separate changeset for registration. The primary reason for separate changeset is so we can validate and hash passwords \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"only\"), \" when necessary. Password hashing is an expensive operation in which a complex algorithm is used to convert our password into a non-reversible random string of characters and numbers. When we hash passwords we are able to safely store them in our database.\"), mdx(\"p\", null, \"Storing passwords unhashed is a \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"major\"), \" no-no. Without hashing, our passwords would be available in clear text to anyone with access to the database, like employees or a malicious attacker. Hashing passwords ensures your user's data is just that much safer.\"), mdx(\"h2\", null, \"Controller updates\"), mdx(\"p\", null, \"With our registration changeset complete, we can update our user controller in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"controllers/user_controller.ex\"), \" to use it. Updating our controller is easy thanks to changesets. All we need to do is update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create/2\"), \" function to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" in place of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"def create(conn, %{\\\"user\\\" => user_params}) do\\n  changeset = User.registration_changeset(%User{}, user_params)\\n\\n  case Repo.insert(changeset) do\\n    {:ok, user} ->\\n      conn\\n      |> put_status(:created)\\n      |> render(\\\"show.json\\\", user: user)\\n    {:error, changeset} ->\\n      conn\\n      |> put_status(:unprocessable_entity)\\n      |> render(PhoenixChat.ChangesetView, \\\"error.json\\\", changeset: changeset)\\n  end\\nend\\n\")), mdx(\"p\", null, \"We can also delete the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"show/2\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"index/2\"), \" functions since we aren't going to call them from our frontend.\"), mdx(\"p\", null, \"Our registration API is now ready for use. With a valid email, password, and username our controller will create a new record in the database and return the user as JSON.\"), mdx(\"h2\", null, \"Cross-Origin Resource Sharing (CORS)\"), mdx(\"p\", null, \"If you've heard of CORS before then reading this section title may have cause you to wince; don't worry we'll only be covering CORS at a high level.\"), mdx(\"p\", null, \"Cross-origin resource sharing, or CORS, is a mechanism for limiting which domains and applications can access our API. CORS isn't usually an issue, since we often times serve the front-end application on the same host as the backend (as in, both the backend and the frontend are run from the same server, like with Rails, Meteor, etc).\"), mdx(\"p\", null, \"In our application however, we've separated the front-end from the back-end and hosting them in two totally separate places. While running locally, our API is on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000\"), \", while our frontend is running on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:3000\"), \". Because of this, we need to add support for CORS to our project, otherwise, our API would only accept requests originating from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000\"), \" and would ignore any requests that originate from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:3000\"), \".\"), mdx(\"p\", null, \"You can think of CORS as a doorman that checks to make sure that the person requesting entrance is on the list. If your API is only supposed to be used by your frontend, then you can limit the incoming requests to that domain. You can also set CORS to accept all incoming traffic from any domain.\"), mdx(\"img\", {\n    src: \"https://raw.githubusercontent.com/LearnPhoenix/graphics/master/cors.png\",\n    style: {\n      \"border\": \"none\",\n      \"borderRadius\": \"0\"\n    }\n  }), mdx(\"p\", null, \"To faciliate supporting CORS, we're going to include the \", mdx(\"a\", {\n    \"href\": \"https://github.com/whatyouhide/corsica\",\n    \"parentName\": \"p\"\n  }, \"Corsica\"), \" library. We need to start by updating our dependencies in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix.exs\"), \", we won't need to add Corsica as an application though. When we're done, don't forget to run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix deps.get\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defp deps do\\n  [\\n    {:comeonin, \\\"~> 2.3\\\"},\\n    {:corsica, \\\"~> 0.4\\\"},\\n    ...\\n  ]\\nend\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix deps.get\\n\")), mdx(\"p\", null, \"Now that we have Corsica in our project we need to configure it. Lucky for us there is only one file we need to change: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lib/phoenix_chat/endpoint.ex\"), \". Open the endpoint file and add this changes at the bottom:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Endpoint do\\n  ...\\n  plug Corsica, allow_headers: ~w(Accept Content-Type Authorization)\\n  plug PhoenixChat.Router\\nend\\n\")), mdx(\"p\", null, \"Don't worry if you don't understand all of this yet, we'll discuss Plugs more shortly. Just know that any request we receive will pass through \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Corsica\"), \" before it hits our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Router\"), \".\"), mdx(\"p\", null, \"We are instructing Corsica to allow data with headers \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Accept\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Content-Type\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Authorization\"), \". This will make more sense when we implement an API call from the frontend.\"), mdx(\"p\", null, \"The last thing to do is to start your Phoenix server so we can start making requests. You do this by running \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix phoenix.server\"), \", which will default to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.server\\n\")), mdx(\"p\", null, \"You will want to keep this open and running so we can make requests to our backend from our React frontend.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"User Accounts and Signup: Part 2 Signup CORS In this lesson, we add the ability to create a new user with a secure, hashed password. Then we…","frontmatter":{"title":"User Accounts and Signup: Part 2","order":13,"active":true,"free":true,"tech":["phoenix"]}}},"pageContext":{"slug":"user-accounts-and-signup-part-2","prevNode":{"frontmatter":{"title":"User Accounts and Signup: Part 1","active":true,"free":true,"order":12,"tech":["phoenix"]},"fields":{"slug":"user-accounts-and-signup-part-1"}},"nextNode":{"frontmatter":{"title":"Create a Reusable Button Component","active":true,"free":false,"order":14,"tech":["react"]},"fields":{"slug":"create-a-reusable-button-component"}}}},"staticQueryHashes":["1723017916"]}