edvinaskrucas / rbauth
Requires
- php: >=5.3.0
- illuminate/auth: 4.0.x
- illuminate/config: 4.0.x
- illuminate/support: 4.0.x
This package is auto-updated.
Last update: 2024-09-11 13:53:22 UTC
README
一个基于角色/权限的 Laravel4 认证包
- 角色
- 权限
- 异常
- 路由过滤器
安装
只需通过 composer.json 将新包添加到您的 Laravel 安装中
"edvinaskrucas/rbauth": "dev-master"
然后执行 composer update
,更新后,通过执行 php artisan migrate --package=edvinaskrucas/rbauth
迁移 rbauth 包
在 Laravel 中注册它
将以下行添加到 app/config/app.php
服务提供者数组
'Krucas\RBAuth\RBAuthServiceProvider'
在 app/config/auth.php
中将认证驱动程序更改为 rbauth
现在您可以使用 Laravel4 了。
配置
如果您想使用自己实现的接口,需要通过执行 php artisan config:publish edvinaskrucas/rbauth
发布包配置文件。现在您可以在 app/config/packages/edvinaskrucas/rbauth/
文件中更改默认实现
用法
基本示例
包括示例 RoleInterface 和 RoleProviderInterface 实现,但用户必须实现方法 can($identifier)
登录用户
$input = Input::all(); try { Auth::attempt( array( 'email' => $input['email'], 'password' => $input['password'] ), isset($input['reminder']) ); return Redirect::back(); // All is ok } catch(UserNotFoundException $e) { // User not found } catch(UserPasswordIncorrectException $e) { // Password incorrect }
确定已登录用户是否在某个角色中
返回布尔值 true
(如果有分配角色)或 false
(如果没有分配角色)
Auth::is('admin');
确定已登录用户是否有访问资源的权限
返回布尔值 true
(如果有)或 false
(如果没有)
Auth::can('view.profile');
通过您的自定义检查扩展认证
有时您需要检查特定对象的几个规则,您可以通过添加自定义检查轻松做到这一点。此示例显示如何检查复合权限。例如,您有两个编辑旅行的权限:trips.edit.all
和 trips.edit.own
,您可以通过简单调用在特定旅行上进行双重检查,或者您可以使用以下示例。
Auth::rule('trips.edit', function($trip) { if(Auth::can('trips.edit.all')) { return true; } elseif(Auth::can('trips.edit.own') && $trip->user_id == Auth::user()->id) { return true; } return false; });
现在您可以简单地通过新的规则调用方法 can
if(Auth::can('trips.edit', $trip)) { echo 'ok'; }
路由过滤器
该包包含几个路由过滤器,一个用于使用 can
进行简单检查,另一个用于您的自定义检查 customCan:canEditTrip
简单示例
Route::get('test', array('before' => 'can:test', function() { echo 'I can test!'; }));
现在让我们尝试使用一些我们的自定义 "can's"(能够)
首先我们需要将一些模型绑定到我们的路由上
Route::bind('trip', function($value, $route) { return Trip::find($value); })
现在我们可以在路由中访问我们的旅行对象。
Route::get('trips/edit/{trip}', array('before' => 'can:trips.edit,trip', function($trip) { echo 'I can edit this trip!'; }));
所以自定义路由权限检查的结构是
cam:trips.edit,trip trips.edit - your rule name trip - and other parameters are optional, this is usefull if you need to pass object to a custom check. In this case (route filter) trip will be resolved from Route object, thats why we need to bind it. When checking this in a controller or a view you can simply call it by "Auth::can('trips.edit', $trip)"
异常
此认证扩展在您尝试登录时抛出两个异常
\Krucas\RBAuth\UserNotFoundException
- 当您尝试使用不存在的用户登录时抛出。 \Krucas\RBAuth\PasswordIncorrectException
- 当用户密码不正确时抛出。
默认实现功能
- 用户可以被分配到多个角色
- 角色可以分配访问权限(启用/禁用状态的权限)
- 用户可以分配访问权限(启用/禁用状态的权限)