diff --git a/examples/form-validation/webserver.cljs b/examples/form-validation/webserver.cljs index 07924f5..43841dc 100644 --- a/examples/form-validation/webserver.cljs +++ b/examples/form-validation/webserver.cljs @@ -21,6 +21,15 @@ :date "You must enter a valid date in YYYY-MM-DD format." :count "You must enter a quantity between 5 and 10."}) +(def button-script + (str + "token=document.cookie.split('; ') + .find((row)=>row.startsWith('XSRF-TOKEN='))?.split('=')[1]; + ajax.onclick=()=>{fetch('/ajax', + {'method':'POST','body':'received!', + 'headers':{'Content-Type':'text/plain','XSRF-Token':token}}) + .then(r=>r.text()).then(d=>{ajaxresult.innerHTML=d})}")) + (defn view:form [csrf-token data validation-errors] (let [ve (or validation-errors #js {}) data (or data #js {})] @@ -42,9 +51,7 @@ [:div#ajaxresult] [:button#ajax "Send fetch request"] [:script {:dangerouslySetInnerHTML - {:__html - "ajax.onclick=()=>{fetch('/ajax',{'method':'POST','data':'hello','headers':{'Content-Type':'text/plain'}}) - .then(r=>r.text()).then(d=>{ajaxresult.innerHTML=d})}"}}]])) + {:__html button-script}}]])) (defn view:thank-you [] [:div @@ -90,7 +97,7 @@ (web/reset-routes app) (web/static-folder app "/css" "node_modules/minimal-stylesheet/") (.use app handle-csrf-error) - (.post app "/ajax" (fn [req res] (.send res (aget req "body")))) + (.post app "/ajax" (fn [req res] (js/console.log (aget req "body")) (.send res (aget req "body")))) (.use app "/" serve-form)) (defonce serve diff --git a/src/sitefoxtest/e2etests.cljs b/src/sitefoxtest/e2etests.cljs index 8ceefdf..9f9c779 100644 --- a/src/sitefoxtest/e2etests.cljs +++ b/src/sitefoxtest/e2etests.cljs @@ -331,7 +331,18 @@ ; then reload the first page to get a new token (.goto page (str base-url "?hello=1")) ; check the second tab can still successfully submit - (check-form-submit page2)) + (check-form-submit page2) + ; close the page2 tab + (.close page2)) + + ; Check that fetch requests still work with CSRF protection in place + (p/all [; click the ajax POST submit button + (-> page (.locator "button#ajax") .click) + ; wait for waitForResponse fetch request loading to complete + (.waitForResponse page #(.includes (.url %) "/ajax"))]) + (check-for-text + page "received!" + "The POST fetch request failed.") (log "Closing resources.") (j/call server :kill) @@ -340,4 +351,5 @@ (done)) #(catch-fail % done server browser)))))) +; (t/run-test sitefoxtest.e2etests/nbb-forms) (t/run-tests *ns*)