- 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從入門到精通
- Mastering Node.js(Second Edition)
- 黑客攻防實戰(zhàn)技術(shù)完全手冊:掃描、嗅探、入侵與防御
- Cisco OSPF命令與配置手冊
- 物聯(lián)網(wǎng)(IoT)基礎(chǔ):網(wǎng)絡(luò)技術(shù)+協(xié)議+用例
- JBoss EAP6 High Availability
- 新一代物聯(lián)網(wǎng)架構(gòu)技術(shù):分層算力網(wǎng)絡(luò)
- 互聯(lián)網(wǎng)安全的40個智慧洞見:2015年中國互聯(lián)網(wǎng)安全大會文集
- 大話社交網(wǎng)絡(luò)
- Microservice Patterns and Best Practices
- 5G技術(shù)與標(biāo)準(zhǔn)
- 信息技術(shù)安全評估準(zhǔn)則:源流、方法與實踐
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計算融合應(yīng)用詳解
- Microservices Development Cookbook
- Architecting Data:Intensive Applications