philomena/lib/philomena_web/controllers/topic/lock_controller.ex

54 lines
1.6 KiB
Elixir
Raw Normal View History

2019-12-14 00:31:42 +01:00
defmodule PhilomenaWeb.Topic.LockController do
import Plug.Conn
use PhilomenaWeb, :controller
alias Philomena.Topics.Topic
alias Philomena.Topics
alias Philomena.Repo
import Ecto.Query
plug :load_topic
plug PhilomenaWeb.CanaryMapPlug, create: :lock, delete: :unlock
plug :authorize_resource, model: Topic, id_name: "topic_id", persisted: true
def create(conn, %{"topic" => topic_params}) do
topic = conn.assigns.topic
user = conn.assigns.current_user
case Topics.lock_topic(topic, topic_params, user) do
{:ok, topic} ->
conn
|> put_flash(:info, "Topic successfully locked!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 00:31:42 +01:00
{:error, _changeset} ->
conn
|> put_flash(:error, "Unable to lock the topic!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 00:31:42 +01:00
end
end
def delete(conn, _opts) do
topic = conn.assigns.topic
case Topics.unlock_topic(topic) do
{:ok, topic} ->
conn
|> put_flash(:info, "Topic successfully unlocked!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 00:31:42 +01:00
{:error, _changeset} ->
conn
|> put_flash(:error, "Unable to unlock the topic!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 00:31:42 +01:00
end
end
defp load_topic(conn, _opts) do
topic = Topic
|> where(forum_id: ^conn.params["forum_id"], slug: ^conn.params["topic_id"])
2019-12-14 17:43:26 +01:00
|> preload([:forum])
2019-12-14 00:31:42 +01:00
|> Repo.one()
Plug.Conn.assign(conn, :topic, topic)
end
end