From a00cdab7391dcd50a213f8e658e6daac074f06a6 Mon Sep 17 00:00:00 2001 From: "byte[]" Date: Sun, 27 Sep 2020 23:53:14 -0400 Subject: [PATCH] improve ajax error messages --- assets/js/utils/requests.js | 6 ++++-- lib/philomena_web/plugs/not_authorized_plug.ex | 18 +++++++++++++----- lib/philomena_web/plugs/not_found_plug.ex | 18 +++++++++++++----- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/assets/js/utils/requests.js b/assets/js/utils/requests.js index d7c597a9..da0a1524 100644 --- a/assets/js/utils/requests.js +++ b/assets/js/utils/requests.js @@ -8,7 +8,8 @@ function fetchJson(verb, endpoint, body) { credentials: 'same-origin', headers: { 'Content-Type': 'application/json', - 'x-csrf-token': window.booru.csrfToken + 'x-csrf-token': window.booru.csrfToken, + 'x-requested-with': 'xmlhttprequest' }, }; @@ -24,7 +25,8 @@ function fetchHtml(endpoint) { return fetch(endpoint, { credentials: 'same-origin', headers: { - 'x-csrf-token': window.booru.csrfToken + 'x-csrf-token': window.booru.csrfToken, + 'x-requested-with': 'xmlhttprequest' }, }); } diff --git a/lib/philomena_web/plugs/not_authorized_plug.ex b/lib/philomena_web/plugs/not_authorized_plug.ex index 220edd7c..530587ea 100644 --- a/lib/philomena_web/plugs/not_authorized_plug.ex +++ b/lib/philomena_web/plugs/not_authorized_plug.ex @@ -7,10 +7,18 @@ defmodule PhilomenaWeb.NotAuthorizedPlug do def call(conn), do: call(conn, nil) def call(conn, _opts) do - conn - |> Controller.fetch_flash() - |> Controller.put_flash(:error, "You can't access that page.") - |> Controller.redirect(to: "/") - |> Conn.halt() + case conn.assigns.ajax? do + true -> + conn + |> Conn.resp(:forbidden, "You can't access that page.") + |> Conn.halt() + + _false -> + conn + |> Controller.fetch_flash() + |> Controller.put_flash(:error, "You can't access that page.") + |> Controller.redirect(to: "/") + |> Conn.halt() + end end end diff --git a/lib/philomena_web/plugs/not_found_plug.ex b/lib/philomena_web/plugs/not_found_plug.ex index 3185218b..654eb959 100644 --- a/lib/philomena_web/plugs/not_found_plug.ex +++ b/lib/philomena_web/plugs/not_found_plug.ex @@ -7,10 +7,18 @@ defmodule PhilomenaWeb.NotFoundPlug do def call(conn), do: call(conn, nil) def call(conn, _opts) do - conn - |> Controller.fetch_flash() - |> Controller.put_flash(:error, "Couldn't find what you were looking for!") - |> Controller.redirect(to: "/") - |> Conn.halt() + case conn.assigns.ajax? do + true -> + conn + |> Conn.resp(:not_found, "Couldn't find what you were looking for!") + |> Conn.halt() + + false -> + conn + |> Controller.fetch_flash() + |> Controller.put_flash(:error, "Couldn't find what you were looking for!") + |> Controller.redirect(to: "/") + |> Conn.halt() + end end end