{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/crud-endpoints-for-organization-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\": \"CRUD Endpoints for Organization: Part 2\",\n  \"order\": 44,\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, \"CRUD Endpoints for Organization: Part 2\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Additional validation for organization creation\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Return organization data on authorization\")), mdx(\"h2\", null, \"Additional validations\"), mdx(\"p\", null, \"Since we currently only want each user to be associated with one organization (either as an admin or an owner), we need to add a validation to make sure that a user cannot create or be associated with more than one account. It's easy to disable this endpoint on the frontend, but we also want to make sure that a feisty customer can't break his own account by using a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"curl\"), \" command.\"), mdx(\"p\", null, \"We're going to create another validation just like we did with our website validation above, using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_change/3\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Changeset.html#validate_change/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". In this case, we're creating a function called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_new_owner_admin/2\"), \" to make sure the user trying to create an organization is not already associated with an existing account. Just like we did in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth/me\"), \" route, we're finding a user, preloading the associations, then checking to see if we get an organization. If we do, we return an error.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  def changeset(struct, params \\\\\\\\ %{}, association \\\\\\\\ false) do\\n    required_fields = if association, do: [:website], else: [:website, :owner_id]\\n\\n    struct\\n    |> cast(params, [:website, :owner_id])\\n    |> validate_required(required_fields)\\n    |> validate_change(:owner_id, &validate_new_owner_admin/2)\\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  ...\\n\\n  defp validate_new_owner_admin(:owner_id, owner_id) do\\n    user = Repo.get! User, owner_id\\n    org = Repo.preload(user, :organization).organization || Repo.preload(user, :owned_organization).owned_organization\\n\\n    if org do\\n      [owner_id: \\\"user is owner or admin of existing organiation\\\"]\\n    else\\n      []\\n    end\\n  end\\n  ...\\n\")), mdx(\"h2\", null, \"Update auth/me\"), mdx(\"p\", null, \"Now that we can create an organization, we need to be able to return the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" to the user in a consistent manner. Currently, when a user creates an organization we return the key in the HTTP response, but after that response the user has no way to access her key again. To solve this, we're going to update the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth/me\"), \" route to return the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" of the organization (if there is one) that the user owns or is an admin.\"), mdx(\"p\", null, \"Although we currently only have \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owners\"), \" and no \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admins\"), \", we want to check if the current user is either an owner or an admin of an existing organization. We check this by using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.preload/3\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Repo.html#c:preload/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" to load the associations of both \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":organization\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \". We then check to see if there is a match in either one. If there is no match, it returns \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \" so we want to render just the user data without the organization data.\"), 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    org = Repo.preload(user, :organization).organization || Repo.preload(user, :owned_organization).owned_organization\\n    case org do\\n      nil -> render(conn, UserView, \\\"show.json\\\", user: user)\\n      org -> render(conn, UserView, \\\"show.json\\\", user: user, org: org)\\n    end\\n  end\\n...\\n\")), mdx(\"p\", null, \"Then we need to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserView\"), \" to handle this new data.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\ndef render(\\\"show.json\\\", %{user: user, org: org}) do\\n  %{data: render_one(user, UserView, \\\"user_organization.json\\\", org: org)}\\nend\\n\\ndef render(\\\"show.json\\\", %{user: user}) do\\n  %{data: render_one(user, UserView, \\\"user.json\\\")}\\nend\\n\\n...\\n\\ndef render(\\\"user_organization.json\\\", %{user: user, org: org}) do\\n  %{email: user.email,\\n  id: user.id,\\n  username: user.username,\\n  website: org.website,\\n  public_key: org.public_key}\\nend\\n\\n\")), mdx(\"p\", null, \"And now when we authorize a user, we check to see if that user is associated with an organization and return the organization's data along with the authorization request. The next step is to connect our frontend and allow our existing user to create an organization.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"CRUD Endpoints for Organization: Part 2 Additional validation for organization creation Return organization data on authorization Additional…","frontmatter":{"title":"CRUD Endpoints for Organization: Part 2","order":44,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"crud-endpoints-for-organization-part-2","prevNode":{"frontmatter":{"title":"Controlling and Validating Forms","active":true,"free":false,"order":44,"tech":["react"]},"fields":{"slug":"controlling-and-validating-forms"}},"nextNode":{"frontmatter":{"title":"Create and Join an Organization on Signup","active":true,"free":false,"order":45,"tech":["react","redux"]},"fields":{"slug":"create-and-join-an-organization-on-signup"}}}},"staticQueryHashes":["1723017916"]}