Skip to content

Instantly share code, notes, and snippets.

@samuelcar
Created July 4, 2014 10:02
Show Gist options
  • Select an option

  • Save samuelcar/54b390e5fea922550bd8 to your computer and use it in GitHub Desktop.

Select an option

Save samuelcar/54b390e5fea922550bd8 to your computer and use it in GitHub Desktop.
Route filters for Login, inGroup and hasAccess using sentry on laravel (taken from laravel snippets)
/**
* 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('prefix' => 'cms/product', 'before' => 'Sentry|inGroup:Admins'), function()
{
Route::get('/', array(
'as' => 'product.index',
'before' => 'hasAccess:product.index',
'uses' => 'ProductController@index'
));
});
- See more at: http://laravelsnippets.com/snippets/sentry-route-filters#sthash.VR0AIbC0.dpuf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment