Last active
June 30, 2022 13:41
-
-
Save dcabanaw/8baac11069921ce71f07 to your computer and use it in GitHub Desktop.
ACL in Laravel: Roles and Permissions fix for booting when scheming is not created...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Policies; | |
use Illuminate\Contracts\Auth\Access\Gate as GateContract; | |
class ApplicationPolicy | |
{ | |
/** | |
* @var GateContract | |
*/ | |
private $gate; | |
public function __construct(GateContract $gate) | |
{ | |
$this->gate = $gate; | |
} | |
public function init() | |
{ | |
// Dynamically register permissions with Laravel's Gate. | |
foreach ($this->getPermissions() as $permission) { | |
$this->gate->define($permission->name, function ($user) use ($permission) { | |
return $user->hasPermission($permission); | |
}); | |
} | |
} | |
/** | |
* Fetch the collection of site permissions. | |
* | |
* @return \Illuminate\Database\Eloquent\Collection | |
*/ | |
protected function getPermissions() | |
{ | |
return Permission::with('roles')->get(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use App\Policies\ApplicationPolicy; | |
use Closure; | |
use Illuminate\Contracts\Auth\Guard; | |
class Authenticate | |
{ | |
/** | |
* @var ApplicationPolicy | |
*/ | |
private $policy; | |
/** | |
* The Guard implementation. | |
* | |
* @var Guard | |
*/ | |
protected $auth; | |
/** | |
* Create a new filter instance. | |
* | |
* @param Guard $auth | |
* @param ApplicationPolicy $policy | |
*/ | |
public function __construct(Guard $auth, ApplicationPolicy $policy) | |
{ | |
$this->auth = $auth; | |
$this->policy = $policy; | |
} | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$this->policy->init(); | |
if ($this->auth->guest()) { | |
if ($request->ajax()) { | |
return response('Unauthorized.', 401); | |
} else { | |
return redirect()->guest('signin'); | |
} | |
} | |
elseif ($this->auth->user()->cannot('base-app')) { | |
abort(403, 'Unauthorized.'); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment