diff options
author | Frankie B <git@diskfloppy.me> | 2023-07-16 01:49:09 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-07-16 01:49:09 +0100 |
commit | 8482a98ca6a767062917747a0b016a9ab4d35f01 (patch) | |
tree | 0ab0e8d3baf5b421ab909bc731334e2deff82fe0 /app/Http | |
parent | 1b267f61029e7d4b824979709434ffb437c347b8 (diff) |
feat: add guestbook with rate limiting (#6)
* Re-add guestbook w/ rate limiting
* Add guestbook to navbar
Diffstat (limited to 'app/Http')
-rw-r--r-- | app/Http/Controllers/GuestbookController.php | 29 | ||||
-rw-r--r-- | app/Http/Kernel.php | 5 | ||||
-rw-r--r-- | app/Http/Middleware/RateLimiter.php | 32 |
3 files changed, 66 insertions, 0 deletions
diff --git a/app/Http/Controllers/GuestbookController.php b/app/Http/Controllers/GuestbookController.php new file mode 100644 index 0000000..aff30ed --- /dev/null +++ b/app/Http/Controllers/GuestbookController.php @@ -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!'); + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 1fb53dc..4eab7b8 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -45,6 +45,11 @@ class Kernel extends HttpKernel ], ]; + protected $routeMiddleware = [ + 'rate_limit' => \App\Http\Middleware\RateLimiter::class, + ]; + + /** * The application's middleware aliases. * diff --git a/app/Http/Middleware/RateLimiter.php b/app/Http/Middleware/RateLimiter.php new file mode 100644 index 0000000..c81da43 --- /dev/null +++ b/app/Http/Middleware/RateLimiter.php @@ -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); + } +} |