Skip to content

Prevent users from creating more than 5 forum threads per day #1161 #1162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,5 @@ LOG_STACK=single
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

APP_MAX_THREAD_COUNT = 5
19 changes: 19 additions & 0 deletions app/Http/Controllers/Forum/ThreadsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,25 @@ public function create(): View

public function store(ThreadRequest $request): RedirectResponse
{
$userId = Auth::id(); // Get the authenticated user's ID
$midnight = now()->endOfDay();
$remainingSeconds = $midnight->diffInSeconds(now());

// Count the threads posted by the user today
$cacheKey = "user_threads_count_{$userId}";
$threadCount = Cache::remember($cacheKey, $remainingSeconds, function () use ($userId) {
return Thread::where('author_id', $userId)
->where('created_at', '>=', now()->startOfDay())
->count();
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't cache the results tbh. Maybe we can simply get the count by default with withCount: https://laravel.com/docs/11.x/eloquent-relationships#counting-related-models

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@driesvints can i use default alert of javascript

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In an ideal world I'd add a new "warning" method to SendsAlerts that gets implemented in the UI as well. But let's use $this->error( for now.


// Check if the user has reached the limit
if ($threadCount >= getenv('APP_MAX_THREAD_COUNT')) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be a fixed value. No need to pull from a config or env.

$this->error('You can only post a maximum of 5 threads per day.');
return redirect()->route('forum');
}


$this->dispatchSync(CreateThread::fromRequest($request, $uuid = Str::uuid()));

$thread = Thread::findByUuidOrFail($uuid);
Expand Down
Loading