Laravel 5.2 部分用户的锁控制器
Laravel 5.2 lock controller for some users
我想为所有用户锁定 AccountsController 对于管理员用户..
For Exampe:
Auth::user() -> roll != 'Admin'
然后关闭 AccountsController..
AccountsController 构造代码:
public function __construct()
{
$this->middleware('auth');
}
Middleware is a completely valid solution for this, but I have switched to Gates 这种情况。 Gate使用起来更方便一些。我使用角色和权限以及 hasRole
方法来管理访问级别,但如果您的系统很简单,您可以轻松地在 User
模型上使用 isAdmin
方法来检查标志在数据库中。
中间件
创建您的自定义中间件。
AuthenticateAdmin.php
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next)
{
if ($this->auth->user()->hasRole('admin'))
{
return $next($request);
}
}
}
将其添加到您的内核。
Kernel.php
protected $routeMiddleware = [
'auth' => Middleware\Authenticate::class,
'auth.admin' => Middleware\AuthenticateAdmin::class,
];
然后你就可以在你的控制器中使用中间件了。
public function __construct()
{
$this->middleware('auth.admin');
}
大门
使用 Gate,您可以在 AuthServiceProvider 中定义策略
AuthServiceProvider.php
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
$gate->define('user-admin', function($user){
return $user->hasRole('admin');
});
}
然后将它添加到您的控制器或任何您需要的地方。
Controller.php
public function show($slug)
{
if (Gate::allows('user-admin')){
return $yes;
}
return $no;
}
我想为所有用户锁定 AccountsController 对于管理员用户..
For Exampe:
Auth::user() -> roll != 'Admin'
然后关闭 AccountsController..
AccountsController 构造代码:
public function __construct()
{
$this->middleware('auth');
}
Middleware is a completely valid solution for this, but I have switched to Gates 这种情况。 Gate使用起来更方便一些。我使用角色和权限以及 hasRole
方法来管理访问级别,但如果您的系统很简单,您可以轻松地在 User
模型上使用 isAdmin
方法来检查标志在数据库中。
中间件
创建您的自定义中间件。
AuthenticateAdmin.php
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next)
{
if ($this->auth->user()->hasRole('admin'))
{
return $next($request);
}
}
}
将其添加到您的内核。
Kernel.php
protected $routeMiddleware = [
'auth' => Middleware\Authenticate::class,
'auth.admin' => Middleware\AuthenticateAdmin::class,
];
然后你就可以在你的控制器中使用中间件了。
public function __construct()
{
$this->middleware('auth.admin');
}
大门
使用 Gate,您可以在 AuthServiceProvider 中定义策略
AuthServiceProvider.php
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
$gate->define('user-admin', function($user){
return $user->hasRole('admin');
});
}
然后将它添加到您的控制器或任何您需要的地方。
Controller.php
public function show($slug)
{
if (Gate::allows('user-admin')){
return $yes;
}
return $no;
}