frenzy/lib/frenzy_web/controllers/group_controller.ex

75 lines
1.7 KiB
Elixir
Raw Normal View History

2019-03-21 23:21:56 +00:00
defmodule FrenzyWeb.GroupController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, Group, Feed}
alias FrenzyWeb.Router.Helpers, as: Routes
alias FrenzyWeb.Endpoint
2019-03-23 23:42:38 +00:00
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
2019-03-21 23:21:56 +00:00
def index(conn, _params) do
2019-03-23 23:42:38 +00:00
groups = conn.assigns[:user].groups
2019-03-21 23:21:56 +00:00
render(conn, "index.html", groups: groups)
end
2019-03-23 23:42:38 +00:00
def show(conn, _params) do
group = conn.assigns[:group] |> Repo.preload(:feeds)
2019-03-21 23:21:56 +00:00
create_feed_changeset =
Feed.changeset(
%Feed{
2019-03-23 23:42:38 +00:00
group_id: group.id
2019-03-21 23:21:56 +00:00
},
%{}
)
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
2019-03-23 23:42:38 +00:00
user = conn.assigns[:user]
changeset =
Ecto.build_assoc(user, :groups, %{
title: title
})
2019-03-21 23:21:56 +00:00
{:ok, group} = Repo.insert(changeset)
2019-03-23 23:42:38 +00:00
redirect(conn, to: Routes.group_path(Endpoint, :show, group.id))
2019-03-21 23:21:56 +00:00
end
2019-03-23 23:42:38 +00:00
def delete(conn, _params) do
group = conn.assigns[:group]
2019-03-21 23:21:56 +00:00
{:ok, _} = Repo.delete(group)
redirect(conn, to: Routes.group_path(Endpoint, :index))
end
end