PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-middleware. Show all posts
Showing posts with label laravel-middleware. Show all posts

Saturday, September 3, 2022

[FIXED] How to check user status while login in Laravel 5?

 September 03, 2022     authentication, laravel, laravel-middleware, middleware     No comments   

Issue

I have used Laravel Authentication (Quickstart). But I need to check the status of the user (approved/pending). If not approved, then an error will be shown in the login page. I need to know in which file I have to make the change and what is the change. Currently I am working on Laravel 5.3.


Solution

You can create a Laravel Middleware check the link for additional info

php artisan make:middleware CheckStatus

modify your middleware to get

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        //If the status is not approved redirect to login 
        if(Auth::check() && Auth::user()->status_field != 'approved'){
            Auth::logout();
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}

then add your middleware to your Kernel.php

'checkstatus' => \App\Http\Middleware\CheckStatus::class,

and finally add the middleware to your route

Route::post('/login', [
    'uses'          => 'Auth\AuthController@login',
    'middleware'    => 'checkstatus',
]);

I hope it helps



Answered By - Camilo Rojas
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 8, 2022

[FIXED] Add Multiple Middleware to Laravel Project

 March 08, 2022     eloquent, laravel, laravel-middleware, php     No comments   

Issue

I'm new to laravel I have created middleware for my each role but when I add it to my route it won't work.

If I add single middleware to my route it works fine but when I add second and third one It will not work.

It won't shows the route to authorized user it redirect it to home,

My User Model:

public function IsAdmin()
{
    if($this->role_id =='1')
    {
        return true;
    }
    else
    {
        return false;
    }
}

public function IsManager()
{
    if($this->role_id =='2')
    {
        return true;
    }
    else
    {
        return false;
    }
}

public function IsUser()
{
    if($this->role_id =='3')
    {
        return true;
    }
    else
    {
        return false;
    }
}

My Kernal:

'IsAdmin' => \App\Http\Middleware\IsAdmin::class,
'IsManager' => \App\Http\Middleware\IsManager::class,
'IsUser' => \App\Http\Middleware\IsUser::class,

My IsAdmin Middlewares:

public function handle($request, Closure $next)
{
    $user =Auth::User();
    if(!$user->IsAdmin())
    {
        return redirect('stock');
    }
    return $next($request);
}

My IsManager

public function handle($request, Closure $next)
{
    $user =Auth::User();
    if(!$user->IsManager())
    {
        return redirect('stock');
    }
    return $next($request);
}

and IsUser

public function handle($request, Closure $next)
{
    $user =Auth::User();
    if(!$user->IsUser())
    {
        return redirect('stock');
    }
    return $next($request);
}

and finally my Route

Route::get('approv',['middleware'=>['IsManager','IsAdmin'],function(){
    return view('approv');
}]);

Solution

This will not work as you'd expect. All middleware need to pass in order for the request to be processed which means that your user will need to be both a manager and an admin at the same time which based on your setup is impossible.

You can get around this (kind of) by making a different kind of middleware:

Kernel:

'roles' => \App\Http\Middleware\Roles::class,

And the Roles middleware:

class Roles {

    private function checkRole($role) {
          switch ($role) {
              case 'user': return \Auth::user()->IsUser();
              case 'manager': return \Auth::user()->IsManager();
              case 'admin': return \Auth::user()->IsAdmin();
          }
          return false;
    }

    public function handle($request, Closure $next, ...$roles) 
    {
         foreach ($roles as $role) {
             if ($this->checkRole($role)) {
                 //At least one role passes
                 return $next($request);
             }
         } 
         //All checks failed so user does not have any of the required roles
         return redirect('stock');  
    }
}

Then to use this you simply do:

Route::get('approv',['middleware'=>['roles:manager,admin'],function(){
   return view('approv');
}]);

This works because Laravel Middleware support parameters. You can pass parameters as a comma separated list of strings where you declare the middleware. In this case this was done as roles:manager,admin

Laravel will then send these parameters as additional parameters in the handle method. These can be accessed using PHPs syntax for variadic arguments. In this particular case it's by using the array spread operator. This is documented as an example in the function arguments section of the PHP manual.

Note that this is actually equivalent to saying :

  public function handle($request, Closure $next, $role1=null, $role2=null, $role3=null)

but using the spread operator is much more convenient since ...$roles would be an array which contains only the roles that were passed in the middleware.



Answered By - apokryfos
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, February 25, 2022

[FIXED] Laravel route group and middlewares

 February 25, 2022     laravel, laravel-5, laravel-middleware, php, routes     No comments   

Issue

i am working on a laravel project with users who can have status verified (email verified).

on the other hand, users can have a subscription which is verified by a "subscriptions" middleware.

So I have several groups of routes including 2 of which the only difference is the presence of subscription or not

group 1:

Route::group(['middleware' => ["auth:sanctum", "verified"]], function () {}

group 2

Route::group(['middleware' => ["auth:sanctum", "verified", "subscriptions"]], function () {}

my question is about the order laravel uses for routes in these groups. for example if the user satisfies all the middleware of the first group, does laravel test the middleware of the second? Does a user verified have a chance to enter the second group of routes with subscription?

conversely, if the user does not have a subscription, he will not pass the subscription middleware. but I have the impression that the user is redirected by the subscription middleware which fails while laravel could find the right route in the group without this middleware (group 1)

what I would like is that it just tests for the presence of a subscription and that if it does not find one it looks for the route in group1.

Does the order of the groups in the code have an impact on the processing?

thanks.

edit:

Route::group(['middleware' => ["auth:sanctum", "verified", ]], function () {
            Route::get("/new", function () {
               // redirect to payment
            })->name("new-payment");
    }


Route::group(['middleware' => ["auth:sanctum", "verified", "subscriptions"]], function () {
    Route::get("/new", function () {
        return view("bourse-new");
    })->name("new-abo");

it is the same route but with a different behavior depending on the presence or not of a subscription When subscriptions middleware fails, it's redirect to "home", but i want laravel to use the first route


Solution

thanks to @NoobDev.

I took over his solution by integrating the subscription tests into middleware

    Route::group(['middleware' => ["auth:sanctum", "verified"]], function () {
        Route::get("/new", function () {
            return view("bourse-new");    
        })->middleware("subscriptions")->name("bourse-new");
    });

and the subscriptions middleware:

    public function handle(Request $request, Closure $next){
        if( //logic tests) {
             return $next($request);
         }
         return redirect('/checkout'); //redirect to payment
    }

this solution is almost perfect, thanks everyone



Answered By - Fouvet Sébastien
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 20, 2022

[FIXED] Laravel 5 Resourceful Routes Plus Middleware

 February 20, 2022     laravel, laravel-5, laravel-middleware, laravel-routing, routes     No comments   

Issue

Is it possible to add middleware to all or some items of a resourceful route?

For example...

<?php

Route::resource('quotes', 'QuotesController');

Furthermore, if possible, I wanted to make all routes aside from index and show use the auth middleware. Or would this be something that needs to be done within the controller?


Solution

In QuotesController constructor you can then use:

$this->middleware('auth', ['except' => ['index','show']]);

Reference: Controller middleware in Laravel 5



Answered By - Marcin NabiaƂek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 10, 2022

[FIXED] Laravel middleware with multiple roles

 February 10, 2022     laravel-5.4, laravel-blade, laravel-middleware, php     No comments   

Issue

I've been running into some issues with Laravel's middleware. Let me tell you the basic idea of what I'm trying to accomplish:

Registered users on the site will have one of four roles:

  1. Student (default): can access 'index' and 'show' views
  2. Approver: can access previous, plus 'overview', 'update'
  3. Editor: can access previous, plus 'create', 'edit' and 'store'
  4. Admin: can access everything

fyi: 'overview' is sort of an index view, but only for approver role and higher

What would you guys suggest is the best way to go about doing this? This is what I've done so far, but it doesn't seem to work:


Kernel.php

protected $middlewareGroups = [
...
    'approver+' => [
        \App\Http\Middleware\Approver::class,
        \App\Http\Middleware\Editor::class,
        \App\Http\Middleware\Admin::class,
    ],
];

protected $routeMiddleware = [
...
    'student' => \App\Http\Middleware\Student::class,
    'approver' => \App\Http\Middleware\Approver::class,
    'editor' => \App\Http\Middleware\Editor::class,
    'admin' => \App\Http\Middleware\Admin::class,
];

Http\Middleware\Admin.php

public function handle($request, Closure $next)
{
   if (Auth::check())
   {

        if(Auth::user()->isAdmin())
        {
            return $next($request);
        }
   }

    return redirect('login');
}

The 'User' Eloquent model:

public function isAdmin()
{
    if($this->role_id === 4)
    { 
        return true; 
    } 
    else 
    { 
        return false; 
    }
}

I've done the exact same in the Approver and Editor middleware files, and in the isApprover and isEditor functions in the User model, only edited the checked value in the if-statement to 2 and 3 respectively.

Finally, here's what I've done in my routes\web file:

Route::get('scholen', 'SchoolsController@index');
Route::get('admin/scholen/overzicht', 'SchoolsController@overview')->middleware('approver+');
Route::get('admin/scholen/maken', 'SchoolsController@create')->middleware('approver+');
Route::post('scholen', 'SchoolsController@store')->middleware('approver+');
Route::get('scholen/{id}', 'SchoolsController@show');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController@edit')->middleware('admin');
Route::patch('admin/scholen/{id}', 'SchoolsController@update')->middleware('admin');
Route::delete('admin/scholen/{id}', 'SchoolsController@destroy')->middleware('admin');

It isn't all exactly on point yet, but I got stuck since when I log in as a user with Approver rights and try to access the schools overview, it redirects me back to the home page.

In general, it just feels like I'm working much too chaotically and not right at all, could somebody give me advice on how to do it more efficiently?

Thank you very much in advance!


Solution

You should't have a separate middleware for each role. It will get very messy very fast. It would be better to have a single role checking middleware that can check against any role passed to it.

Http\Kernel.php

protected $routeMiddleware = [
    ...
    'role' => \App\Http\Middleware\Role::class,
];

Http\Middleware\Role.php

public function handle($request, Closure $next, ... $roles)
{
    if (!Auth::check()) // I included this check because you have it, but it really should be part of your 'auth' middleware, most likely added as part of a route group.
        return redirect('login');

    $user = Auth::user();

    if($user->isAdmin())
        return $next($request);

    foreach($roles as $role) {
        // Check if user has the role This check will depend on how your roles are set up
        if($user->hasRole($role))
            return $next($request);
    }

    return redirect('login');
}

Finally in your web routes

Route::get('admin/scholen/overzicht', 'SchoolsController@overview')->middleware('role:editor,approver');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController@edit')->middleware('role:admin');


Answered By - jfadich
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 28, 2022

[FIXED] How to Solve Facade\Ignition\Http\Middleware\IgnitionEnabled?

 January 28, 2022     eloquent, laravel, laravel-middleware     No comments   

Issue

----------------------------------------------------------------------------------+
| Domain | Method   | URI                        | Name             | Action                                                                 | Middleware
                                                                                  |
+--------+----------+----------------------------+------------------+------------------------------------------------------------------------+--------------------------------------------------
----------------------------------------------------------------------------------+
|        | GET|HEAD | /                          |                  | Closure                                                                | web
                                                                                  |
|        | POST     | _ignition/execute-solution |                  | Facade\Ignition\Http\Controllers\ExecuteSolutionController             | Facade\Ignition\Http\Middleware\IgnitionEnabled,F
acade\Ignition\Http\Middleware\IgnitionConfigValueEnabled:enableRunnableSolutions |
|        | GET|HEAD | _ignition/health-check     |                  | Facade\Ignition\Http\Controllers\HealthCheckController                 | Facade\Ignition\Http\Middleware\IgnitionEnabled
                                                                                  |
|        | GET|HEAD | _ignition/scripts/{script} |                  | Facade\Ignition\Http\Controllers\ScriptController                      | Facade\Ignition\Http\Middleware\IgnitionEnabled
                                                                                  |
|        | POST     | _ignition/share-report     |                  | Facade\Ignition\Http\Controllers\ShareReportController                 | Facade\Ignition\Http\Middleware\IgnitionEnabled,F
acade\Ignition\Http\Middleware\IgnitionConfigValueEnabled:enableShareButton       |
|        | GET|HEAD | _ignition/styles/{style}   |                  | Facade\Ignition\Http\Controllers\StyleController                       | Facade\Ignition\Http\Middleware\IgnitionEnabled

Solution

It's not a problem to solve, these are the routes of the new debugging package for Laravel 6 called Facade/Ignition

They are required so Laravel can show you errors when they occur

So just ignore them

However, if you want to remove these routes (which is not recommended), you can remove this line from composer.json

 "require-dev": {
        "facade/ignition": "^1.4", <--- Remove this one
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^8.0"
    },

And run

composer update

But then you wouldn't see custom error pages but the default PHP7 errors table and stack trace.

You can still get the old package filp/whoops by installing it

composer require filp/whoops


Answered By - Salim Djerbouh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 8, 2022

[FIXED] How to overwrite parameters of a Laravel middleware which already is assigned as a group middleware?

 January 08, 2022     laravel, laravel-8, laravel-middleware, php, url-routing     No comments   

Issue

I have a Laravel middleware which accepts parameters. This middleware is assigned to a group of routes on the group level. I need to overwrite the parameters specifically for a single route inside this group. How do I do this?

If I add ->middleware('my_middleware:new_param') to the specific route, then the middleware is executed twice: first with the default parameters from the group level, second with the new parameter.

If I add ->withoutMiddleware('my_middleware')->middleware('my_middleware:new_param') then the middleware is not executed at all.

Example

\App\Http\Kernel:

class Kernel extends HttpKernel {
  protected $middleware = [
    ...
  ];

  protected $middlewareGroups = [
    'my_middleware_group' => [
      'my_middlware:default_param',
      ...,
    ],
  ];

  protected $routeMiddleware = [
    'my_middlware' => \App\Http\Middleware\MyMiddleware::class,
    ...
  ];
}

\App\Providers\RouteServiceProvider:

class RouteServiceProvider extends ServiceProvider {
  public function boot() {
    $this->routes(function () {
      Route::middleware('my_middleware_group')
        ->group(base_path('routes/my_routing_group.php'));
    });
  }
}

routes/my_routing_group.php:

// Neither the following line
Route::get('/my-url', [MyController::class, 'getSomething'])->middleware(['my_middlware:new_param']);
// nor this line works as expected
Route::get('/my-url', [MyController::class, 'getSomething'])->withoutMiddleware('my_middleware')->middleware(['my_middlware:new_param']);

Solution

The answer is simple: One must also repeat the exact parameters in ->withoutMiddleware which one want not to use. This means

routes/my_routing_group.php:

Route::get('/my-url', [MyController::class, 'getSomething'])
  ->withoutMiddleware(['my_middlware:default_param'])   // the original parameters must be repeated, too
  ->middleware(['my_middlware:new_param']);

does the trick.



Answered By - user2690527
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing