Merge pull request 'Store answers atomically and limit word cloud input' (#31) from fix/atomic-votes into main
CI / Deploy / test (push) Successful in 52s
CI / Deploy / deploy (push) Successful in 4s

Reviewed-on: #31
This commit was merged in pull request #31.
This commit is contained in:
gnilebein committed 2026-11-08 22:35:42 +01:00
commit 6912d045cf
11 files changed
+224 -50

No files matched your search

+6 -1
View File
@@ -68,7 +68,8 @@ src/
VoteService Validiert + speichert Antworten (alle Abstimmungsregeln hier) VoteService Validiert + speichert Antworten (alle Abstimmungsregeln hier)
ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock) ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock)
PollStateService State-JSON für Presenter und Teilnehmende PollStateService State-JSON für Presenter und Teilnehmende
ThrottleService Rate-Limit pro IP (Cache 'throttle') ThrottleService Rate-Limit pro IP (Cache 'throttle'), in Controllern über `AppController::throttle()`:
Anlegen/Recover pro Stunde, Antworten (`vote`) pro Minute (`THROTTLE_VOTES_PER_MINUTE`, 429)
YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client)
QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen
SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam) SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam)
@@ -113,6 +114,10 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
- Teilnehmende sind anonym: nur `VoteService::participantHash()` (HMAC, pro Poll) speichern. - Teilnehmende sind anonym: nur `VoteService::participantHash()` (HMAC, pro Poll) speichern.
- Abgestimmt werden darf nur auf der **aktuellen** Folie (`polls.current_slide_id`), bei offener Abstimmung, - Abgestimmt werden darf nur auf der **aktuellen** Folie (`polls.current_slide_id`), bei offener Abstimmung,
aktivem Poll und einmal pro Teilnehmer. Diese Logik gehört in `VoteService`, nicht in Controller. aktivem Poll und einmal pro Teilnehmer. Diese Logik gehört in `VoteService`, nicht in Controller.
Prüfen und Speichern laufen in **einer Transaktion mit gesperrter Folienzeile** (`VoteService::lockSlide()`),
sonst entstehen bei Doppelklick/Retry doppelte Stimmen. Neue Regeln, die vorhandene Antworten lesen, gehören in diese Transaktion.
Request-Felder nur über `VoteService::stringField()` lesen (Arrays zählen als leer). Wortwolke: höchstens
`MAX_WORDS_PER_REQUEST` Begriffe pro Request und `MAX_WORDS` pro Person und Folie.
- **Ergebnisse gehören auf die Bühne, nicht aufs Endgerät.** Teilnehmende bekommen `results` nur, wo sie damit - **Ergebnisse gehören auf die Bühne, nicht aufs Endgerät.** Teilnehmende bekommen `results` nur, wo sie damit
interagieren (Wortwolke mit Upvotes, solange offen) und als Auflösung ihrer eigenen Antwort (Quiz nach `finished`, interagieren (Wortwolke mit Upvotes, solange offen) und als Auflösung ihrer eigenen Antwort (Quiz nach `finished`,
Reihenfolge nach dem Schließen) – dann nur die Lösung **ohne** Zählungen/Verteilung (`PollStateService::participantResults()` Reihenfolge nach dem Schließen) – dann nur die Lösung **ohne** Zählungen/Verteilung (`PollStateService::participantResults()`
+2
View File
@@ -34,6 +34,8 @@ SHOW_ADMIN_LINK_AFTER_CREATE=false
# Max. polls / recovery mails per IP and hour (0 = unlimited) # Max. polls / recovery mails per IP and hour (0 = unlimited)
THROTTLE_CREATE_PER_HOUR=10 THROTTLE_CREATE_PER_HOUR=10
THROTTLE_RECOVER_PER_HOUR=5 THROTTLE_RECOVER_PER_HOUR=5
# Max. answers per IP and minute (0 = unlimited). Keep it high: a whole audience may share one Wi-Fi/IP.
THROTTLE_VOTES_PER_MINUTE=600
# How often presenter and participant pages poll for updates (ms) # How often presenter and participant pages poll for updates (ms)
POLL_INTERVAL_MS=2000 POLL_INTERVAL_MS=2000
# Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s) # Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s)
+3 -1
View File
@@ -21,7 +21,7 @@ return [
* confirmation page (useful for local development without mail server). * confirmation page (useful for local development without mail server).
* Defaults to the debug flag. NEVER enable this in production, otherwise * Defaults to the debug flag. NEVER enable this in production, otherwise
* the e-mail confirmation is pointless. * the e-mail confirmation is pointless.
* - throttle: max. number of polls / recovery mails per IP and hour. * - throttle: max. number of polls / recovery mails per IP and hour, answers per IP and minute.
* - pollIntervalMs: how often presenter / participant pages poll for state. * - pollIntervalMs: how often presenter / participant pages poll for state.
*/ */
'Plenario' => [ 'Plenario' => [
@@ -39,6 +39,8 @@ return [
'throttle' => [ 'throttle' => [
'createPerHour' => (int)env('THROTTLE_CREATE_PER_HOUR', 10), 'createPerHour' => (int)env('THROTTLE_CREATE_PER_HOUR', 10),
'recoverPerHour' => (int)env('THROTTLE_RECOVER_PER_HOUR', 5), 'recoverPerHour' => (int)env('THROTTLE_RECOVER_PER_HOUR', 5),
// Answers (incl. word cloud entries and upvotes) per IP and minute; a whole audience may share one IP.
'votesPerMinute' => (int)env('THROTTLE_VOTES_PER_MINUTE', 600),
], ],
'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000), 'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000),
// Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva). // Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva).
+20
View File
@@ -3,7 +3,9 @@ declare(strict_types=1);
namespace App\Controller; namespace App\Controller;
use App\Service\ThrottleService;
use Cake\Controller\Controller; use Cake\Controller\Controller;
use Cake\Core\Configure;
use Cake\Event\EventInterface; use Cake\Event\EventInterface;
use Cake\Http\Response; use Cake\Http\Response;
@@ -38,6 +40,24 @@ class AppController extends Controller
->withHeader('Referrer-Policy', 'same-origin'); ->withHeader('Referrer-Policy', 'same-origin');
} }
/**
* Registers a hit of the client IP in a throttle bucket (see ThrottleService).
*
* @param string $bucket Throttle bucket
* @param string $configKey Configure key holding the limit (0 = unlimited)
* @param int $windowSeconds Length of the window
* @return bool Whether the request is still allowed
*/
protected function throttle(string $bucket, string $configKey, int $windowSeconds = ThrottleService::WINDOW_SECONDS): bool
{
return (new ThrottleService())->attempt(
$bucket,
(string)$this->request->clientIp(),
(int)Configure::read($configKey, 0),
$windowSeconds,
);
}
/** /**
* Returns a JSON response without going through the view layer. * Returns a JSON response without going through the view layer.
* *
-15
View File
@@ -7,7 +7,6 @@ use App\Captcha\CaptchaFactory;
use App\Mailer\PollMailer; use App\Mailer\PollMailer;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Model\Table\PollsTable; use App\Model\Table\PollsTable;
use App\Service\ThrottleService;
use Cake\Core\Configure; use Cake\Core\Configure;
use Cake\Http\Response; use Cake\Http\Response;
use Cake\Log\Log; use Cake\Log\Log;
@@ -228,20 +227,6 @@ class HomeController extends AppController
} }
} }
/**
* @param string $bucket Throttle bucket
* @param string $configKey Configure key holding the hourly limit
* @return bool
*/
protected function throttle(string $bucket, string $configKey): bool
{
return (new ThrottleService())->attempt(
$bucket,
(string)$this->request->clientIp(),
(int)Configure::read($configKey, 0),
);
}
/** /**
* Sends a mail and logs (instead of throwing) transport errors. * Sends a mail and logs (instead of throwing) transport errors.
* *
+7 -1
View File
@@ -118,8 +118,14 @@ class ParticipateController extends AppController
$slide = $stateService->currentSlide($poll); $slide = $stateService->currentSlide($poll);
$submittedSlideId = (int)$this->request->getData('slide_id'); $submittedSlideId = (int)$this->request->getData('slide_id');
$ajax = $this->request->is('ajax'); $ajax = $this->request->is('ajax');
$status = 200;
try { try {
// Generous per IP (a whole audience may share one Wi-Fi), only stops scripted floods.
if (!$this->throttle('vote', 'Plenario.throttle.votesPerMinute', 60)) {
$status = 429;
throw new VoteException(__('Zu viele Antworten in kurzer Zeit. Bitte warte einen Moment und versuche es dann noch einmal.'));
}
if ($slide === null || $slide->id !== $submittedSlideId) { if ($slide === null || $slide->id !== $submittedSlideId) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.')); throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
} }
@@ -141,7 +147,7 @@ class ParticipateController extends AppController
'ok' => $ok, 'ok' => $ok,
'message' => $message, 'message' => $message,
'state' => $stateService->forParticipant($poll, $this->participantHash($poll)), 'state' => $stateService->forParticipant($poll, $this->participantHash($poll)),
]); ], $status);
} }
$ok ? $this->Flash->success($message) : $this->Flash->error($message); $ok ? $this->Flash->success($message) : $this->Flash->error($message);
+5 -3
View File
@@ -7,7 +7,8 @@ use Cake\Cache\Cache;
/** /**
* Very small fixed-window rate limiter backed by the "throttle" cache config. * Very small fixed-window rate limiter backed by the "throttle" cache config.
* Used to limit poll creation and recovery mails per client IP. * Used to limit poll creation and recovery mails per client IP (per hour) and
* participant answers per client IP (per minute).
*/ */
class ThrottleService class ThrottleService
{ {
@@ -19,9 +20,10 @@ class ThrottleService
* @param string $bucket Logical action, e.g. "create" * @param string $bucket Logical action, e.g. "create"
* @param string $identifier Client identifier, e.g. IP address * @param string $identifier Client identifier, e.g. IP address
* @param int $limit Allowed hits per window; <= 0 disables throttling * @param int $limit Allowed hits per window; <= 0 disables throttling
* @param int $windowSeconds Length of the window
* @return bool * @return bool
*/ */
public function attempt(string $bucket, string $identifier, int $limit): bool public function attempt(string $bucket, string $identifier, int $limit, int $windowSeconds = self::WINDOW_SECONDS): bool
{ {
if ($limit <= 0) { if ($limit <= 0) {
return true; return true;
@@ -31,7 +33,7 @@ class ThrottleService
$now = time(); $now = time();
/** @var array{start: int, hits: int}|null $state */ /** @var array{start: int, hits: int}|null $state */
$state = Cache::read($key, 'throttle'); $state = Cache::read($key, 'throttle');
if (!is_array($state) || $state['start'] + self::WINDOW_SECONDS <= $now) { if (!is_array($state) || $state['start'] + $windowSeconds <= $now) {
$state = ['start' => $now, 'hits' => 0]; $state = ['start' => $now, 'hits' => 0];
} }
if ($state['hits'] >= $limit) { if ($state['hits'] >= $limit) {
+87 -28
View File
@@ -6,6 +6,7 @@ namespace App\Service;
use App\Model\Entity\Poll; use App\Model\Entity\Poll;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable; use App\Model\Table\ResponsesTable;
use Cake\Database\Expression\IdentifierExpression;
use Cake\ORM\Locator\LocatorAwareTrait; use Cake\ORM\Locator\LocatorAwareTrait;
use Cake\Utility\Security; use Cake\Utility\Security;
@@ -21,6 +22,9 @@ use Cake\Utility\Security;
* exists in the cloud is an upvote – both are stored as the same row. * exists in the cloud is an upvote – both are stored as the same row.
* `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing * `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing
* word of someone else. Each participant rates a word only once (up or down). * word of someone else. Each participant rates a word only once (up or down).
* At most MAX_WORDS_PER_REQUEST terms per request and MAX_WORDS per participant and slide.
* - checks and insert run in one transaction with the slide row locked (see lockSlide()),
* so concurrent or repeated requests cannot store an answer twice.
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen() * - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
* includes the deadline of a timed quiz). * includes the deadline of a timed quiz).
* - Q&A (see QaService for the stages): `question` (text) only while collecting, * - Q&A (see QaService for the stages): `question` (text) only while collecting,
@@ -40,6 +44,12 @@ class VoteService
public const MAX_TEXT_LENGTH = 500; public const MAX_TEXT_LENGTH = 500;
public const MAX_QA_QUESTIONS = 10; public const MAX_QA_QUESTIONS = 10;
/**
* Word cloud: terms per request and terms a participant may name or upvote per slide.
*/
public const MAX_WORDS_PER_REQUEST = 10;
public const MAX_WORDS = 50;
/** /**
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null). * `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
*/ */
@@ -97,31 +107,71 @@ class VoteService
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
}); });
} }
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) { // Checks (answered already, upvote budget, duplicates) and the insert run as one unit,
throw new VoteException(__('Du hast bereits abgestimmt.')); // so a double click or a retried request cannot store an answer twice.
} $this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $data): void {
$this->lockSlide($slide);
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) {
throw new VoteException(__('Du hast bereits abgestimmt.'));
}
$rows = match ($slide->type) { $rows = match ($slide->type) {
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data), Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data), Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
Slide::TYPE_OPEN => $this->openRows($data), Slide::TYPE_OPEN => $this->openRows($data),
Slide::TYPE_SCALE => $this->scaleRows($slide, $data), Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
Slide::TYPE_QUIZ => $this->quizRows($slide, $data), Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data), Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
Slide::TYPE_ORDER => $this->orderRows($slide, $data), Slide::TYPE_ORDER => $this->orderRows($slide, $data),
default => throw new VoteException(__('Unbekannter Folientyp.')), default => throw new VoteException(__('Unbekannter Folientyp.')),
}; };
$entities = []; $entities = [];
foreach ($rows as $row) { foreach ($rows as $row) {
$entities[] = $this->Responses->newEntity($row + [ $entities[] = $this->Responses->newEntity($row + [
'slide_id' => $slide->id, 'slide_id' => $slide->id,
'participant_hash' => $participantHash, 'participant_hash' => $participantHash,
]); ]);
} }
if ($entities !== []) { if ($entities !== []) {
$this->Responses->saveManyOrFail($entities); $this->Responses->saveManyOrFail($entities);
} }
});
}
/**
* Serialises answers to one slide for the rest of the transaction.
*
* A no-op write on the slide row (`position = position`) is the portable lock: MySQL/MariaDB
* and PostgreSQL lock the row until commit, SQLite takes its write lock before anything is
* read. Must be the first statement of the transaction, so later reads see committed answers
* of concurrent requests. Neither `modified` nor any value changes.
*
* @param \App\Model\Entity\Slide $slide Slide
* @return void
*/
protected function lockSlide(Slide $slide): void
{
$this->fetchTable('Slides')->updateQuery()
->set(['position' => new IdentifierExpression('position')])
->where(['id' => $slide->id])
->execute()
->closeCursor();
}
/**
* A request field as string; arrays and other non-scalar values count as empty
* (instead of being stored as "Array").
*
* @param array<string, mixed> $data Request data
* @param string $key Field
* @return string
*/
protected static function stringField(array $data, string $key): string
{
$value = $data[$key] ?? '';
return is_scalar($value) ? (string)$value : '';
} }
/** /**
@@ -227,7 +277,7 @@ class VoteService
if ($stage !== Slide::QA_COLLECT) { if ($stage !== Slide::QA_COLLECT) {
throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.')); throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.'));
} }
$text = trim((string)preg_replace('/\s+/u', ' ', (string)($data['question'] ?? ''))); $text = trim((string)preg_replace('/\s+/u', ' ', self::stringField($data, 'question')));
if ($text === '') { if ($text === '') {
throw new VoteException(__('Bitte gib eine Frage ein.')); throw new VoteException(__('Bitte gib eine Frage ein.'));
} }
@@ -328,10 +378,16 @@ class VoteService
$existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up']))); $existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up'])));
$downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true); $downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true);
if (($data['vote'] ?? null) === 'down') { if (($data['vote'] ?? null) === 'down') {
return $this->downvoteRows($slide, (string)($data['word'] ?? ''), $existing, $downvoted); return $this->downvoteRows($slide, self::stringField($data, 'word'), $existing, $downvoted);
} }
$input = array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? [])); $input = array_filter(
array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? [])),
fn($word) => is_scalar($word) && trim((string)$word) !== '',
);
if (count($input) > self::MAX_WORDS_PER_REQUEST) {
throw new VoteException(__('Bitte gib höchstens {0} Begriffe auf einmal ein.', self::MAX_WORDS_PER_REQUEST));
}
$seen = array_fill_keys($existing, true); $seen = array_fill_keys($existing, true);
$words = []; $words = [];
@@ -362,6 +418,9 @@ class VoteService
default => __('Bitte gib einen Begriff ein.'), default => __('Bitte gib einen Begriff ein.'),
}); });
} }
if (count($existing) + count($words) > self::MAX_WORDS) {
throw new VoteException(__('Du kannst bei dieser Frage höchstens {0} Begriffe nennen oder unterstützen.', self::MAX_WORDS));
}
return array_map(fn(string $word) => ['text_value' => $word], $words); return array_map(fn(string $word) => ['text_value' => $word], $words);
} }
@@ -399,7 +458,7 @@ class VoteService
*/ */
protected function openRows(array $data): array protected function openRows(array $data): array
{ {
$text = trim((string)($data['text'] ?? '')); $text = trim(self::stringField($data, 'text'));
if ($text === '') { if ($text === '') {
throw new VoteException(__('Bitte gib eine Antwort ein.')); throw new VoteException(__('Bitte gib eine Antwort ein.'));
} }
@@ -424,7 +483,7 @@ class VoteService
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max)); throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
} }
// The optional comment is stored in the same row; ignored if the slide has no comment field. // The optional comment is stored in the same row; ignored if the slide has no comment field.
$comment = $slide->hasComments() ? trim((string)($data['comment'] ?? '')) : ''; $comment = $slide->hasComments() ? trim(self::stringField($data, 'comment')) : '';
if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) { if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH)); throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
} }
@@ -5,6 +5,8 @@ namespace App\Test\TestCase\Controller;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Test\TestCase\PlenarioTestTrait; use App\Test\TestCase\PlenarioTestTrait;
use Cake\Cache\Cache;
use Cake\Core\Configure;
use Cake\ORM\TableRegistry; use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestTrait; use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase; use Cake\TestSuite\TestCase;
@@ -28,6 +30,7 @@ class ParticipateControllerTest extends TestCase
{ {
parent::setUp(); parent::setUp();
$this->enableCsrfToken(); $this->enableCsrfToken();
Cache::clear('throttle');
} }
public function testUnknownCodeIs404(): void public function testUnknownCodeIs404(): void
@@ -157,4 +160,24 @@ class ParticipateControllerTest extends TestCase
$this->get('/p/' . $poll->join_code); $this->get('/p/' . $poll->join_code);
$this->assertResponseContains('Diese Umfrage ist geschlossen'); $this->assertResponseContains('Diese Umfrage ist geschlossen');
} }
public function testVotesAreThrottledPerIp(): void
{
Configure::write('Plenario.throttle.votesPerMinute', 2);
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$this->goLive($poll, $slide);
foreach (['Kaffee', 'Tee', 'Wasser'] as $i => $word) {
$this->cookie('plenario_pid', self::PID);
$this->configRequest(['headers' => ['X-Requested-With' => 'XMLHttpRequest', 'Accept' => 'application/json']]);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'word' => $word]);
$body = json_decode((string)$this->_response->getBody(), true);
$this->assertSame($i < 2, $body['ok'], $word);
}
$this->assertResponseCode(429);
$this->assertStringContainsString('Zu viele Antworten', $body['message']);
$this->assertArrayHasKey('state', $body);
$this->assertSame(2, TableRegistry::getTableLocator()->get('Responses')->find()->where(['slide_id' => $slide->id])->count());
}
} }
@@ -210,4 +210,73 @@ class VoteServiceTest extends TestCase
$this->expectExceptionMessage('Downvotes sind bei dieser Frage nicht möglich.'); $this->expectExceptionMessage('Downvotes sind bei dieser Frage nicht möglich.');
$service->submit($poll, $slide, 'p2', ['word' => 'Kaffee', 'vote' => 'down']); $service->submit($poll, $slide, 'p2', ['word' => 'Kaffee', 'vote' => 'down']);
} }
public function testWordcloudLimitsWordsPerRequest(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$poll = $this->goLive($poll, $slide);
$words = array_map(fn(int $i) => 'Begriff ' . $i, range(1, VoteService::MAX_WORDS_PER_REQUEST + 1));
$this->expectExceptionMessage('höchstens ' . VoteService::MAX_WORDS_PER_REQUEST . ' Begriffe auf einmal');
(new VoteService())->submit($poll, $slide, 'p1', ['words' => $words]);
}
public function testWordcloudLimitsWordsPerParticipant(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
foreach (array_chunk(range(1, VoteService::MAX_WORDS), VoteService::MAX_WORDS_PER_REQUEST) as $chunk) {
$service->submit($poll, $slide, 'p1', ['words' => array_map(fn(int $i) => 'Begriff ' . $i, $chunk)]);
}
$this->assertSame(VoteService::MAX_WORDS, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count());
// Others can still add words.
$service->submit($poll, $slide, 'p2', ['word' => 'Noch einer']);
$this->expectExceptionMessage('höchstens ' . VoteService::MAX_WORDS . ' Begriffe');
$service->submit($poll, $slide, 'p1', ['word' => 'Einer zu viel']);
}
public function testArrayInputIsNeverStoredAsText(): void
{
[$poll] = $this->createPoll();
$open = $this->createSlide($poll, Slide::TYPE_OPEN);
$poll = $this->goLive($poll, $open);
$service = new VoteService();
try {
$service->submit($poll, $open, 'p1', ['text' => ['injected']]);
$this->fail('Array input must be rejected.');
} catch (VoteException $e) {
$this->assertSame('Bitte gib eine Antwort ein.', $e->getMessage());
}
$cloud = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$poll = $this->goLive($poll, $cloud);
$service->submit($poll, $cloud, 'p1', ['words' => [['nested'], 'Kaffee']]);
$texts = $this->fetchTable('Responses')->find()->where(['slide_id' => $cloud->id])->all()->extract('text_value')->toList();
$this->assertSame(['Kaffee'], $texts);
}
public function testRejectedVoteLeavesNoRows(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['option_id' => $slide->slide_options[0]->id]);
try {
// A repeated request (double click, retry) is rejected and stores nothing.
$service->submit($poll, $slide, 'p1', ['option_id' => $slide->slide_options[1]->id]);
$this->fail('Second vote must be rejected.');
} catch (VoteException $e) {
$this->assertSame('Du hast bereits abgestimmt.', $e->getMessage());
}
$this->assertSame(1, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count());
// The lock does not touch the slide.
$this->assertEquals($slide->modified, $this->slidesTable()->get($slide->id)->modified);
$this->assertSame($slide->position, $this->slidesTable()->get($slide->id)->position);
}
} }
+2 -1
View File
@@ -79,7 +79,8 @@
'X-CSRF-Token': csrfToken() 'X-CSRF-Token': csrfToken()
} }
}).then(function (response) { }).then(function (response) {
if (!response.ok) { // 429 (too many answers) carries a message for the participant like any other rejection.
if (!response.ok && response.status !== 429) {
throw new Error('HTTP ' + response.status); throw new Error('HTTP ' + response.status);
} }
return response.json(); return response.json();