Skip to content

Commit

Permalink
Handle model instance in Authorize middleware.
Browse files Browse the repository at this point in the history
This will help extending Middleware capabilities by giving it directly the Model to check.

Implementation example :

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Middleware\Authorize;

class AuthorizeCommand extends Authorize
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $ability = null, ...$models)
    {
        if ((null !== $command = $request->route('command')) &&
            $command instanceof Model
        ) {
            return parent::handle($request, $next, 'access', $command);
        }

        return $next($request);
    }
}
```
  • Loading branch information
shulard committed Feb 12, 2017
1 parent 01aeaa8 commit 89b296b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Illuminate/Auth/Middleware/Authorize.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authorize
Expand Down Expand Up @@ -70,7 +71,9 @@ protected function getGateArguments($request, $models)
}

return collect($models)->map(function ($model) use ($request) {
return $this->getModel($request, $model);
return $model instanceof Model
?$model
:$this->getModel($request, $model);
})->all();
}

Expand Down
22 changes: 22 additions & 0 deletions tests/Auth/AuthorizeMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,28 @@ public function testModelAuthorized()
$this->assertEquals($response->content(), 'success');
}

public function testModelInstanceAsParameter()
{
$instance = m::mock(\Illuminate\Database\Eloquent\Model::class);

$this->gate()->define('success', function ($user, $model) use ($instance) {
$this->assertSame($model, $instance);

return true;
});

$request = m::mock(Request::class);

$nextParam = null;

$next = function ($param) use (&$nextParam) {
$nextParam = $param;
};

(new Authorize($this->container->make(Auth::class), $this->gate()))
->handle($request, $next, 'success', $instance);
}

/**
* Get the Gate instance from the container.
*
Expand Down

0 comments on commit 89b296b

Please sign in to comment.