1.6 KiB · text History 3208487
defmodule VigilWeb.OrgAuth do
  @moduledoc """
  `on_mount` for everything under `/orgs/:org`: puts the organization and the
  caller's membership into `current_scope` (`Vigil.Accounts.Scope`), or
  sends a non-member back to their organizations. Runs after
  `UserAuth`'s `:require_authenticated`.

  With `:project` as well, the `:project` path param must name a project
  the caller may see (`Vigil.Projects.get_visible/2`); it is assigned as
  `@project`.
  """
  use VigilWeb, :verified_routes

  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [put_flash: 3, push_navigate: 2]

  alias Vigil.Accounts.Scope
  alias Vigil.{Organizations, Projects}

  def on_mount(:organization, %{"org" => slug}, _session, socket) do
    scope = socket.assigns.current_scope

    case Organizations.get_membership(scope.user, slug) do
      {org, member} ->
        {:cont, assign(socket, :current_scope, Scope.put_organization(scope, org, member))}

      nil ->
        {:halt,
         socket
         |> put_flash(:error, "That organization doesn't exist, or you're not in it.")
         |> push_navigate(to: ~p"/orgs")}
    end
  end

  def on_mount(:project, %{"project" => slug}, _session, socket) do
    scope = socket.assigns.current_scope

    case Projects.get_visible(scope, slug) do
      nil ->
        {:halt,
         socket
         |> put_flash(:error, "That project doesn't exist, or you can't see it.")
         |> push_navigate(to: ~p"/orgs/#{scope.organization.slug}")}

      project ->
        {:cont, assign(socket, :project, project)}
    end
  end
end