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

74 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)
2020-01-11 05:20:19 +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: ~p"/admin/adverts")
2019-12-15 03:54:16 +01:00
2024-08-16 05:01:34 +02:00
{:error, changeset} ->
2019-12-15 03:54:16 +01:00
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: ~p"/admin/adverts")
2019-12-15 03:54:16 +01:00
{: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: ~p"/admin/adverts")
2019-12-15 03:54:16 +01:00
end
defp verify_authorized(conn, _opts) do
case Canada.Can.can?(conn.assigns.current_user, :index, Advert) do
2020-01-11 05:20:19 +01:00
true -> conn
2019-12-15 03:54:16 +01:00
false -> PhilomenaWeb.NotAuthorizedPlug.call(conn)
end
end
end