Assignment s Of Day 9 Middleware Basics
Assignment s Of Day 9
Middleware Basics
Assignment 1: Create a Custom Middleware to Check Age
Problem Statement:
Create a middleware that checks whether the user is older than 18 years before they can access certain routes.
Steps to Solve:
1. Create the Middleware: Open your terminal and navigate to your Laravel project directory. Run the following command to create a new middleware called CheckAge:
bash
Copy code
php artisan make:middleware CheckAge
This command will generate a new file CheckAge.php in the app/Http/Middleware directory.
2. Define the Middleware Logic: Open the CheckAge.php file and update the handle() method to check the age from the request data.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Assume the age is passed in the request data
if ($request->age < 18) {
return response('You must be 18 years or older to access this page.', 403);
}
// Proceed to the next middleware or the controller if the age is valid
return $next($request);
}
}
3. Register the Middleware: Open the app/Http/Kernel.php file and add the new middleware to the $routeMiddleware array:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'check.age' => \App\Http\Middleware\CheckAge::class,
];
4. Use the Middleware on a Route: Open your routes/web.php file and apply the check.age middleware to a route that should only be accessible to users aged 18 or older.
Code:
php
Copy code
use Illuminate\Support\Facades\Route;
Route::get('/profile', function () {
return 'You have access to this page!';
})->middleware('check.age');
5. Testing: Test the functionality by visiting the /profile route with different age values in the request (for example, use query parameters or form data to send the age).
Example request URL:
arduino
Copy code
http://your-app.test/profile?age=15
This should return the message: "You must be 18 years or older to access this page."
Assignment 2: Apply Middleware for Authentication
Problem Statement:
Create a middleware that checks if the user is authenticated before they can access a protected route.
Steps to Solve:
1. Create the Middleware: Run the following Artisan command to create a new middleware called CheckAuthenticated:
bash
Copy code
php artisan make:middleware CheckAuthenticated
This will create the CheckAuthenticated.php file in the app/Http/Middleware directory.
2. Define the Middleware Logic: Open the CheckAuthenticated.php file and define the logic in the handle() method to check if the user is authenticated. You can use Laravel's built-in authentication methods, such as auth()->check().
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check if the user is authenticated
if (!Auth::check()) {
return redirect('/login'); // Redirect to login page if not authenticated
}
// Proceed to the next middleware or controller if authenticated
return $next($request);
}
}
3. Register the Middleware: In the app/Http/Kernel.php file, register the middleware in the $routeMiddleware array:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'auth.check' => \App\Http\Middleware\CheckAuthenticated::class,
];
4. Use the Middleware on Routes: In routes/web.php, apply the auth.check middleware to any routes you want to protect. For example, you can protect the /dashboard route:
Code:
php
Copy code
Route::get('/dashboard', function () {
return 'Welcome to the dashboard!';
})->middleware('auth.check');
5. Testing: To test the middleware:
o Ensure that your app has user authentication set up (you can use Laravel's built-in authentication or a custom implementation).
o Try to visit the /dashboard route when you are not logged in. You should be redirected to the login page.
o After logging in, try accessing the /dashboard route again.
Assignment 3: Create and Apply Middleware to Handle CSRF Token
Problem Statement:
Create a middleware that verifies whether a CSRF token is present in the request headers, and if not, returns a response indicating the request is invalid.
Steps to Solve:
1. Create the Middleware: Run the Artisan command to generate a middleware called CheckCsrfToken:
bash
Copy code
php artisan make:middleware CheckCsrfToken
This will create the CheckCsrfToken.php file in the app/Http/Middleware directory.
2. Define the Middleware Logic: Open the CheckCsrfToken.php file and implement the logic to check for the presence of a CSRF token in the request. You can use the csrf_token() helper function to check the token.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
class CheckCsrfToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check if CSRF token is present in the request
if ($request->header('X-CSRF-TOKEN') !== csrf_token()) {
return response('Invalid CSRF Token', 403); // Return an error if no valid token is found
}
// Proceed to the next middleware or controller
return $next($request);
}
}
3. Register the Middleware: Open app/Http/Kernel.php and register the CheckCsrfToken middleware in the $routeMiddleware array:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'csrf.check' => \App\Http\Middleware\CheckCsrfToken::class,
];
4. Apply Middleware to Routes: In routes/web.php, apply the csrf.check middleware to any routes that you want to protect with a CSRF token check.
Code:
php
Copy code
Route::post('/submit-form', function () {
return 'Form submitted successfully!';
})->middleware('csrf.check');
5. Testing: To test:
o Make a POST request to /submit-form without including the correct CSRF token in the request header.
o The middleware should return a 403 Forbidden response with the message "Invalid CSRF Token".
o Add the correct CSRF token to the request headers and test again. The request should now proceed successfully.
Assignment 4: Group Middleware for Web Routes
Problem Statement:
Use a group of middleware for routes that require both authentication and CSRF protection.
Steps to Solve:
1. Create Middleware for Authentication and CSRF Protection: You can combine the authentication and CSRF middleware into one group. The CSRF middleware is already registered in Laravel, so you only need to register the authentication middleware.
2. Apply Middleware Group to Routes: In the routes/web.php file, apply both auth and csrf middleware to routes that require both authentication and CSRF protection.
Code:
php
Copy code
Route::middleware(['auth', 'csrf.check'])->group(function () {
Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
});
Route::get('/settings', function () {
return 'Change your settings here.';
});
});
3. Testing:
o Test the routes to ensure both authentication and CSRF protection are applied.
o Try accessing these routes without being logged in or without a valid CSRF token, and check that the appropriate error responses are returned.
Conclusion:
These assignments help students practice and understand middleware concepts in Laravel. By following the step-by-step solutions, students will get hands-on experience in creating, registering, and using middleware to filter HTTP requests based on conditions such as authentication, age validation, and CSRF token verification.
4o
You said:
some more
ChatGPT said:
ChatGPT
Assignment 5: Middleware to Log User IP Address
Problem Statement:
Create a middleware that logs the user's IP address whenever they make a request to the application.
Steps to Solve:
1. Create the Middleware: Use Artisan to generate a new middleware called LogIpAddress:
bash
Copy code
php artisan make:middleware LogIpAddress
2. Define the Middleware Logic: In the handle() method of LogIpAddress.php, use Laravel's logging functionality to log the user's IP address.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Log;
class LogIpAddress
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Log the user's IP address
Log::info('User IP Address: ' . $request->ip());
// Proceed to the next middleware or controller
return $next($request);
}
}
3. Register the Middleware: Open app/Http/Kernel.php and register the middleware in the $routeMiddleware array:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'log.ip' => \App\Http\Middleware\LogIpAddress::class,
];
4. Apply Middleware to a Route: In the routes/web.php file, apply the log.ip middleware to a route:
Code:
php
Copy code
Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
})->middleware('log.ip');
5. Testing: After accessing the /dashboard route, check the storage/logs/laravel.log file. It should contain a log entry for the user's IP address.
Assignment 6: Middleware for User Roles (Admin Access)
Problem Statement:
Create a middleware that restricts access to a route based on the user's role. Only users with the admin role should be able to access the /admin route.
Steps to Solve:
1. Create the Middleware: Generate a new middleware called CheckAdminRole:
bash
Copy code
php artisan make:middleware CheckAdminRole
2. Define the Middleware Logic: In the handle() method, check the role of the authenticated user. If the user is not an admin, redirect them to a "403 Forbidden" page.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckAdminRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check if the user is authenticated and has the 'admin' role
if (Auth::check() && Auth::user()->role !== 'admin') {
return response('Forbidden', 403); // If not admin, return 403 Forbidden
}
// Proceed to the next middleware or controller if the user is an admin
return $next($request);
}
}
3. Register the Middleware: Register the CheckAdminRole middleware in app/Http/Kernel.php:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'admin.role' => \App\Http\Middleware\CheckAdminRole::class,
];
4. Apply the Middleware to a Route: Use the middleware in routes/web.php for the /admin route.
Code:
php
Copy code
Route::get('/admin', function () {
return 'Welcome to the Admin Dashboard!';
})->middleware('admin.role');
5. Testing:
o Ensure that you have users with both admin and non-admin roles in your application.
o Try accessing the /admin route with both types of users. Users with the admin role should have access, while others should see a "403 Forbidden" response.
Assignment 7: Middleware to Track Request Execution Time
Problem Statement:
Create a middleware that tracks the time it takes for a request to execute and logs the result.
Steps to Solve:
1. Create the Middleware: Generate a new middleware called TrackExecutionTime:
bash
Copy code
php artisan make:middleware TrackExecutionTime
2. Define the Middleware Logic: In the handle() method, record the time before the request is processed and calculate the execution time after the response is returned.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Log;
class TrackExecutionTime
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Record the start time of the request
$startTime = microtime(true);
// Process the request
$response = $next($request);
// Calculate the execution time
$executionTime = microtime(true) - $startTime;
// Log the execution time
Log::info('Request Execution Time: ' . $executionTime . ' seconds');
return $response;
}
}
3. Register the Middleware: Register the TrackExecutionTime middleware in app/Http/Kernel.php:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'track.time' => \App\Http\Middleware\TrackExecutionTime::class,
];
4. Apply the Middleware to a Route: Apply the middleware in routes/web.php to a route you want to track execution time for.
Code:
php
Copy code
Route::get('/dashboard', function () {
return 'Welcome to the dashboard!';
})->middleware('track.time');
5. Testing:
o After accessing the /dashboard route, check the storage/logs/laravel.log file.
o You should see the execution time of the request logged in the file.
Assignment 8: Middleware to Ensure HTTPS
Problem Statement:
Create a middleware that ensures the request is made over HTTPS. If the request is made over HTTP, the middleware should redirect the user to the HTTPS version of the URL.
Steps to Solve:
1. Create the Middleware: Generate a new middleware called EnsureHttps:
bash
Copy code
php artisan make:middleware EnsureHttps
2. Define the Middleware Logic: In the handle() method, check if the request is using HTTPS. If not, redirect to the HTTPS version of the URL.
Code:
php
Copy code
namespace App\Http\Middleware;
use Closure;
class EnsureHttps
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check if the request is not using HTTPS
if (!$request->secure()) {
// Redirect to the HTTPS version of the URL
return redirect()->secure($request->getRequestUri());
}
// Proceed to the next middleware or controller if the request is secure
return $next($request);
}
}
3. Register the Middleware: Register the EnsureHttps middleware in app/Http/Kernel.php:
Code:
php
Copy code
protected $routeMiddleware = [
// Other middleware...
'https' => \App\Http\Middleware\EnsureHttps::class,
];
4. Apply the Middleware to Routes: In routes/web.php, apply the https middleware to routes you want to enforce HTTPS on:
Code:
php
Copy code
Route::get('/profile', function () {
return 'Secure Profile Page';
})->middleware('https');
5. Testing:
o Try accessing the /profile route with HTTP (e.g., http://your-app.test/profile).
o The middleware should automatically redirect you to the HTTPS version of the URL (e.g., https://your-app.test/profile).
Comments
Post a Comment