Skip to content

Commit

Permalink
Merge pull request #100 from Ejdamm/issue87_refreshCaptcha
Browse files Browse the repository at this point in the history
Issue #87: Refresh captcha
  • Loading branch information
Ejdamm authored Dec 10, 2020
2 parents d9ce725 + f923206 commit 3283929
Show file tree
Hide file tree
Showing 14 changed files with 81 additions and 28 deletions.
2 changes: 1 addition & 1 deletion config/config.php.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ return [
# Monolog logger config. Log folder and file must be writable
'logger' => [
'name' => 'market-board',
'level' => Logger::DEBUG,
'level' => Logger::INFO,
'path' => __DIR__ . '/../logs/app.log',
'test_path' => __DIR__ . '/../logs/apptest.log',
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function change()
->addColumn('all_subcategories', 'string', ['default' => 'All subcategories'])
->addColumn('filter', 'string', ['default' => 'Filter'])
->addColumn('new', 'string', ['default' => 'New'])
->addColumn('refresh', 'string', ['default' => 'Refresh'])
->addColumn('unit_price', 'string', ['default' => 'Unit price'])
->addColumn('created', 'string', ['default' => 'Created'])
->addColumn('first', 'string', ['default' => 'First'])
Expand Down
1 change: 1 addition & 0 deletions resources/db/seeds/language/DefaultLanguage.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ private function generateConstantData()
'all_subcategories' => 'All subcategories',
'filter' => 'Filter',
'new' => 'New',
'refresh' => 'Refresh',
'unit_price' => 'Unit price',
'created' => 'Created',
'first' => 'First',
Expand Down
19 changes: 10 additions & 9 deletions resources/views/new_listing.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<div class="form-group">
<label for="category_dropdown">{{ language.category }}</label>
<select class="form-control" id="category_dropdown" name="category_id" required>
<option value="0">{{ language.choose_category }}</option>
<option value="">{{ language.choose_category }}</option>
{% for category in categories %}
<option value="{{ category.id }}" class="{{ category.category_name }}" {% if category.id == params.category_id %}selected{% endif %}>{{ category.category_name }}</option>
{% endfor %}
Expand All @@ -14,7 +14,7 @@
<div class="form-group">
<label for="subcategory_dropdown">{{ language.subcategory }}</label>
<select class="form-control" id="subcategory_dropdown" name="subcategory_id" required>
<option value="0">{{ language.choose_subcategory }}</option>
<option value="">{{ language.choose_subcategory }}</option>
{% for subcategory in subcategories %}
<option value="{{ subcategory.id }}" class="{{ subcategory.category_name }}" {% if subcategory.id == params.subcategory_id %}selected{% endif %}>{{ subcategory.subcategory_name }}</option>
{% endfor %}
Expand Down Expand Up @@ -44,8 +44,9 @@
<div class="form-group">
<label for="new_listing_captcha">{{ language.captcha }}</label>
<div class="form-inline">
<input type="text" class="form-control" id="new_listing_captcha" placeholder="{{ language.enter_captcha }}" name="captcha" required>
<input type="text" class="form-control" id="new_listing_captcha" placeholder="{{ language.enter_captcha }}" name="captcha">
<img class="mx-2" alt="captcha_image" src="{{ captcha }}" />
<button type="submit" class="btn btn-dark" name="refresh_captcha">{{ language.refresh }}</button>
</div>
</div>

Expand All @@ -54,7 +55,7 @@
{% include 'templates/gdpr.html.twig'%}
</div>

<button type="submit" class="btn btn-primary">{{ language.create_listing }}</button>
<button type="submit" class="btn btn-primary" name="new_listing_form">{{ language.create_listing }}</button>
</form>

<!-- query to filter second dropdown -->
Expand All @@ -68,10 +69,10 @@
let selectedSubcategory = $('#subcategory_dropdown option:selected');
let selectedCategory = $('#category_dropdown option:selected');
filterSubCategoryOptions(subCatOptions, selectedCategory);
if (selectedSubcategory.prop('class') === selectedCategory.prop('class') || selectedCategory.prop('value') === "0") {
$('#subcategory_dropdown option[value=' + selectedSubcategory.prop('value') + ']').prop('selected', true);
if (selectedSubcategory.prop('class') === selectedCategory.prop('class') || selectedCategory.prop('value') === "") {
$('#subcategory_dropdown option[value="' + selectedSubcategory.prop('value') + '"]').prop('selected', true);
} else {
$('#subcategory_dropdown option[value=0]').prop('selected', true);
$('#subcategory_dropdown option[value=""]').prop('selected', true);
}
});
Expand All @@ -96,9 +97,9 @@
// Always reset subcategory options
$('#subcategory_dropdown').append(options);
if (selectedCategory.prop('value') !== "0") {
if (selectedCategory.prop('value') !== "") {
// Remove all options which are not the default option or belonging to categoryClass
$('#subcategory_dropdown :not(.' + selectedCategory.prop('class') + ',option[value="0"])').remove();
$('#subcategory_dropdown :not(.' + selectedCategory.prop('class') + ',option[value=""])').remove();
}
}
</script>
Expand Down
3 changes: 2 additions & 1 deletion resources/views/single_listing.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@
<div class="form-group">
<label for="new_listing_captcha">{{ language.captcha }}</label>
<div class="form-inline">
<input type="text" class="form-control" id="new_listing_captcha" placeholder="{{ language.enter_captcha }}" name="captcha" required>
<input type="text" class="form-control" id="new_listing_captcha" placeholder="{{ language.enter_captcha }}" name="captcha">
<img class="mx-2" alt="captcha_image" src="{{ captcha }}" />
<button type="submit" class="btn btn-dark" name="refresh_captcha">{{ language.refresh }}</button>
</div>
</div>

Expand Down
2 changes: 1 addition & 1 deletion src/Controllers/HomepageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function get($request, $response, $args) : ResponseInterface

public function post($request, $response, $args): ResponseInterface
{
$this->logger->addError(get_class($this) . " POST not implemented");
$this->logger->addWarning(get_class($this) . " POST not implemented");
return $this->view->render($response->withStatus(501), 'errors/error501.html.twig', [
'language' => $this->language,
'settings' => $this->container->get("settings"),
Expand Down
2 changes: 1 addition & 1 deletion src/Controllers/MultipleListingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function get($request, $response, $args): ResponseInterface

public function post($request, $response, $args): ResponseInterface
{
$this->logger->addError(get_class($this) . " POST not implemented");
$this->logger->addWarning(get_class($this) . " POST not implemented");
return $this->view->render($response->withStatus(501), 'errors/error501.html.twig', [
'language' => $this->language,
'settings' => $this->container->get("settings"),
Expand Down
32 changes: 27 additions & 5 deletions src/Controllers/NewListingController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace MarketBoard\Controllers;

use Exception;
use MarketBoard\Categories;
use MarketBoard\EmailNewListing;
use MarketBoard\Listings;
Expand Down Expand Up @@ -33,7 +34,28 @@ public function get($request, $response, $args) : ResponseInterface
public function post($request, $response, $args) : ResponseInterface
{
$params = $request->getParams();
$this->logger->addInfo("Received post params:" . print_r($params, true));

if (array_key_exists("new_listing_form", $params)) {
$responseParams = $this->processNewListing($params);
} elseif (array_key_exists("refresh_captcha", $params)) {
$categories = new Categories($this->db);
$responseParams = [
'categories' => $categories->getMainCategories(),
'subcategories' => $categories->getSubcategories(),
'language' => $this->language,
'captcha' => Utils::createCaptcha($this->session),
'params' => $params,
'settings' => $this->container->get("settings"),
];
} else {
throw new Exception("Unknown post request was sent.");
}
return $this->view->render($response, 'new_listing.html.twig', $responseParams);
}

private function processNewListing($params)
{
$this->logger->addDebug("Received post params:" . print_r($params, true));

if (!$params['captcha'] || $this->session->get('captcha') != $params['captcha']) {
$alertText = $this->language['wrong_captcha'];
Expand All @@ -50,22 +72,22 @@ public function post($request, $response, $args) : ResponseInterface
}

$categories = new Categories($this->db);
return $this->view->render($response, 'new_listing.html.twig', [
return [
'categories' => $categories->getMainCategories(),
'subcategories' => $categories->getSubcategories(),
'alert' => ['level' => $alertLevel, 'text' => $alertText],
'language' => $this->language,
'captcha' => Utils::createCaptcha($this->session),
'params' => $params,
'settings' => $this->container->get("settings"),
]);
];
}

private function insertNewListing($params, $removalCode)
{
$listings = new Listings($this->db);
$insertedId = $listings->insertListing($params, $removalCode);
$this->logger->addInfo("Parameters inserted:", $params);
$this->logger->addDebug("Parameters inserted:", $params);
return $insertedId;
}

Expand All @@ -85,7 +107,7 @@ private function sendEmail($insertedId, $removalCode, $address)
// E-mail function is excluded if run in Travis since it's a closed environment and tests will fail
if (getenv('TRAVIS') != 'true') {
$this->mailer->setTo($address)->sendMessage(new EmailNewListing($emailParams, $this->language['email_new_listing_subject']));
$this->logger->addInfo("Sent email to " . $address);
$this->logger->addDebug("Sent email to " . $address);
}
}
}
14 changes: 12 additions & 2 deletions src/Controllers/SingleListingController.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,16 @@ public function post($request, $response, $args): ResponseInterface
} elseif (array_key_exists("email_form", $params)) {
$responseParams = $this->processContact($args['id'], $params);
return $this->view->render($response, 'single_listing.html.twig', $responseParams);
} elseif (array_key_exists("refresh_captcha", $params)) {
return $this->view->render($response, 'single_listing.html.twig', [
'listing' => $this->listings->getSingleListing($args['id']),
'language' => $this->language,
'captcha' => Utils::createCaptcha($this->session),
'params' => $params,
'settings' => $this->container->get("settings"),
]);
} else {
throw new Exception("Neither email_form nor removal_form was set.");
throw new Exception("Unknown post request was sent.");
}
}

Expand All @@ -77,6 +85,7 @@ private function processContact($listingId, $params)
'language' => $this->language,
'captcha' =>Utils::createCaptcha($this->session),
'params' => $params,
'settings' => $this->container->get("settings"),
];
}

Expand All @@ -102,12 +111,13 @@ private function processRemove($listingId, $removalCode)
'alert' => $alert,
'language' => $this->language,
'captcha' => Utils::createCaptcha($this->session),
'settings' => $this->container->get("settings"),
];
}

private function sendEmail($listingId, $sender, $receiver, $text)
{
$this->logger->addInfo("Sending email from: " . $sender . " to: " . $receiver);
$this->logger->addDebug("Sending email from: " . $sender . " to: " . $receiver);
$message = new stdClass;
$message->listingId = $listingId;
$message->message = $text;
Expand Down
18 changes: 15 additions & 3 deletions src/Listings.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ public function getSingleListing(int $id)
WHERE listings.id = ?;";
$statement = $this->prepareAndExecute($query, [$id]);
$result = $statement->fetch();
return $result;
if ($result) {
return $result;
} else {
return [];
}
}

public function getMultipleListings()
Expand All @@ -87,7 +91,11 @@ public function getMultipleListings()
LIMIT ? OFFSET ?;";
$statement = $this->prepareAndExecute($query, $params);
$result = $statement->fetchAll();
return $result;
if ($result) {
return $result;
} else {
return [];
}
}

public function insertListing($params, $removalCode)
Expand Down Expand Up @@ -129,7 +137,11 @@ public function getNrOfListings()
$statement = $this->prepareAndExecute($query, $this->params);

$count = $statement->fetch();
return intval($count['count']);
if ($count) {
return intval($count['count']);
} else {
return 0;
}
}

private function prepareAndExecute($query, $params=[])
Expand Down
7 changes: 6 additions & 1 deletion tests/functional/BaseTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -331,13 +331,18 @@ public function verifyEntryRemoved($table, $id)
*/
public function assertLogContains($expectedContent = array())
{
$actualLogging = file_get_contents($this->logFile);
$actualLogging = $this->getLogContent();

foreach ($expectedContent as $singleContent) {
$this->assertStringContainsString($singleContent, $actualLogging);
}
}

public function getLogContent()
{
return file_get_contents($this->logFile);
}

/**
* Verify the log file does not contain the given array
* @param array $expectedNotContain Array of strings with expected strings to NOT contain.
Expand Down
5 changes: 3 additions & 2 deletions tests/functional/NewListingPageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ public function testPOSTNewListing()
unset($listing_data['removal_code']);
unset($listing_data['created_at']);
$listing_data['captcha'] = self::$container['session']->get('captcha');
$listing_data['new_listing_form'] = null;
$response = $this->processRequest('POST', '/listings/new', $listing_data);
unset($listing_data['captcha']);
$this->assertEquals(200, $response->getStatusCode());
unset($listing_data['new_listing_form']);
$this->assertEquals(200, $response->getStatusCode(), $this->getLogContent());

$this->assertLogDoesNotContain(['ERROR']);
$this->assertLogContains(["INFO: Parameters inserted"]);

$this->verifyEntryInserted("listings", $listing_data);
}
Expand Down
1 change: 0 additions & 1 deletion tests/functional/SingleListingPageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ public function testSendMail()

$this->assertEquals(200, $response->getStatusCode());
$this->assertLogDoesNotContain(['ERROR']);
$this->assertLogContains(["INFO: Sending email from: " . $email_from . " to: " . self::$listing_data[0]['email']]);
$this->assertStringContainsString("Your E-mail was sent.", $htmlBody);
}
}
2 changes: 1 addition & 1 deletion tests/integration/ListingsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public function testGetSingleListingThatExist()
public function testGetSingleListingThatDontExist()
{
$actual = self::$listings->getSingleListing($this->last_inserted_id + 1);
$this->assertFalse($actual);
$this->assertEmpty($actual);
}

public function testRemoveListingThatExists()
Expand Down

0 comments on commit 3283929

Please sign in to comment.