官术网_书友最值得收藏!

Restricting access to certain pages

In this recipe, we'll explore how to restrict access to various pages in our app. This way, we can make pages viewable to only those with the correct credentials.

Getting ready

We will be using the code created in the Setting up and configuring the Auth library and Creating an authentication system recipes as the basis for this recipe.

How to do it...

To complete this recipe, follow these steps:

  1. Create a filter in our filters.php file that checks for logged-in users. The default Laravel auth filter will be fine:
    Route::filter('auth', function()
    {
        if (Auth::guest()) return Redirect::guest('login');
    });
  2. Create a filter in filter.php for checking if a user is an admin:
    Route::filter('auth_admin', function()
    {
        if (Auth::guest()) return Redirect::guest('login');
        if (Auth::user()->admin != TRUE)
            return Redirect::to('restricted');
    });
  3. Make a route that we restrict to logged-in users:
    Route::get('restricted', array('before' => 'auth',
        function()
    {
        return 'This page is restricted to logged-in users!
            <a href="admin">Admins Click Here.</a>';
    }));
  4. Make a route that is restricted to admins:
    Route::get('admin', array('before' => 'auth_admin',function()
    {
        return 'This page is restricted to Admins only!';
    }));

How it works...

Filters are a powerful part of Laravel and can be used to simplify many tasks. The default auth filter that comes with Laravel simply checks if a user is logged in or not and, if not, redirects him/her to the login page. In our restricted route, we add the auth filter to run before the function is executed.

Our auth_admin filter checks to make sure the user is logged in and also checks if the user is set as admin. If not, he/she is redirected back to the normal restricted page.

主站蜘蛛池模板: 长垣县| 资兴市| 云霄县| 琼结县| 五家渠市| 北流市| 万山特区| 马尔康县| 苍溪县| 邳州市| 疏附县| 渭南市| 泽库县| 玉门市| 东乌珠穆沁旗| 宣恩县| 许昌县| 阿合奇县| 奉节县| 中阳县| 洛川县| 宁波市| 唐山市| 云安县| 凤城市| 六盘水市| 蓬莱市| 宁城县| 体育| 霍州市| 刚察县| 同心县| 七台河市| 桂东县| 鹰潭市| 祥云县| 合水县| 太仓市| 东乌| 池州市| 平原县|