defmodule WikiWeb.PageController do use WikiWeb, :controller alias Wiki.Content alias Wiki.Content.Page plug :get_page when action in [:show, :edit, :update, :delete] defp get_page(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do case Content.get_page(id) do nil -> conn |> send_resp(404, "Not found") |> halt() page -> key = get_session(conn, :content_encryption_key) page = %Page{page | content_encryption_key: key} page = if action_name(conn) in [:show, :edit] do Page.decrypt_content(page) else page end assign(conn, :page, page) end end def index(conn, _params) do pages = Content.list_pages() render(conn, "index.html", pages: pages) end def new(conn, _params) do changeset = Content.change_page(%Page{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"page" => page_params}) do key = get_session(conn, :content_encryption_key) page_params = page_params |> Map.put("user_id", conn.assigns.current_user.id) |> Map.put("content_encryption_key", key) case Content.create_page(page_params) do {:ok, page} -> conn |> put_flash(:info, "Page created successfully.") |> redirect(to: Routes.page_path(conn, :show, page)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, _params) do render(conn, "show.html", page: conn.assigns.page) end def edit(conn, _params) do page = conn.assigns.page changeset = Content.change_page(page) render(conn, "edit.html", page: page, changeset: changeset) end def update(conn, %{"page" => page_params}) do page = conn.assigns.page case Content.update_page(page, page_params) do {:ok, page} -> conn |> put_flash(:info, "Page updated successfully.") |> redirect(to: Routes.page_path(conn, :show, page)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", page: page, changeset: changeset) end end def delete(conn, _params) do page = conn.assigns.page {:ok, _page} = Content.delete_page(page) conn |> put_flash(:info, "Page deleted successfully.") |> redirect(to: Routes.page_path(conn, :index)) end end