philomena/lib/philomena_web/plugs/load_comment_plug.ex

36 lines
1.1 KiB
Elixir
Raw Permalink Normal View History

2019-12-14 20:46:50 +01:00
defmodule PhilomenaWeb.LoadCommentPlug do
alias Philomena.Comments.Comment
alias Philomena.Repo
import Plug.Conn, only: [assign: 3]
import Canada.Can, only: [can?: 3]
import Ecto.Query
def init(opts),
do: opts
def call(%{assigns: %{image: image}} = conn, opts) do
param = Keyword.get(opts, :param, "comment_id")
show_hidden = Keyword.get(opts, :show_hidden, false)
Comment
|> where(image_id: ^image.id, id: ^to_string(conn.params[param]))
2019-12-18 16:06:43 +01:00
|> preload([:image, :deleted_by, user: [awards: :badge]])
2019-12-14 20:46:50 +01:00
|> Repo.one()
|> maybe_hide_comment(conn, show_hidden)
end
defp maybe_hide_comment(nil, conn, _show_hidden),
do: PhilomenaWeb.NotFoundPlug.call(conn)
defp maybe_hide_comment(%{hidden_from_users: false} = comment, conn, _show_hidden),
do: assign(conn, :comment, comment)
defp maybe_hide_comment(comment, %{assigns: %{current_user: user}} = conn, show_hidden) do
case show_hidden or can?(user, :show, comment) do
2020-01-11 05:20:19 +01:00
true -> assign(conn, :comment, comment)
2019-12-14 20:46:50 +01:00
false -> PhilomenaWeb.NotAuthorizedPlug.call(conn)
end
end
end