Created
April 1, 2014 04:00
-
-
Save anaxamaxan/9907466 to your computer and use it in GitHub Desktop.
args in a Laravel 4 auth filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// in my controller constructor, I apply a filter with arguments: | |
$this->beforeFilter('auth.hasRole:admin,staff,developer', ['except' => 'getLogoutas',]); | |
// in my global filters.php | |
/** | |
* Verify that the logged-in user has a specified role | |
*/ | |
Route::filter('auth.hasRole', function($route, $request, $value) | |
{ | |
if (! Auth::check() OR ! Auth::user()->hasRole($value)) { | |
return Response::json(['flash' => __('application.access_denied'),],403); | |
} | |
}); | |
// in User.php model (this could easily be a trait or abstracted to a service) | |
public function hasRole($key) | |
{ | |
return $this->hasAnyRole(explode(',',$key)); | |
} | |
public function hasAnyRole($keys) | |
{ | |
if( ! is_array($keys)) | |
{ | |
$keys = func_get_args(); | |
} | |
foreach($this->roles as $role) | |
{ | |
if(in_array($role->keyname, $keys)) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment