Skip to content

Commit

Permalink
Create middleware that redirects back to log in page if unauthenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
range-of-motion committed Nov 9, 2024
1 parent ee39a0f commit 71e2ae5
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
2 changes: 1 addition & 1 deletion app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class Kernel extends HttpKernel
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth' => \App\Http\Middleware\RedirectIfUnauthenticated::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
Expand Down
20 changes: 20 additions & 0 deletions app/Http/Middleware/RedirectIfUnauthenticated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfUnauthenticated
{
public function handle(Request $request, Closure $next): Response
{
if (!Auth::check()) {
return redirect()->route('log-in');
}

return $next($request);
}
}
10 changes: 6 additions & 4 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
Route::get('/register', [RegisterController::class, 'index'])->name('register');
Route::post('/register', [RegisterController::class, 'store']);

Route::get('/dashboard', DashboardController::class)->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/dashboard', DashboardController::class)->name('dashboard');

Route::get('/transactions', [TransactionController::class, 'index'])->name('transactions.index');
Route::get('/transactions/create', [TransactionController::class, 'create'])->name('transactions.create');
Route::post('/transactions', [TransactionController::class, 'store']);
Route::get('/transactions', [TransactionController::class, 'index'])->name('transactions.index');
Route::get('/transactions/create', [TransactionController::class, 'create'])->name('transactions.create');
Route::post('/transactions', [TransactionController::class, 'store']);
});

0 comments on commit 71e2ae5

Please sign in to comment.