{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/creating-an-organization-model","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\": \"Creating an Organization Model\",\n  \"order\": 41,\n  \"free\": false,\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, \"Creating an Organization Model\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Creating the model\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Writing tests\")), mdx(\"p\", null, \"At this point in our app, all users who sign up will have access to the same chatroom. This is fine if you're self-hosting, but we want to build this to handle multiple accounts, which we will call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organizations\"), \". Then at some point, we will add the ability to include multiple administrators within each organization.\"), mdx(\"p\", null, \"For example, if you have two websites, say \", mdx(\"a\", {\n    \"href\": \"http://sightlinemaps.com\",\n    \"parentName\": \"p\"\n  }, \"sightlinemaps.com\"), \" and \", mdx(\"a\", {\n    \"href\": \"http://learnphoenix.io\",\n    \"parentName\": \"p\"\n  }, \"learnphoenix.io\"), \", each website would represent an organization. We want to send chat messages from visitors to \", mdx(\"a\", {\n    \"href\": \"http://sightlinemaps.com\",\n    \"parentName\": \"p\"\n  }, \"sightlinemaps.com\"), \" only to the admins of the Sightline Maps organization, and not to LearnPhoenix.\"), mdx(\"p\", null, \"The structure of our organizations will look like the image below, with the following characteristics: 1) Every user (admin/owner) may only be associated with one organization, 2) Each organization may only have one owner, 3) Every organization may have multiple administrators who can see and respond to messages.\"), mdx(\"p\", null, mdx(\"img\", {\n    \"src\": \"/learnphoenix-static-assets/images/organization_chart.jpg\",\n    \"alt\": \"organization chart\",\n    \"parentName\": \"p\"\n  })), mdx(\"h2\", null, \"Creating an Organization model\"), mdx(\"p\", null, \"We're going to start by adding an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model with only three fields:\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public key\"), \" - randomly generated unique key that will be used for routing messages from users to admins.\\n\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"website\"), \" - a unique website.\\n\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner\"), \" - an association with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \". This is the creator/owner of the organization.\"), mdx(\"p\", null, \"The public key will be automatically generated when an organization is created. This public key will be used for routing messages from users to admins. All users of website A will use the same public key as all admins of website A. Every\\nuser and admin socket connection will store the public key of the relevant organization.\"), mdx(\"p\", null, \"We also take steps to ensure our data is valid since we want \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"website\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" to be unique. Also, we want the website to have a valid URL format. So to validate the URL format, we use Regular Expressions, which we will cover only briefly. If you are not familiar with Regular Expressions, there are ample resources online to learn how they work and what they are used for. One of them is \", mdx(\"a\", {\n    \"href\": \"https://regexone.com/\",\n    \"parentName\": \"p\"\n  }, \"regexone.com\"), \".\"), mdx(\"p\", null, \"So now let's create an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"website\"), \", a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \", and an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner_id\"), \". We're also going to generate the controller and a lot of other boilerplate that comes with it by using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix phoenix.gen.json\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.json Organization organizations \\\\\\n  public_key website owner_id:references:users\\n\")), mdx(\"p\", null, \"Then we need to change a few things. The first notable change is that we're adding a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":nilify_all\"), \" option to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":on_delete\"), \" for our user \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Migration.html#references/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". The reason we're doing this is because every organization must have an owner, and if a user is deleted, we have to decide what to do with the organization. For now, we're just going to set the value of the owner to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \" and we can later decide what we want to do with un-owned organizations. If we didn't do this, we would only know if an organization is un-owned by filtering out all organization that do not have a user that is currently registered.\"), mdx(\"p\", null, \"Then we change around our index since we want our organizations to be unique based on their \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" and their \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"website\"), \". We're also adding an index on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner_id\"), \" because we might have to search based on that parameter at some point.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Repo.Migrations.CreateOrganization do\\n  use Ecto.Migration\\n\\n  def change do\\n    create table(:organizations) do\\n      add :public_key, :string, null: false\\n      add :website, :string, null: false\\n      add :owner_id, references(:users, on_delete: :nilify_all)\\n\\n      timestamps()\\n    end\\n\\n    create index(:organizations, [:owner_id])\\n    create unique_index(:organizations, [:public_key])\\n    create unique_index(:organizations, [:website])\\n  end\\nend\\n\")), mdx(\"p\", null, \"And now we have to build out our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model. For the sake of clarity, we're going to go through each function individually. The first is our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \", in which we define what is a valid \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model with a variety of constraints. These constraints and functions are defined below the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" and are explained in greater detail below. The format of the changeset should look familiar.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  use PhoenixChat.Web, :model\\n\\n  schema \\\"organizations\\\" do\\n    field :public_key, :string\\n    field :website, :string\\n    belongs_to :owner, PhoenixChat.Owner\\n\\n    timestamps()\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  Builds a changeset based on the `struct` and `params`.\\n  \\\"\\\"\\\"\\n  def changeset(struct, params \\\\\\\\ %{}) do\\n    struct\\n    |> cast(params, [:website])\\n    |> validate_required([:website])\\n    |> update_change(:website, &set_uri_scheme/1)\\n    |> validate_change(:website, &validate_website/2)\\n    |> unique_constraint(:website)\\n    |> put_public_key()\\n    |> unique_constraint(:public_key)\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" pipeline, we have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_public_key/1\"), \" function. This is the function that generates the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":public_key\"), \" for the organization. We're going to allow for the future possibility that someone might need to change their information without changing the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \", so we're going to use this function only if the organization is new, which we determine based on whether the incoming data has an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" field (if it's been added to the database already, it will have an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \", otherwise it won't).\"), mdx(\"p\", null, \"Assuming the organization is new and the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" is valid, we pass it along to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_change/3\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Changeset.html#put_change/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which changes a key (in this case \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":public_key\"), \") with a value. On our case, that value is the output of another function we need to create called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"random_key/0\"), \". If the organization already exists, then we pass it along to the rest of the changeset without changing the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" field.\"), mdx(\"p\", null, \"Within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"random_key\"), \" function, we're generating a random key using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"crypto\"), \" module in Erlang, which gives us random bytes which encode to Base64 text, then we trim that to a certain number of characters. We're setting a default length of 10 characters. If you're interested in learning more about has collision probabilities to determine how long you should make your API key, check our \", mdx(\"a\", {\n    \"href\": \"https://blog.learnphoenix.io/how-long-should-i-make-my-api-key-833ebf2dc26f#.a4s7j1s67\",\n    \"parentName\": \"p\"\n  }, \"blog post\"), \" on the subject.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  use PhoenixChat.Web, :model\\n\\n  ...\\n\\n  defp put_public_key(%{data: data} = changeset) do\\n    if changeset.valid? && !data.id do\\n      changeset\\n      |> put_change(:public_key, random_key())\\n    else\\n      changeset\\n    end\\n  end\\n\\n  defp random_key(length \\\\\\\\ 10) do\\n    :crypto.strong_rand_bytes(length) |> Base.encode64 |> binary_part(0, length)\\n  end\\n\\n  ...\\n\\nend\\n\")), mdx(\"p\", null, \"The next couple functions deal with the website input. If the user provides an input for a website without a \", mdx(\"a\", {\n    \"href\": \"https://en.wikipedia.org/wiki/Uniform_Resource_Identifier\",\n    \"parentName\": \"p\"\n  }, \"URI\"), \" prefix, such as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"http://\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https://\"), \", or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ftp://\"), \", we are going to prepend it with a default URI scheme of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https://\"), \", so that a website of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"foo.com\"), \" becomes \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https://foo.com\"), \".\"), mdx(\"p\", null, \"Within this function, we're using Elixir's \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/elixir/Regex.html\",\n    \"parentName\": \"p\"\n  }, \"Regex\"), \" module to match on any string that starts with (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"^\"), \") any set of numbers or letters (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"w+\"), \") followed by \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"://\"), \". If it matches, that means the website provided already has a URI scheme. If it doesn't match, then we're prepending \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https://\"), \" to it. And regardless of whether it matches or not, we're turning the whole string into lowercase before returning. If you want to test out if your particular regex is valid with Elixir, check out \", mdx(\"a\", {\n    \"href\": \"http://www.elixre.uk/\",\n    \"parentName\": \"p\"\n  }, \"Elixre\"), \" (you might even want to bookmark it).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  use PhoenixChat.Web, :model\\n\\n  ...\\n\\n  defp set_uri_scheme(nil), do: nil\\n  defp set_uri_scheme(website) do\\n    if Regex.match?(~r/^\\\\w+:\\\\/\\\\//, website) do\\n      website\\n    else\\n      \\\"https://\\\" <> website\\n    end |> String.downcase()\\n  end\\nend\\n\")), mdx(\"p\", null, \"In the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_website\"), \" function, we're validating that the website address we received is valid. This a complicated thing to match and we aren't going to even attempt to handle the edge cases, but this validation should handle the overwhelming majority of websites (if you want to get a sense of how many random things are actually valid URLs, check out \", mdx(\"a\", {\n    \"href\": \"http://formvalidation.io/validators/uri/\",\n    \"parentName\": \"p\"\n  }, \"formvalidation.io\"), \"). This function starts by using the Elixir \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/elixir/URI.html\",\n    \"parentName\": \"p\"\n  }, \"URI\"), \" module to split the website into \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"scheme\"), \" (e.g. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https://\"), \") and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"host\"), \" (e.g. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"learnphoenix.io\"), \").\"), mdx(\"p\", null, \"We want to return an error if the URI scheme is not \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"http\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"https\"), \", or if it does not pass our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"valid_host_format/1\"), \" function, which has its own regular expression. The first grouping of the regular expression looks for some series of numbers and letters that end in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".\"), \" (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"^([a-zA-z]+\\\\.)\"), \"). The asterisk (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"*\"), \") tells us that\"), mdx(\"p\", null, \"Within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"valid_host_format/1\"), \" function, we're running a new regular expression that checks to make sure that the url starts with some series of numbers and/or letters, followed by a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".\"), \", followed by anything (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"*\"), \"), and must end with a series of letters.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  use PhoenixChat.Web, :model\\n\\n  ...\\n\\n  defp validate_website(:website, website) do\\n    %URI{scheme: scheme, host: host} = URI.parse(website)\\n\\n    if is_nil(scheme) ||\\n       is_nil(host) ||\\n       not scheme in ~w(http https) ||\\n       !valid_host_format?(host) do\\n      [website: \\\"invalid url format\\\"]\\n    else\\n      []\\n    end\\n  end\\n\\n  defp valid_host_format?(host) do\\n    Regex.match? ~r/^([a-zA-z]+\\\\.)*[a-zA-Z]+$/, host\\n  end\\nend\\n\")), mdx(\"h2\", null, \"Organization model tests\"), mdx(\"p\", null, \"To ensure the stability of our app, we're going to write some tests for our Organization model. Much of the code below will have already been written by the generator and all of the content of these tests has already been covered in the previous chapters on testing. (If there is anything in this codeblock that you do not believe was covered previously, please email \", mdx(\"a\", {\n    \"href\": \"mailto:info@learnphoenix.io\",\n    \"parentName\": \"p\"\n  }, \"info@learnphoenix.io\"), \" and we will add clarification)\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.OrganizationTest do\\n  use PhoenixChat.ModelCase\\n\\n  alias PhoenixChat.Organization\\n\\n  @valid_attrs %{website: \\\"foo.com\\\"}\\n  @invalid_attrs %{}\\n\\n  test \\\"changeset with valid attributes\\\" do\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n\\n    assert changeset.valid?\\n  end\\n\\n  test \\\"changeset must have unique website\\\" do\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    Repo.insert! changeset\\n\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    {:error, changeset} = Repo.insert(changeset)\\n\\n    assert {:website, {\\\"has already been taken\\\", []}} in changeset.errors\\n  end\\n\\n  test \\\"changeset must have a unique public key generated on create\\\" do\\n    changeset = Organization.changeset(%Organization{}, %{website: \\\"http://foo.com\\\"})\\n    org1 = Repo.insert! changeset\\n\\n    changeset = Organization.changeset(%Organization{}, %{website: \\\"http://bar.com\\\"})\\n    org2 = Repo.insert! changeset\\n\\n    assert org1.public_key != org2.public_key\\n  end\\n\\n  test \\\"changeset's website must be a valid url\\\" do\\n    some_invalid_urls = [\\\"test this\\\", \\\"???\\\", \\\"...\\\", \\\".www.foo.bar.\\\", \\\"foo.\\\", \\\"ftp://foo.com\\\"]\\n\\n    for invalid_url <- some_invalid_urls do\\n      changeset = Organization.changeset(%Organization{}, %{website: invalid_url})\\n\\n      assert {:website, {\\\"invalid url format\\\", []}} in changeset.errors\\n    end\\n\\n    some_valid_urls = ~w(foo.com www.foo.com http://foo.com https://foo.com?test=foo foo.com?test=bar)\\n\\n    for valid_url <- some_valid_urls do\\n      changeset = Organization.changeset(%Organization{}, %{website: valid_url})\\n\\n      assert changeset.valid?\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"Also, just for the sake of making sure our app compiles at this point, let's add the endpoint that the generator suggested to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"router.ex\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  scope \\\"/api\\\", PhoenixChat do\\n    pipe_through :api\\n\\n    resources \\\"/users\\\", UserController, except: [:new, :edit]\\n    resources \\\"/organizations\\\", OrganizationController, except: [:new, :edit]\\n  end\\n...\\n\")), mdx(\"p\", null, \"Next we need to associate our users with an organization and set up endpoints to change our organizations.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Creating an Organization Model Creating the model Writing tests At this point in our app, all users who sign up will have access to the same…","frontmatter":{"title":"Creating an Organization Model","order":41,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"creating-an-organization-model","prevNode":{"frontmatter":{"title":"Associate Organizations and Users","active":true,"free":false,"order":41,"tech":["phoenix"]},"fields":{"slug":"associate-organizations-and-users"}},"nextNode":{"frontmatter":{"title":"CRUD Endpoints for Organization: Part 1","active":true,"free":false,"order":43,"tech":["phoenix"]},"fields":{"slug":"crud-endpoints-for-organization-part-1"}}}},"staticQueryHashes":["1723017916"]}