问题
I am wondering how I can restrict access to certain routes in the routes.php
file when using Sentry
. Currently I have the following routes set up
Route::model('book', 'Book');
Route::get('/books', 'BookController@index');
Route::get('book/create', 'BookController@create');
Route::get('book/edit/{book}', 'BookController@edit');
Route::get('book/delete/{book}', 'BookController@delete');
Route::get('book/view/{book}', 'BookController@view');
Route::post('book/create', 'BookController@handleCreate');
Route::post('book/edit', 'BookController@handleEdit');
Route::post('book/delete', 'BookController@handleDelete');
I have 2 groups
- Admin
- User
I would only like the Admin
to be able to access these routes. I'd appreciate any help
回答1:
Taken from http://laravelsnippets.com/snippets/sentry-route-filters and modified for your propose. Hope this helps. I implemented something similar to this recently.
Youll need to replace the routes in the failure redirects to your own though.
<?php
/**
* Sentry filter
*
* Checks if the user is logged in
*/
Route::filter('Sentry', function()
{
if ( ! Sentry::check()) {
return Redirect::route('cms.login');
}
});
/**
* hasAcces filter (permissions)
*
* Check if the user has permission (group/user)
*/
Route::filter('hasAccess', function($route, $request, $value)
{
try
{
$user = Sentry::getUser();
if( ! $user->hasAccess($value))
{
return Redirect::route('cms.login')->withErrors(array(Lang::get('user.noaccess')));
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
return Redirect::route('cms.login')->withErrors(array(Lang::get('user.notfound')));
}
});
/**
* InGroup filter
*
* Check if the user belongs to a group
*/
Route::filter('inGroup', function($route, $request, $value)
{
try
{
$user = Sentry::getUser();
$group = Sentry::findGroupByName($value);
if( ! $user->inGroup($group))
{
return Redirect::route('cms.login')->withErrors(array(Lang::get('user.noaccess')));
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
return Redirect::route('cms.login')->withErrors(array(Lang::get('user.notfound')));
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
return Redirect::route('cms.login')->withErrors(array(Lang::get('group.notfound')));
}
});
//Example use
Route::group(array('before' => 'Sentry|inGroup:Admin'), function()
{
Route::model('book', 'Book');
Route::get('/books', 'BookController@index');
Route::get('book/create', 'BookController@create');
Route::get('book/edit/{book}', 'BookController@edit');
Route::get('book/delete/{book}', 'BookController@delete');
Route::get('book/view/{book}', 'BookController@view');
Route::post('book/create', 'BookController@handleCreate');
Route::post('book/edit', 'BookController@handleEdit');
Route::post('book/delete', 'BookController@handleDelete');
});
来源:https://stackoverflow.com/questions/25383316/controlling-access-to-routes-laravel-and-sentry