{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/login-and-authentication-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\": \"Login and Authentication: Part 2\",\n  \"order\": 20,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"elixir\", \"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, \"Login and Authentication: Part 2\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Authentication\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Automatic login on signup\")), mdx(\"p\", null, \"Now that we have the concept, it's time to implement this for our user login. In this section, we add an authentication pipeline for routes that need authentication and we add an endpoint that allows our frontend to login.\"), mdx(\"h2\", null, \"Adding authentication\"), mdx(\"p\", null, \"Let's make our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \" a bit more useful and finish setting up Ueberauth and Guardian. Following along with their documentation, let's update our router:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Router do\\n  use PhoenixChat.Web, :router\\n\\n  ...\\n\\n  pipeline :api do\\n    plug :accepts, [\\\"json\\\"]\\n  end\\n\\n  pipeline :api_auth do\\n    plug Guardian.Plug.VerifyHeader, realm: \\\"Bearer\\\"\\n    plug Guardian.Plug.LoadResource\\n  end\\n\\n ...\\n\\n  scope \\\"/api\\\", PhoenixChat do\\n    pipe_through :api\\n\\n    resources \\\"/users\\\", UserController, except: [:show, :index, :new, :edit]\\n  end\\n\\n  scope \\\"/auth\\\", PhoenixChat do\\n    pipe_through [:api, :api_auth]\\n\\n    post \\\"/:identity/callback\\\", AuthController, :callback\\n  end\\nend\\n\")), mdx(\"p\", null, \"In addition to creating an \\\"/auth\\\" scope, we created a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"pipeline\"), \". Our new pipeline takes care to verify our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Authorization\"), \" header and load the resource using our serializer. We learned about the serializer when we configured Guardian, so let's discuss the authorization header.\"), mdx(\"p\", null, \"Under-the-hood Guardian relies on an HTTP header, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Authorization\"), \", to pass the JSON web token between the frontend and the backend. If you don't know what an authorization header is, it will become abundantly clear later on when we head back over to the frontend to make a call with an authorization header.\"), mdx(\"p\", null, \"Now we need to implement the callback function we specified. Open up our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \" and change it to include our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"callback/2\"), \" function. We can also get rid of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test\"), \" function.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AuthController do\\n  use PhoenixChat.Web, :controller\\n\\n  alias PhoenixChat.{ErrorView, UserView, User, AuthController}\\n\\n  plug Ueberauth\\n\\n  def callback(%{assigns: %{ueberauth_auth: auth}} = conn, _params) do\\n    result = with {:ok, user} <- user_from_auth(auth),\\n                  :ok <- validate_pass(user.encrypted_password, auth.credentials.other.password),\\n                  do: signin_user(conn, user)\\n\\n    case result do\\n      {:ok, user, token} ->\\n        conn\\n        |> put_status(:created)\\n        |> render(UserView, \\\"show.json\\\", user: user, token: token)\\n      {:error, reason} ->\\n        conn\\n        |> put_status(:bad_request)\\n        |> render(ErrorView, \\\"error.json\\\", error: reason)\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"If we read down the function, what we're doing is: get the user from Ueberauth, validate the password, and sign in the user. If it's successful we'll render the user view along with our JSON web token. In the event of an error, we'll show the error view instead.\"), mdx(\"p\", null, \"Let's implement the individual functions that make up our callback, we'll start with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_from_auth/1\"), \". For this function we need to lookup a user by the email address provided by Ueberauth. Add the following function to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/controller/auth_controller.ex\"), \", below the callback.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  defp user_from_auth(auth) do\\n    result = Repo.get_by(User, email: auth.info.email)\\n    case result do\\n      nil -> {:error, %{\\\"email\\\" => [\\\"invalid email\\\"]}}\\n      user -> {:ok, user}\\n    end\\n  end\\n\")), mdx(\"p\", null, \"The next step in our authentication process is validating the password. We'll use pattern matching in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_pass/2\"), \" function to handle missing or blank passwords and Comeonin to compare the clear text password and the one stored in the database. To handle the comparison we'll rely on Comeonin and the Bcrypt module.\"), mdx(\"p\", null, \"Bcrypt is the hashing algorithm we used in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" to compute our hashed password. The code below is what we should end up with.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  defp validate_pass(_encrypted, password) when password in [nil, \\\"\\\"] do\\n    {:error, \\\"password required\\\"}\\n  end\\n\\n  defp validate_pass(encrypted, password) do\\n    if Comeonin.Bcrypt.checkpw(password, encrypted) do\\n      :ok\\n    else\\n      {:error, \\\"invalid password\\\"}\\n    end\\n  end\\n\\n\")), mdx(\"p\", null, \"Lastly, we need to sign in so we can retrieve the user and JSON web token:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  defp signin_user(conn, user) do\\n    token = conn\\n            |> Guardian.Plug.api_sign_in(user)\\n            |> Guardian.Plug.current_token\\n    {:ok, user, token}\\n  end\\n\")), mdx(\"p\", null, \"That's it for the controller but there's still one step left: updating our user view to support the JSON web token. We can start by creating a new function similar to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"user.json\\\"\"), \" but including our token. Then we can use pattern matching in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"show.json\\\"\"), \" to render the JSON with or without the JWT token.\"), mdx(\"p\", null, \"With all the pieces together, this is how our view should appear:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserView do\\n  use PhoenixChat.Web, :view\\n\\n  alias PhoenixChat.{UserView}\\n\\n  def render(\\\"index.json\\\", %{users: users}) do\\n    %{data: render_many(users, UserView, \\\"user.json\\\")}\\n  end\\n\\n  def render(\\\"show.json\\\", %{user: user, token: token}) do\\n    %{data: render_one(user, UserView, \\\"user_token.json\\\", token: token)}\\n  end\\n\\n  def render(\\\"show.json\\\", %{user: user}) do\\n    %{data: render_one(user, UserView, \\\"user.json\\\")}\\n  end\\n\\n  def render(\\\"user.json\\\", %{user: user}) do\\n    %{email: user.email,\\n      id: user.id,\\n      username: user.username}\\n  end\\n\\n  def render(\\\"user_token.json\\\", %{user: user, token: token}) do\\n    %{email: user.email,\\n      id: user.id,\\n      token: token,\\n      username: user.username}\\n  end\\nend\\n\")), mdx(\"p\", null, \"One thing our frontend application will need to know, is who current user is. To facilate this, let's build an endpoint to return the user given a JSON web token. This will be our \\\"/me\\\" endpoint, let's go ahead and add the endpoint to the router:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\n  scope \\\"/auth\\\", PhoenixChat do\\n    pipe_through [:api, :api_auth]\\n\\n    get \\\"/me\\\", AuthController, :me\\n    post \\\"/:identity/callback\\\", AuthController, :callback\\n    delete \\\"/signout\\\", AuthController, :delete\\n  end\\n\\n...\\n\")), mdx(\"p\", null, \"Now we can go back to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \" and implement our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"me\"), \" function. For now all we want our endpoint to do is retrieve the currently logged in user and return their info to us. If they're not logged in, an HTTP error code will do. To do this, we're going to introduce a new Guardian plug: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsureAuthenicated\"), \".\"), mdx(\"p\", null, \"With \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsureAuthenticated\"), \", Guardian will check to see whether our incoming HTTP request contains our Authentication header. In the event that it does not, Guardian will take care of returning the appropriate error code and won't run any other functions in the module. The first step is to add the plug to the top of our controller:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AuthController do\\n  use PhoenixChat.Web, :controller\\n\\n  alias PhoenixChat.{ErrorView, UserView, User, AuthController}\\n\\n  plug Ueberauth\\n  plug Guardian.Plug.EnsureAuthenticated, [handler: AuthController] when action in [:delete, :me]\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"By now we should be somewhat familiar with what this does but just in case, let's go over it. Here we are adding a new plug to our request pipeline, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsureAuthentication\"), \", passing a set of options (namely the error handler), and lastly we use a guard to apply the plug only for requests to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/me\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/signout\"), \" routes. This is because (obviously) we don't want to ensure a user is authenticated before that user can login.\"), mdx(\"p\", null, \"To get everything working we only need to implement our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"me\"), \" function now. Since we know \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsureAuthenticated\"), \" will take care of logged out users, our method is pretty simple. We need to retrieve the current user and return them using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserView\"), \". Add the following to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth_controller\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n\\n  def me(conn, _params) do\\n    user = Guardian.Plug.current_resource(conn)\\n    render(conn, UserView, \\\"show.json\\\", user: user)\\n  end\\n\\n  ...\\n\")), mdx(\"p\", null, \"We're not quite done. According to the \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/guardian#guardianplugensureauthenticated\",\n    \"parentName\": \"p\"\n  }, \"Guardian docs\"), \" for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsureAuthenticated\"), \", we will need to add another function in the event a user is not authenticated. From the docs:\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"Looks for a previously verified token. If one is found, continues, otherwise it will call the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":unauthenticated\"), \" function of your handler.\")), mdx(\"p\", null, \"While we're at it, let's also add an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":unauthorized\"), \" function in case we want to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"EnsurePermissions\"), \" plug in the future.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  def unauthenticated(conn, _params) do\\n    conn\\n    |> put_status(:unauthorized)\\n    |> render(ErrorView, \\\"error.json\\\", errors: %{\\\"account\\\" => [\\\"insufficient privilege\\\"]})\\n  end\\n\\n  def unauthorized(conn, _params) do\\n    conn\\n    |> put_status(:forbidden)\\n    |> render(ErrorView, \\\"error.json\\\", error: %{\\\"account\\\" => [\\\"unauthorized\\\"]})\\n  end\\n\")), mdx(\"p\", null, \"It's probably worthwhile to at least skim the rest of the \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/guardian\",\n    \"parentName\": \"p\"\n  }, \"Guardian docs\"), \" so you know about some of the functionality. Knowing what is available and what is required will help a lot when debugging.\"), mdx(\"h2\", null, \"Automatic login on signup\"), mdx(\"p\", null, \"Now that we can sign a user up and login independently, let's automatically log a user in upon signup. This is actually really simple. Since \\\"login\\\" really just means returning a valid token to a user, we can generate a token after an account has successfully been created and pass that along to the user. We only have to change two lines of code.\"), 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      {:ok, token, _claims} = Guardian.encode_and_sign(user, :token)\\n\\n      conn\\n      |> put_status(:created)\\n      |> render(\\\"show.json\\\", user: user, token: token)\\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, \"Now we have everything we need to register for an account and sign-in. Let's head back to the frontend to connect it.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Login and Authentication: Part 2 Authentication Automatic login on signup Now that we have the concept, it's time to implement this for our…","frontmatter":{"title":"Login and Authentication: Part 2","order":20,"active":true,"free":false,"tech":["phoenix","elixir","ueberauth"]}}},"pageContext":{"slug":"login-and-authentication-part-2","prevNode":{"frontmatter":{"title":"Login and Authentication: Part 1","active":true,"free":false,"order":19,"tech":["phoenix","elixir","ueberauth"]},"fields":{"slug":"login-and-authentication-part-1"}},"nextNode":{"frontmatter":{"title":"Move Logic to Redux","active":true,"free":false,"order":21,"tech":["react","redux"]},"fields":{"slug":"move-logic-to-redux"}}}},"staticQueryHashes":["1723017916"]}