philomena/lib/philomena_web/controllers/admin/advert_controller.ex

70 lines
2 KiB
Elixir
Raw Normal View History

2019-12-15 03:54:16 +01:00
defmodule PhilomenaWeb.Admin.AdvertController do
use PhilomenaWeb, :controller
alias Philomena.Adverts.Advert
alias Philomena.Adverts
alias Philomena.Repo
import Ecto.Query
plug :verify_authorized
plug :load_and_authorize_resource, model: Advert, only: [:edit, :update, :delete]
def index(conn, _params) do
adverts =
Advert
|> order_by(desc: :finish_date)
|> Repo.paginate(conn.assigns.scrivener)
2019-12-16 20:24:38 +01:00
render(conn, "index.html", title: "Admin - Adverts", layout_class: "layout--wide", adverts: adverts)
2019-12-15 03:54:16 +01:00
end
def new(conn, _params) do
changeset = Adverts.change_advert(%Advert{})
2019-12-16 20:24:38 +01:00
render(conn, "new.html", title: "New Advert", changeset: changeset)
2019-12-15 03:54:16 +01:00
end
def create(conn, %{"advert" => advert_params}) do
case Adverts.create_advert(advert_params) do
{:ok, _advert} ->
conn
|> put_flash(:info, "Advert was successfully created.")
|> redirect(to: Routes.admin_advert_path(conn, :index))
{:error, :advert, changeset, _changes} ->
render(conn, "new.html", changeset: changeset)
end
end
def edit(conn, _params) do
changeset = Adverts.change_advert(conn.assigns.advert)
2019-12-16 20:24:38 +01:00
render(conn, "edit.html", title: "Editing Advert", changeset: changeset)
2019-12-15 03:54:16 +01:00
end
def update(conn, %{"advert" => advert_params}) do
case Adverts.update_advert(conn.assigns.advert, advert_params) do
{:ok, _advert} ->
conn
|> put_flash(:info, "Advert was successfully updated.")
|> redirect(to: Routes.admin_advert_path(conn, :index))
{:error, changeset} ->
render(conn, "edit.html", changeset: changeset)
end
end
def delete(conn, _params) do
{:ok, _advert} = Adverts.delete_advert(conn.assigns.advert)
conn
|> put_flash(:info, "Advert was successfully deleted.")
|> redirect(to: Routes.admin_advert_path(conn, :index))
end
defp verify_authorized(conn, _opts) do
case Canada.Can.can?(conn.assigns.current_user, :index, Advert) do
true -> conn
false -> PhilomenaWeb.NotAuthorizedPlug.call(conn)
end
end
end