63 lines
1.5 KiB
Elixir
63 lines
1.5 KiB
Elixir
defmodule FrenzyWeb.ItemController do
|
|
use FrenzyWeb, :controller
|
|
alias Frenzy.{Repo, Item}
|
|
alias FrenzyWeb.Endpoint
|
|
|
|
plug :user_owns_item
|
|
|
|
defp user_owns_item(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do
|
|
user = conn.assigns[:user]
|
|
|
|
item = Repo.get(Item, id)
|
|
|
|
if Enum.any?(user.feeds, fn f -> f.id == item.feed_id end) do
|
|
conn
|
|
|> assign(:item, item)
|
|
else
|
|
conn
|
|
|> put_flash(:error, "You do not have permission to access that resource.")
|
|
|> redirect(to: Routes.group_path(Endpoint, :index))
|
|
|> halt()
|
|
end
|
|
end
|
|
|
|
defp user_owns_item(conn, _opts), do: conn
|
|
|
|
def show(conn, _params) do
|
|
item = conn.assigns[:item] |> Repo.preload(:feed)
|
|
|
|
render(conn, "show.html", %{
|
|
item: item,
|
|
feed: item.feed
|
|
})
|
|
end
|
|
|
|
def read(conn, params) do
|
|
item = conn.assigns[:item] |> Repo.preload(:feed)
|
|
|
|
changeset =
|
|
Item.changeset(item, %{
|
|
read: true,
|
|
read_date: Timex.now()
|
|
})
|
|
|
|
{:ok, item} = Repo.update(changeset)
|
|
path = Map.get(params, "redirect") || Routes.item_path(Endpoint, :show, item.id)
|
|
redirect(conn, to: path)
|
|
end
|
|
|
|
def unread(conn, params) do
|
|
item = conn.assigns[:item] |> Repo.preload(:feed)
|
|
|
|
changeset =
|
|
Item.changeset(item, %{
|
|
read: false,
|
|
read_date: nil
|
|
})
|
|
|
|
{:ok, item} = Repo.update(changeset)
|
|
path = Map.get(params, "redirect") || Routes.item_path(Endpoint, :show, item.id)
|
|
redirect(conn, to: path)
|
|
end
|
|
end
|