Reputation: 3060
Still very new to Laravel 3 and working through some issues.
I'm trying to set up a role based access to page. Users are currently able to log in and that part works well but I want to restrict access to certain pages based on the users role eg admin, editor etc.
So, I've created a filter as follows:
Route::filter('check_roles', function () {
$current_url = URI::current(); //get current url excluding the domain.
$current_page = URI::segment(2); //get current page which is stored in the second uri segment. Just a refresher: //the first uri segment is the controller, the second is the method,
//third and up are the parameters that you wish to pass in
$access = 0;
$counter = 1;
//excluded pages are the pages we don't want to execute this filter
//since they should always be accessible for a logged in user
$excluded_pages = array(
'base' => array('login', 'user/authenticate'),
1 => array('user/profile', 'dashboard','dashboard/index','articles','articles/index', 'articles/create', 'articles/preview', 'articles/edit', 'user/profile', 'user/logout'),
2 => array('articles/publish','user/create', 'user/edit'),
3 => array('user/delete')
);
if (!in_array($current_url, $excluded_pages['base']) ) { //if current page is not an excluded pages
if(Auth::user()->level < 4) {
do {
if (in_array($current_url, $excluded_pages[$counter])) {
$access=1;
}
$counter++;
} while ($counter < $user_level AND $counter < 4);
if ($access == 0) { //if user doesn't have access to the page that he's trying to access
//redirect the user to the homepage
return Redirect::to('dashboard')
->with('error', 'You don\'t have permission to access the following page: ' . $current_url);
}
}
}
This is based on tutorial I found https://gist.github.com/anchetaWern/4223764
My thoughts were depending on user access level which is 'level' in the user object I'd filter the pages etc.
However I'm getting an error 'Trying to get property of non-object' this relates to this code:
if(Auth::user()->level < 4) {
testing Auth::user()->level in a view confirms the user is logged in. Can anyone advise why this doesnt work in the routes.php as a filter?
Thank you
Upvotes: 0
Views: 1407
Reputation: 3060
Problem solved - I was using the incorrect syntax in my script which I realised once I posted here.
if($user_level = Auth::user()->level < 4) {
Should be:
if(Auth::user()->level < 4) {
Filter works now. However I'm looking at ways to improve as not sure this is the most efficient way now!
Thanks
Upvotes: 1