所以我试图了解Laravel 5.1中的用户授权。
基于docs,我按如下方式设置了AuthServiceProvider启动方法:
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
$gate->define('view-dashboard', function ($user, $post) {
return $user->id === $post->user_id;
});
$gate->before(function ($user, $ability) {
if($user->isSuperAdmin()) {
return true;
}
});
}
在我的控制器中我有:
if (Gate::denies('view-dashboard')) {
return view('auth.login');
}
return view('admin.home');
当我没有登录时,我会获得auth.login视图。但是,一旦我登录,我收到以下错误:
Builder.php第2025行中的BadMethodCallException:调用undefined 方法Illuminate \ Database \ Query \ Builder :: isSuperAdmin()
首先,由于我直接从文档中删除了这些内容,因此我不确定为什么会出现该错误。有什么想法吗?
其次,文档似乎没有解释如何将给定用户指定为超级管理员,或者如何为用户提供特定能力(例如我的示例中的“视图 - 仪表板”功能)。我该怎么做?
更新:这是我的用户模型:
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
}
答案 0 :(得分:5)
在您的模型用户中,您没有定义方法 isSuperAdmin
public function isSuperAdmin()
{
// your logic here
return true; // or false
}
答案 1 :(得分:4)
检查AuthServiceProvider的行:
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
默认我的文件有:
use Illuminate\Support\ServiceProvider;
替换所有工作正常后
答案 2 :(得分:0)
看起来可能没有定义Super Admin midwhere。
在app/Http/Kernel.php
中,您会看到名为routeMiddleware
的指令。在数组中添加以下行。
'superadmin' => 'App\Http\Middleware\SuperAdminMiddleware'
您也没有提供User
型号。请您仔细检查User
模型是否至少实现了以下接口和特征。
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}