Skip to content

Commit

Permalink
Merge pull request #62 from PhpGt/61-post-only
Browse files Browse the repository at this point in the history
Only inject into POST forms, closes #61
  • Loading branch information
g105b authored Dec 31, 2018
2 parents f8b7236 + ae6ff0b commit 0f39d43
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 24 deletions.
5 changes: 5 additions & 0 deletions src/HTMLDocumentProtector.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ public function protectAndInject(
$this->tokenStore->saveToken($token);

foreach($forms as $form) {
$formMethod = $form->getAttribute("method");
if(strtolower($formMethod) !== "post") {
continue;
}

$csrfElement = $this->document->createElement(
"input"
);
Expand Down
53 changes: 29 additions & 24 deletions test/unit/HTMLDocumentProtectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ class HTMLDocumentProtectorTest extends TestCase {
<body>
<h1>This HTML is for the unit test.</h1>
<p>Hello</p>
<form method="POST">
<input type="text">
<button type="submit"></button>
</form>
<form method="POST">
<input type="text">
<button type="submit"></button>
</form>
</body>
</html>
HTML;
Expand All @@ -50,17 +51,16 @@ class HTMLDocumentProtectorTest extends TestCase {
<body>
<h1>This HTML is for the unit test.</h1>
<p>Hello</p>
<form method="POST">
<input type="text">
<button type="submit"></button>
</form>
<form method="GET">
<input type="text" value="A text field">
<button type="submit"></button>
</form>
<!-- an empty form too...-->
<form method="POST">
</form>
<form method="POST">
<input type="text">
<button type="submit"></button>
</form>
<form method="GET">
<input type="text" value="A text field">
<button type="submit"></button>
</form>
<!-- an empty form too...-->
<form method="POST"></form>
</body>
</html>
HTML;
Expand All @@ -77,9 +77,9 @@ class HTMLDocumentProtectorTest extends TestCase {
<body>
<h1>This HTML is for the unit test.</h1>
<p>Hello</p>
<!-- an empty form too...-->
<form method="POST">
</form>
<!-- an empty form too...-->
<form method="POST">
</form>
</body>
</html>
HTML;
Expand Down Expand Up @@ -153,12 +153,17 @@ public function testMultipleForms() {

// check that the token has been injected in all forms
$doc = $sut->getHTMLDocument();
$this->assertEquals(
3, $doc->querySelectorAll(
"input[name='" . HTMLDocumentProtector::TOKEN_NAME . "']")->length);
$this->assertEquals(
1, $doc->querySelectorAll(
"head meta[name='" . HTMLDocumentProtector::TOKEN_NAME . "']")->length);
$this->assertCount(
2,
$doc->querySelectorAll(
"input[name='" . HTMLDocumentProtector::TOKEN_NAME . "']"
)
);
$this->assertCount(
1,
$doc->querySelectorAll(
"head meta[name='" . HTMLDocumentProtector::TOKEN_NAME . "']")
);
}

public function testSingleCodeSharedAcrossForms() {
Expand Down

0 comments on commit 0f39d43

Please sign in to comment.