0

对 Laravel 3 来说仍然很新,并且正在解决一些问题。

我正在尝试设置基于角色的页面访问权限。用户目前能够登录并且该部分运行良好,但我想根据用户角色(例如管理员、编辑器等)限制对某些页面的访问。

因此,我创建了一个过滤器,如下所示:

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);
    }
    }
}

这是基于我找到的教程https://gist.github.com/anchetaWern/4223764

我的想法取决于用户访问级别,即用户对象中的“级别”,我将过滤页面等。

但是,我收到与此代码有关的错误“尝试获取非对象的属性”:

if(Auth::user()->level < 4) {

在视图中测试 Auth::user()->level 确认用户已登录。谁能告诉为什么这在 routes.php 中作为过滤器不起作用?

谢谢

4

1 回答 1

1

问题已解决 - 我在我的脚本中使用了不正确的语法,我在此处发布后意识到这一点。

if($user_level = Auth::user()->level < 4) {

应该:

if(Auth::user()->level < 4) {

过滤器现在工作。但是我正在寻找改进的方法,因为不确定这是现在最有效的方法!

谢谢

于 2013-06-05T06:25:30.193 回答