Friday, 16 June 2023

Laravel logout user if role changed by admin in active session of user

1) Create a new middleware that will check if the user's role has been changed and log them out if necessary. Run the following command to generate the middleware:

php artisan make:middleware CheckUserRole

2)Open the generated middleware file (app/Http/Middleware/CheckUserRole.php) and implement the handle method. The method should compare the user's current role with the role stored in the session. If they don't match, log out the user. Here's an example implementation:

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class CheckUserRole { public function handle($request, Closure $next) { if (Auth::check()) { $user = Auth::user(); // Check if the user's role has changed if ($user->role !== session('role')) { Auth::logout(); return redirect('/login')->with('message', 'Your role has been changed. Please log in again.'); } } return $next($request); } }

3) Register the middleware in the $routeMiddleware array of the app/Http/Kernel.php file. Add the following line to the array:

'role.check' => \App\Http\Middleware\CheckUserRole::class,

4)Apply the middleware to the relevant routes or route groups. For example, you can apply it to the routes that handle role changes:

Route::middleware('role.check')->group(function () { // Routes for changing user roles });

5)When an admin changes a user's role, update the user's role and update the role value stored in the user's session. You can accomplish this in your controller or wherever you handle the role change logic. Here's an example:

// Update the user's role $user->role = 'new_role'; $user->save(); // Update the role value in the session session(['role' => 'new_role']);

6) Open the RegisterController located at app/Http/Controllers/Auth/RegisterController.php.

Inside the create method, after the line that creates a new user, add the following code to set the user's role in the session:

// Create a new user $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); // Set the user's role in the session session(['role' => $user->role]);

7)Next, open the LoginController located at app/Http/Controllers/Auth/LoginController.php.

Inside the authenticated method, after the line that logs in the user, add the following code to set the user's role in the session:
Note: (authenticated method not present by default we need to create it.)

use Illuminate\Http\Request;

protected function authenticated(Request $request, $user) { // Log in the user // Set the user's role in the session session(['role' => $user->role]); // Redirect the user return redirect()->intended($this->redirectPath()); }


No comments:

Post a Comment

Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...