【发布时间】:2015-10-23 17:35:48
【问题描述】:
我正在使用 Laravel 5 开发一个 RESTful API。我的 routes.php 文件中有一些资源,并且一切正常。
但现在我添加了auth.basic 中间件,我想介绍用户角色,但我很困惑。
在我的控制器中,我有一个构造函数来调用 2 个中间件,auth.basic 和角色中间件,但由于缺乏知识而无法继续。
我需要什么?好吧,我需要设置可以访问每个控制器的用户角色,但无法做到这一点。我是Controller 我想访问用户查看他的角色并与Controller上设置的角色进行比较,但是我不知道如何访问用户,您能帮帮我吗?
编辑:
我把这个放在Controller的构造函数上
public function __construct(Request $request)
{
$actions = $request->route()->setAction( ['roles' => ['admin', 'seller', 'buyer']]);
$this->middleware('auth.basic');
$this->middleware('roles');
}
基本上,我在控制器构造函数中注入请求,然后设置一个名为角色的操作。 然后我调用中间件 auth.basic 来设置用户。 最后调用中间件角色,根据请求中的角色数组检查用户角色,如果它具有角色或者他是 root,则结果为真,否则我返回错误:
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
现在我总是遇到错误:
{"error":{"code":"INSUFFICIENT_ROLE","description":"You are not authorized to access this resource."}}
那是因为用户模型不返回角色。看我的课:
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 = ['username', 'email', 'password', 'role_id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
//Comprobacion del rol del usuario
public function hasRole($roles)
{
$this->have_role = $this->getUserRole();
// Check if the user is a root account
if($this->have_role->name == 'root') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
private function getUserRole()
{
return $this->role()->getResults();
}
private function checkIfUserHasRole($need_role)
{
return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}
//User relation with role
public function role(){
return $this->belongsTo('App\Role');
}
}
怎么了?
【问题讨论】:
标签: php rest laravel-5 restful-authentication middleware