feat: add guestbook with rate limiting (#6)
* Re-add guestbook w/ rate limiting * Add guestbook to navbar
This commit is contained in:
parent
8adae46775
commit
94133ec0f7
12 changed files with 329 additions and 91 deletions
29
app/Http/Controllers/GuestbookController.php
Normal file
29
app/Http/Controllers/GuestbookController.php
Normal file
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use DB;
|
||||
|
||||
class GuestbookController extends Controller {
|
||||
public function guestbook() {
|
||||
return view('pages.guestbook');
|
||||
}
|
||||
|
||||
public function guestbookPost(Request $request) {
|
||||
$this->validate($request, [
|
||||
'name' => 'required',
|
||||
'message' => 'required'
|
||||
]);
|
||||
|
||||
DB::insert('INSERT INTO guestbook_entries (name, timestamp, ip_address, agent, message) values (?, ?, ?, ?, ?)', array(
|
||||
htmlspecialchars($request->get('name')),
|
||||
time(),
|
||||
$request->ip(),
|
||||
$request->userAgent(),
|
||||
htmlspecialchars($request->get('message'))
|
||||
));
|
||||
|
||||
return back()->with('success', 'Entry submitted successfully!');
|
||||
}
|
||||
}
|
|
@ -45,6 +45,11 @@ class Kernel extends HttpKernel
|
|||
],
|
||||
];
|
||||
|
||||
protected $routeMiddleware = [
|
||||
'rate_limit' => \App\Http\Middleware\RateLimiter::class,
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* The application's middleware aliases.
|
||||
*
|
||||
|
|
32
app/Http/Middleware/RateLimiter.php
Normal file
32
app/Http/Middleware/RateLimiter.php
Normal file
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RateLimiter
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$ipAddress = $request->ip();
|
||||
$cacheKey = 'rate_limit_' . $ipAddress;
|
||||
|
||||
if (Cache::has($cacheKey)) {
|
||||
// If the cache key exists, the IP has submitted an entry within the last hour
|
||||
return response()->view('errors.ratelimit-guestbook', [], 429);
|
||||
}
|
||||
|
||||
// Add the IP address to the cache and set the expiration time to one hour
|
||||
Cache::put($cacheKey, true, 60);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue