在路由上设置Laravel过滤器以防止某些用户访问某些页面

时间:2014-11-10 20:29:22

标签: php laravel

我有3个不同的用户(普通,技术人员,管理员) - 每个用户都有不同的页面可供访问,但我不希望普通用户访问技术/管理页面,反之亦然..目前如果我登录这三个用户中的任何一个,他们都可以通过url(/ users / home)中的硬编码访问普通用户页面。

**ROUTES**
    Route::get('/', 'MainController@index');
    Route::get('/user/create', 'UserController@create');
    Route::post('/user/store', 'UserController@store');
    Route::post('/user/login', 'SessionsController@login');

    Route::group(array('before' => 'auth'), function()
    {
    Route::get('/user/home' , 'UserController@userHome');
    Route::get('/tech/home', 'TechController@techHome');
    Route::get('/admin/home', 'AdminController@adminHome');
    });


**--UserController--**

 public function userHome(){

        $user = Auth::user();
        $username = $user->username;

        return "You have reached the main page for the normal user" . $username;
    }

- SESSIONSCONTROLLER -

public function login() {
        $validator = Validator::make(Input::all(), ['username' => 'required', 'password' => 'required']);
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator->messages());
        }
        $input = Input::all();
        $attempt = Auth::attempt([

                    'username' => $input['username'],
                    'password' => $input['password']
        ]);

        if ($attempt) {
            $user = Auth::user();
            $username = $user->username;
            $accountType = $user->account_type_id;
            if ($accountType == 1) {
                return View::make('normaluser')->with('username', $username);
            } elseif ($accountType == 2) {
                return View::make('technician')->with('username', $username);
            } elseif ($accountType == 3) {
                return View::make('administrator')->with('username', $username);
            }
        } else {
            return "Failed!";
        }
    }

帐户类型1 =正常,2 =科技,3 =管理员

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

Route::group(array('before' => 'auth'), function()
{
    Route::get('/user/home' , array('before' => 'user', 'uses' => 'UserController@userHome'));
    Route::get('/tech/home', array('before' => 'tech', 'uses' => 'TechController@techHome'));
    Route::get('/admin/home', array('before' => 'admin', 'uses' => 'AdminController@adminHome'));
});

Route::filter('tech',function(){
    if(!Auth::check() || Auth::user()->account_type_id != 2){
        return Redirect::to('/');
    }
});

对其他2个角色也这样做!或者你可以使用这个:

Route::when('tech/*','tech');

使用这种方法,您不必每次都指定before语句。