- Laravel Application Development Cookbook
- Terry Matula
- 273字
- 2021-07-23 15:33:35
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:
- Create a filter in our
filters.php
file that checks for logged-in users. The default Laravelauth
filter will be fine:Route::filter('auth', function() { if (Auth::guest()) return Redirect::guest('login'); });
- 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'); });
- 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>'; }));
- 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.
- 廣電5G從入門到精通
- C++黑客編程揭秘與防范
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- 計(jì)算機(jī)網(wǎng)絡(luò)安全實(shí)訓(xùn)教程(第二版)
- Building RESTful Web services with Go
- 網(wǎng)絡(luò)環(huán)境中基于用戶視角的信息質(zhì)量評(píng)價(jià)研究
- 6G無線網(wǎng)絡(luò)空口關(guān)鍵技術(shù)
- 局域網(wǎng)組成實(shí)踐
- AWS Lambda Quick Start Guide
- 物聯(lián)網(wǎng)的機(jī)遇與利用
- 智能物聯(lián)安防視頻技術(shù)基礎(chǔ)與應(yīng)用
- 互聯(lián)網(wǎng)戰(zhàn)略變革與未來
- 加密與解密實(shí)戰(zhàn)全攻略
- 物聯(lián)網(wǎng):感知、傳輸與應(yīng)用
- 網(wǎng)絡(luò)是怎樣連接的