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 Organizations. Then at some point, we will add the ability to include multiple administrators within each organization.
For example, if you have two websites, say sightlinemaps.com and learnphoenix.io, each website would represent an organization. We want to send chat messages from visitors to sightlinemaps.com only to the admins of the Sightline Maps organization, and not to LearnPhoenix.
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.

We're going to start by adding an Organization model with only three fields:
public key - randomly generated unique key that will be used for routing messages from users to admins.
website - a unique website.
owner - an association with a User. This is the creator/owner of the organization.
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 user and admin socket connection will store the public key of the relevant organization.
We also take steps to ensure our data is valid since we want website and 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 regexone.com.
So now let's create an Organization model with a website, a public_key, and an owner_id. We're also going to generate the controller and a lot of other boilerplate that comes with it by using mix phoenix.gen.json.
$ mix phoenix.gen.json Organization organizations \ public_key website owner_id:references:usersThen we need to change a few things. The first notable change is that we're adding a :nilify_all option to the :on_delete for our user (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 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.
Then we change around our index since we want our organizations to be unique based on their public_key and their website. We're also adding an index on owner_id because we might have to search based on that parameter at some point.
defmodule PhoenixChat.Repo.Migrations.CreateOrganization do use Ecto.Migration def change do create table(:organizations) do add :public_key, :string, null: false add :website, :string, null: false add :owner_id, references(:users, on_delete: :nilify_all) timestamps() end create index(:organizations, [:owner_id]) create unique_index(:organizations, [:public_key]) create unique_index(:organizations, [:website]) endendAnd now we have to build out our Organization model. For the sake of clarity, we're going to go through each function individually. The first is our changeset, in which we define what is a valid Organization model with a variety of constraints. These constraints and functions are defined below the changeset and are explained in greater detail below. The format of the changeset should look familiar.
defmodule PhoenixChat.Organization do use PhoenixChat.Web, :model schema "organizations" do field :public_key, :string field :website, :string belongs_to :owner, PhoenixChat.Owner timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:website]) |> validate_required([:website]) |> update_change(:website, &set_uri_scheme/1) |> validate_change(:website, &validate_website/2) |> unique_constraint(:website) |> put_public_key() |> unique_constraint(:public_key) end ...endWithin our changeset pipeline, we have a put_public_key/1 function. This is the function that generates the :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 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 id field (if it's been added to the database already, it will have an id, otherwise it won't).
Assuming the organization is new and the changeset is valid, we pass it along to put_change/3 (docs), which changes a key (in this case :public_key) with a value. On our case, that value is the output of another function we need to create called random_key/0. If the organization already exists, then we pass it along to the rest of the changeset without changing the public_key field.
Within the random_key function, we're generating a random key using the 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 blog post on the subject.
defmodule PhoenixChat.Organization do use PhoenixChat.Web, :model ... defp put_public_key(%{data: data} = changeset) do if changeset.valid? && !data.id do changeset |> put_change(:public_key, random_key()) else changeset end end defp random_key(length \\ 10) do :crypto.strong_rand_bytes(length) |> Base.encode64 |> binary_part(0, length) end ...endThe next couple functions deal with the website input. If the user provides an input for a website without a URI prefix, such as http://, https://, or ftp://, we are going to prepend it with a default URI scheme of https://, so that a website of foo.com becomes https://foo.com.
Within this function, we're using Elixir's Regex module to match on any string that starts with (^) any set of numbers or letters (w+) followed by ://. If it matches, that means the website provided already has a URI scheme. If it doesn't match, then we're prepending 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 Elixre (you might even want to bookmark it).
defmodule PhoenixChat.Organization do use PhoenixChat.Web, :model ... defp set_uri_scheme(nil), do: nil defp set_uri_scheme(website) do if Regex.match?(~r/^\w+:\/\//, website) do website else "https://" <> website end |> String.downcase() endendIn the 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 formvalidation.io). This function starts by using the Elixir URI module to split the website into scheme (e.g. https://) and host (e.g. learnphoenix.io).
We want to return an error if the URI scheme is not http or https, or if it does not pass our 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 . (^([a-zA-z]+\.)). The asterisk (*) tells us that
Within the 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 ., followed by anything (*), and must end with a series of letters.
defmodule PhoenixChat.Organization do use PhoenixChat.Web, :model ... defp validate_website(:website, website) do %URI{scheme: scheme, host: host} = URI.parse(website) if is_nil(scheme) || is_nil(host) || not scheme in ~w(http https) || !valid_host_format?(host) do [website: "invalid url format"] else [] end end defp valid_host_format?(host) do Regex.match? ~r/^([a-zA-z]+\.)*[a-zA-Z]+$/, host endendTo 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 info@learnphoenix.io and we will add clarification)
defmodule PhoenixChat.OrganizationTest do use PhoenixChat.ModelCase alias PhoenixChat.Organization @valid_attrs %{website: "foo.com"} @invalid_attrs %{} test "changeset with valid attributes" do changeset = Organization.changeset(%Organization{}, @valid_attrs) assert changeset.valid? end test "changeset must have unique website" do changeset = Organization.changeset(%Organization{}, @valid_attrs) Repo.insert! changeset changeset = Organization.changeset(%Organization{}, @valid_attrs) {:error, changeset} = Repo.insert(changeset) assert {:website, {"has already been taken", []}} in changeset.errors end test "changeset must have a unique public key generated on create" do changeset = Organization.changeset(%Organization{}, %{website: "http://foo.com"}) org1 = Repo.insert! changeset changeset = Organization.changeset(%Organization{}, %{website: "http://bar.com"}) org2 = Repo.insert! changeset assert org1.public_key != org2.public_key end test "changeset's website must be a valid url" do some_invalid_urls = ["test this", "???", "...", ".www.foo.bar.", "foo.", "ftp://foo.com"] for invalid_url <- some_invalid_urls do changeset = Organization.changeset(%Organization{}, %{website: invalid_url}) assert {:website, {"invalid url format", []}} in changeset.errors end some_valid_urls = ~w(foo.com www.foo.com http://foo.com https://foo.com?test=foo foo.com?test=bar) for valid_url <- some_valid_urls do changeset = Organization.changeset(%Organization{}, %{website: valid_url}) assert changeset.valid? end endendAlso, just for the sake of making sure our app compiles at this point, let's add the endpoint that the generator suggested to router.ex.
... scope "/api", PhoenixChat do pipe_through :api resources "/users", UserController, except: [:new, :edit] resources "/organizations", OrganizationController, except: [:new, :edit] end...Next we need to associate our users with an organization and set up endpoints to change our organizations.
Previous: Associate Organizations and UsersNext: CRUD Endpoints for Organization: Part 1