{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/user-accounts-and-signup-part-1","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 1\",\n  \"order\": 12,\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 1\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Account creation\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"JSON web token (JWT)\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Migrations\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"CORS\")), mdx(\"p\", null, \"This is the first lesson in which we will make significant changes to our Phoenix backend. Just about every app has user accounts, often with varying degrees of complexity. For our app, we will use a standard email-password combination.\"), mdx(\"p\", null, \"In this lesson, we create the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model and add API endpoints so our frontend can create and update an account. We're also going to create and run a migration to update our database.\"), mdx(\"h2\", null, \"Creating our user\"), mdx(\"p\", null, \"The first thing we need to do is create a user model and controller, which we cover in more detail shortly. Creating these components is a standard part of most Phoenix applications so there are helpers available to generate the boilerplate.\"), mdx(\"p\", null, \"To view a list of the generators, and other \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix\"), \" tasks available to us, run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix -h\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix -h\\n\\nmix                     # Runs the default task (current: \\\"mix run\\\")\\n...\\nmix new                 # Creates a new Elixir project\\nmix phoenix.digest      # Digests and compress static files\\nmix phoenix.gen.channel # Generates a Phoenix channel\\nmix phoenix.gen.html    # Generates controller, model and views for an HTML based resource\\nmix phoenix.gen.json    # Generates a controller and model for a JSON based resource\\nmix phoenix.gen.model   # Generates an Ecto model\\nmix phoenix.gen.secret  # Generates a secret\\nmix phoenix.new         # Create a new Phoenix v1.1.3 application\\nmix phoenix.routes      # Prints all routes\\nmix phoenix.server      # Starts applications and their servers\\n...\\n\")), mdx(\"p\", null, \"There are many tasks but for now we'll focus only on the Phoenix ones. Since we're building a JSON API, let's try the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix.gen.json\"), \" generator. This will cause an error but the errors in Phoenix are quite helpful and will tell you what you're missing.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.json\\n\\n** (Mix) mix phoenix.gen.json expects both singular and plural names\\nof the generated resource followed by any number of attributes:\\n\\n    mix phoenix.gen.json User users name:string\\n\")), mdx(\"p\", null, \"Let's try it again but this time for a user with an email, encrypted password, and a username:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.json User users email:string encrypted_password:string \\\\\\n  username:string\\n\")), mdx(\"p\", null, \"You will get output similar to the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"* creating web/controllers/user_controller.ex\\n* creating web/views/user_view.ex\\n* creating test/controllers/user_controller_test.exs\\n* creating web/views/changeset_view.ex\\n* creating priv/repo/migrations/20160406190555_create_user.exs\\n* creating web/models/user.ex\\n* creating test/models/user_test.exs\\n\\nAdd the resource to your api scope in web/router.ex:\\n\\n    resources \\\"/users\\\", UserController, except: [:new, :edit]\\n\\nRemember to update your repository by running migrations:\\n\\n    $ mix ecto.migrate\\n\")), mdx(\"p\", null, \"This generates a number of different files and instructions for setting up our user. We'll take this opportunity to discuss some of the files and their purpose within our project.\"), mdx(\"h2\", null, \"The Controller\"), mdx(\"p\", null, \"In the output from our generator the very first file is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/controllers/user_controller.ex\"), \".\"), mdx(\"p\", null, \"Controllers are responsible for doing most of the work for a given request. When our application receives a request it will use the router to direct the request to a controller and a specific function. For example, when someone arrives at your website, you need to determine whether or not that person is a logged-in user. The controller is where your app will check with the database to determine how to handle the current connection.\"), mdx(\"p\", null, \"If you come from a Rails background, the concept of a controller should be familiar.\"), mdx(\"p\", null, \"Controllers are a big topic and will be used frequently so if you do not understand them now, you will after we use them a little more.\"), mdx(\"h2\", null, \"The View\"), mdx(\"p\", null, \"The second file created is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/views/user_view.ex\"), \", our view. If you're familiar with other frameworks, you might be expecting the view to be HTML files but that's not necessarily the case. In Phoenix, our view is a module containing functions for rendering data into a consumable format which can be either JSON or HTML. Since we're building a JSON API, it will respond with JSON.\"), mdx(\"p\", null, \"Our layout and other HTML assets are referred to as \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"templates\"), \" in Phoenix. These templates can be used by our views to generate the final HTML or JSON.\"), mdx(\"p\", null, \"By default our generated boilerplate includes our password in the JSON response. Open the user view and update the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"render/3\"), \" function by removing the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"encrypted_password\"), \" reference:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  def render(\\\"user.json\\\", %{user: user}) do\\n    %{id: user.id,\\n      email: user.email,\\n      username: user.username}\\n  end\\n\")), mdx(\"h2\", null, \"The Migration\"), mdx(\"p\", null, \"A migration is a set of changes we want applied to our database schema, such as adding new tables and columns or updating existing ones. When we look at the generated migration we'll see it is creates a new database table for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"users\\\"\"), \" and add a number of column for each of the three fields we supplied the generator. The migration that was generated for us can be found at \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"priv/repo/migrations/20160406190555_create_user.exs\"), \"; it's important to note that your file will almost certainly be different since migrations rely on timestamps at the beginning of the file for uniqueness.\"), mdx(\"p\", null, \"Let's open our migration make a few changes. For starters we want to make sure that users enter a valid username and email for an account to be created. We also want to make sure that email addresses are unique.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Repo.Migrations.CreateUser do\\n  use Ecto.Migration\\n\\n  def change do\\n    create table(:users) do\\n      add :username, :string, null: false\\n      add :email, :string, null: false\\n      add :encrypted_password, :string\\n\\n      timestamps\\n    end\\n\\n    create unique_index(:users, [:email])\\n    create unique_index(:users, [:username])\\n  end\\nend\\n\")), mdx(\"p\", null, \"The first change we made was to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"null: false\"), \" to both \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":username\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":email\"), \", this tells the database that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"null\"), \" values are not to be accepted. In other words, a value is required. The second change we made was to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create unique_index/2\"), \". A unique index is to make sure a username and email is only used once.\"), mdx(\"h2\", null, \"The Model\"), mdx(\"p\", null, \"Next up is our model, found in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/models/user.ex\"), \". In Phoenix, models are modules containing functions for working with our data's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"schema\"), \" and the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"struct\"), \" that contains its values. We're already familiar with structs and if you've worked in another framework, you're probably already familiar with a schema, but in case you aren't, a schema is describes the different fields of our table and it is defined within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"schema\"), \" block. You can think of it as a way to enforce a particular structure.\"), mdx(\"p\", null, \"Let's open our model and add support for the unique index we added into our migration.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.User do\\n  use PhoenixChat.Web, :model\\n\\n  schema \\\"users\\\" do\\n    field :email, :string\\n    field :encrypted_password, :string\\n    field :username, :string\\n\\n    timestamps\\n  end\\n\\n  @required_fields ~w(email encrypted_password username)\\n  @optional_fields ~w()\\n\\n  def changeset(model, params \\\\\\\\ :empty) do\\n    model\\n    |> cast(params, @required_fields, @optional_fields)\\n    |> validate_format(:email, ~r/@/)\\n    |> validate_length(:username, min: 1, max: 20)\\n    |> update_change(:email, &String.downcase/1)\\n    |> unique_constraint(:email)\\n    |> update_change(:username, &String.downcase/1)\\n    |> unique_constraint(:username)\\n  end\\nend\\n\")), mdx(\"p\", null, \"We've made some changes to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \" function. A \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" is a function that validates and transforms data into a format the database is expecting. For now we'll focus on a single changeset function but it's possible, and common, to use different functions for different situations. You will see some of these later on.\"), mdx(\"p\", null, \"Let's look at the individual changeset changes we made. With \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_format(:email, ~r/@/)\"), \" we check the email field using a regular expression to ensure it contains an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@\"), \". The second change we introduced is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_length(:username, min: 1, max: 20)\"), \" to ensure a username is at least one character and at most 20.\"), mdx(\"p\", null, \"Finally, the last change ties in with the index we added to our migration: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"unique_constraint(:email)\"), \". With the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"unique_constraint/3\"), \" function we can ensure the email is not already in use, thanks to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"unique_index\"), \". We also do the same for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":username\"), \".\"), mdx(\"h2\", null, \"The Router\"), mdx(\"p\", null, \"The last piece to our puzzle is the router, found in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/router.ex\"), \". The output from our generator directed us to make a change, open the router and update it accordingly.\"), mdx(\"p\", null, \"When our frontend makes a request to our API, the first place it hits is the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"router\"), \". This router sends that request to the right place so the request can be handled properly.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Router do\\n  use PhoenixChat.Web, :router\\n\\n  pipeline :browser do\\n    plug :accepts, [\\\"html\\\"]\\n    plug :fetch_session\\n    plug :fetch_flash\\n    plug :protect_from_forgery\\n    plug :put_secure_browser_headers\\n  end\\n\\n  pipeline :api do\\n    plug :accepts, [\\\"json\\\"]\\n  end\\n\\n  scope \\\"/\\\", PhoenixChat do\\n    pipe_through :browser # Use the default browser stack\\n\\n    get \\\"/\\\", PageController, :index\\n  end\\n\\n  scope \\\"/api\\\", PhoenixChat do\\n    pipe_through :api\\n\\n    resources \\\"/users\\\", UserController, except: [:show, :index, :new, :edit]\\n  end\\nend\\n\")), mdx(\"p\", null, \"With this change we are telling Phoenix that any requests to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/users\"), \", except \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":new\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":edit\"), \" should be sent to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserController\"), \". We're also removing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":index\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":show\"), \" since we don't want random users to be able to see our list of users, but for some apps, you'd want this behavior.\"), mdx(\"p\", null, \"There are a few things to notice in this file. There are two \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"pipeline\"), \" functions and two \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"scope\"), \" functions. Since we are creating an API we won't be using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":browser\"), \" pipeline, but you can see that it accepts HTML and has a series of plugs that apply useful transformations to your connection. For our application we'll focus on the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":api\"), \" pipeline.\"), mdx(\"p\", null, \"Within the code we just wrote, you see that any connection that hits the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/users\"), \" route is \\\"piped through\\\" the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":api\"), \" pipeline. Be wary of adding plugs to the API pipeline, because if you do, that transformation will be applied to every incoming connection. This is a very powerful tool and should be used with discretion.\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"scope\"), \" allow us group different routes together under a common base path. In our case, we want to direct anyone hitting the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/api/users\"), \" route to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserController\"), \".\"), mdx(\"p\", null, \"Finally, we see the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"resources/4\"), \" function which takes our path, controller, and options. Within the Phoenix router, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"resources/4\"), \", is a handy function that takes care of generating all of the standard routes for us. We can see a list of the routes \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"resources/4\"), \" has created by running \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix phoenix.routes\"), \" in our command line:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.routes\\n\")), mdx(\"p\", null, \"If you run the above command you should see something like this (if you do not see these, make sure your app has been compiled):\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"page_path  GET     /               PhoenixChat.PageController :index\\nuser_path  POST    /api/users      PhoenixChat.UserController :create\\nuser_path  PATCH   /api/users/:id  PhoenixChat.UserController :update\\n           PUT     /api/users/:id  PhoenixChat.UserController :update\\nuser_path  DELETE  /api/users/:id  PhoenixChat.UserController :delete\\n\")), mdx(\"p\", null, \"In later sections we'll explore creating individual routes without the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"resources/4\"), \" helper.\"), mdx(\"p\", null, \"Once we've updated our migration we should create the database and run the migration. Running our migration will apply the changes to our database:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.create\\n$ mix ecto.migrate\\n\")), mdx(\"p\", null, \"If this isn't your first time through the tutorial, you might need to run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix ecto.drop\"), \" first to drop the old database.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"User Accounts and Signup: Part 1 Account creation JSON web token (JWT) Migrations CORS This is the first lesson in which we will make…","frontmatter":{"title":"User Accounts and Signup: Part 1","order":12,"active":true,"free":true,"tech":["phoenix"]}}},"pageContext":{"slug":"user-accounts-and-signup-part-1","prevNode":{"frontmatter":{"title":"More Basics of Elixir and Phoenix","active":true,"free":true,"order":11,"tech":["phoenix","elixir"]},"fields":{"slug":"more-basics-of-elixir-and-phoenix"}},"nextNode":{"frontmatter":{"title":"User Accounts and Signup: Part 2","active":true,"free":true,"order":13,"tech":["phoenix"]},"fields":{"slug":"user-accounts-and-signup-part-2"}}}},"staticQueryHashes":["1723017916"]}