Properly handle failed captchas after XHR post (#85)

* handle form posts and xhr posts differently on captcha failure

* formatting
This commit is contained in:
Nick 2020-04-11 14:23:55 -04:00 committed by GitHub
parent 1836fef402
commit d247e01347
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 8 deletions

View file

@ -2,7 +2,8 @@ import { $$, makeEl, findFirstTextNode } from './utils/dom';
import { fire, delegate, leftClick } from './utils/events'; import { fire, delegate, leftClick } from './utils/events';
const headers = () => ({ const headers = () => ({
'x-csrf-token': window.booru.csrfToken 'x-csrf-token': window.booru.csrfToken,
'x-requested-with': 'XMLHttpRequest'
}); });
function confirm(event, target) { function confirm(event, target) {
@ -56,9 +57,13 @@ function formRemote(event, target) {
method: (target.dataset.method || target.method || 'POST').toUpperCase(), method: (target.dataset.method || target.method || 'POST').toUpperCase(),
headers: headers(), headers: headers(),
body: new FormData(target) body: new FormData(target)
}).then(response => }).then(response => {
if (response && response.status == 300) {
window.location.reload(true);
return;
}
fire(target, 'fetchcomplete', response) fire(target, 'fetchcomplete', response)
); });
} }
function formReset(event, target) { function formReset(event, target) {

View file

@ -1,7 +1,7 @@
defmodule PhilomenaWeb.CaptchaPlug do defmodule PhilomenaWeb.CaptchaPlug do
alias Philomena.Captcha alias Philomena.Captcha
alias Phoenix.Controller import Plug.Conn
alias Plug.Conn import Phoenix.Controller
def init([]), do: false def init([]), do: false
@ -19,14 +19,31 @@ defmodule PhilomenaWeb.CaptchaPlug do
false -> false ->
conn conn
|> Controller.put_flash( |> put_flash(
:error, :error,
"There was an error verifying you're not a robot. Please try again." "There was an error verifying you're not a robot. Please try again."
) )
|> Controller.redirect(external: conn.assigns.referrer) |> do_failure_response(ajax?(conn))
|> Conn.halt() |> halt()
end end
end end
defp maybe_check_captcha(conn, _user), do: conn defp maybe_check_captcha(conn, _user), do: conn
defp do_failure_response(conn, true) do
conn
|> put_status(:multiple_choices)
|> text("")
end
defp do_failure_response(conn, _false) do
redirect(conn, external: conn.assigns.referrer)
end
def ajax?(conn) do
case get_req_header(conn, "x-requested-with") do
[value] -> String.downcase(value) == "xmlhttprequest"
_ -> false
end
end
end end