defmodule FrenzyWeb.GroupController do use FrenzyWeb, :controller alias Frenzy.{Repo, Group, Feed} alias FrenzyWeb.Router.Helpers, as: Routes alias FrenzyWeb.Endpoint plug :user_owns_group defp user_owns_group(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do user = conn.assigns[:user] group = Repo.get(Group, id) if Enum.any?(user.groups, fn g -> g.id == group.id end) do conn |> assign(:group, group) else conn |> put_flash(:error, "You do not have permission to acess that resource.") |> redirect(to: Routes.group_path(Endpoint, :index)) |> halt() end end defp user_owns_group(conn, _opts), do: conn def index(conn, _params) do groups = conn.assigns[:user].groups render(conn, "index.html", groups: groups) end def show(conn, _params) do group = conn.assigns[:group] |> Repo.preload(:feeds) create_feed_changeset = Feed.changeset( %Feed{ group_id: group.id }, %{} ) render(conn, "show.html", %{ group: group, create_feed_changeset: create_feed_changeset }) end def new(conn, _params) do changeset = Group.changeset(%Group{}, %{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"group" => %{"title" => title}}) do user = conn.assigns[:user] title = title |> String.trim() if String.length(title) > 0 do changeset = Ecto.build_assoc(user, :groups, %{ title: title }) {:ok, group} = Repo.insert(changeset) redirect(conn, to: Routes.group_path(Endpoint, :show, group.id)) else conn |> put_flash(:error, "Group title must not be empty") |> redirect(to: Routes.group_path(Endpoint, :new)) end end def delete(conn, _params) do group = conn.assigns[:group] {:ok, _} = Repo.delete(group) redirect(conn, to: Routes.group_path(Endpoint, :index)) end end