SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
OH MY!
LARAVEL 5.2
GATES, AUTHSERVICEPROVIDERS AND
POLICIES
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
WHOAMI
▸ Alison Gianotto (aka “snipe”, aka @snipeyhead)
▸ One of the original members of SDPHP ;)
▸ Working with PHP for 15+ years
▸ CTO/Co-Founder of AnySha.re
▸ Founder of Grokability, Inc.
▸ Creator of Snipe-IT and other internet things
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
PROBLEMS THE AUTHSERVICEPROVIDER SOLVES
▸ Much cleaner syntax in blades (@can and @cannot)
▸ One unified place to keep authorization rules
▸ Assumes a user instance. If no user available, it fails to false
▸ Can handle basic authorization (“does the user own this
thing?”) or much more sophisticated rules based off your
model methods.
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP
public	function	boot(GateContract	$gate)	
{	
				$this->registerPolicies($gate);	
				//	--------------------------------	
				//	BEFORE	ANYTHING	ELSE	
				//	--------------------------------	
			$gate->before(function	($user,	$ability)	{	
								if	($user->superadmin=='1')	{	
												return	true;	
								}	
				});
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
SCENARIO: USER COMMUNITY WEBSITE
▸ users table
▸ communities table with user_id for creator
▸ communities_users pivot table
▸ boolean is_admin
▸ entries table with created_by for creator
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
SCENARIO: USER COMMUNITY WEBSITE: USERS
▸ Users CAN update their own posts
▸ Users CAN delete their own posts
▸ Users CANNOT update other users’ posts
▸ Uses CAN see other posts in a community
▸ … (etc)
▸ Users CAN message other users if they are not blocked
▸ Users CANNOT messages other users if they are blocked
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP
//	Check	if	the	user	can	update	an	entry	
$gate->define('update-entry',	function	($user,	$entry)	{	
				return	$user->id	===	$entry->created_by;	
});
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/USER.PHP (USER MODEL)
/**	
*	Checks	if	a	user	is	a	member	of	a	community	
*	
*	@param	Community	$community	
*	@return	boolean	
*/	
public	function	isMemberOfCommunity($community)	
{	
return	$this->communities()

												->where('community_id',	'=',	$community->id)	
												->count()	>	0;	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/HTTP/ENTRIESCONTROLLER.PHP (VIA GATE FACADE)
public	function	getEdit(Request	$request,	$id)	
{	
				if	($entry	=	Entry::find($id))	{	
								if	(Gate::denies('update-entry',	$entry))	{	
												//	You	can	return	a	403	or	whatever	you	want	here	
												abort(403);	
								}	
								return	view('entries.edit');	
				}	
				return	redirect()->back()->with('error',	'Invalid	entry.');	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/HTTP/ENTRIESCONTROLLER.PHP (VIA USER MODEL)
public	function	getEdit(Request	$request,	$id)	
{	
				if	($entry	=	Entry::find($id))	{	
								if	($request->user()->cannot('update-entry',	$entry))	{	
												//	You	could	return	a	403	response	here,	etc.	
												abort(403);	
								}	
								return	view('entries.edit');	
				}	
				return	redirect()->back()->with('error',	'Invalid	entry.');	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
RESOURCES/VIEWS/ENTRIES/VIEW.BLADE.PHP
@can('update-entry',	$entry)	
				<a	href="{{	route('entry.edit.form',	$entry->id)	}}">Edit</a>	
@endcan
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/HTTP/ENTRIESCONTROLLER.PHP (VIA FORM REQUEST)
/**	
	*	Determine	if	the	user	is	authorized	to	make	this	request.	
	*	
	*	@return	bool	
	*/	
public	function	authorize()	
{	
				$entryId	=	$this->route('entry');	
				return	Gate::allows('update',	Entry::findOrFail($entryId));	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
SCENARIO: USER COMMUNITY WEBSITE: COMMUNITY ADMINS
▸ Community admins CAN edit their own community
settings
▸ … (etc)
▸ Community admins CAN update user posts
▸ Community admins CAN add/remove users from
community
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/USER.PHP (USER MODEL)
/**	
*	Returns	whether	or	not	the	user	is	an	admin	of	a	community	
*	
*	@param	object	$community	
*	@return	boolean	
*/	
public	function	isAdminOfCommunity($community)	
{	
				return	$this->communities()	
																->where('community_id',	'=',	$community->id)	
																->where('is_admin',	'=',	'1')	
																->count()	>	0;	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP
//	Check	if	the	user	can	join	a	community	
//	(they	are	not	already	a	member)	
$gate->define('join-community',	function	($user,	$community)	{	
				if	(!$user->isMemberOfCommunity($community))	{	
								return	true;	
				}	
});	
//	Check	if	the	user	can	update	the	community	settings	
//	(they	are	an	admin)	
$gate->define('update-community',	function	($user,	$community)	{	
				if	($user->isAdminOfCommunity($community)	)	{	
								return	true;	
				}	
});
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
THIS COULD GET OUT OF HAND QUICKLY.
ENTER POLICIES.
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
CREATING A POLICY
>	php	artisan	make:policy	EntryPolicy	
Policy	created	successfully.	
>	php	artisan	make:policy	CommunityPolicy	
Policy	created	successfully.
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/POLICIES/ENTRYPOLICY.PHP
<?php	
namespace	AppPolicies;	
use	AppUser;	
use	AppEntry;	
use	IlluminateAuthAccessHandlesAuthorization;	
class	EntryPolicy	
{	
				use	HandlesAuthorization;	
				public	function	update(User	$user,	Entry	$entry)	
				{	
								return	$user->id	===	$entry->created_by;	
				}	
				public	function	delete(User	$user,	Entry	$entry)	
				{	
								//	etc	
				}	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/POLICIES/COMMUNITYPOLICY.PHP
<?php	
namespace	AppPolicies;	
use	AppUser;	
use	AppCommunity;	
use	IlluminateAuthAccessHandlesAuthorization;	
class	CommunityPolicy	
{	
				use	HandlesAuthorization;	
				public	function	update(User	$user,	Community	$community)	
				{	
								return	$user->id	===	$community->created_by;	
				}	
				public	function	delete(User	$user,	Community	$community)	
				{	
								//	etc	
				}	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP
<?php	
namespace	AppProviders;	
use	AppPoliciesEntryPolicy;	
use	AppPoliciesCommunityPolicy;	
use	IlluminateContractsAuthAccessGate	as	GateContract;	
use	IlluminateFoundationSupportProvidersAuthServiceProvider	as	ServiceProvider;	
class	AuthServiceProvider	extends	ServiceProvider	
{	
				protected	$policies	=	[	
									Entry::class	=>	EntryPolicy::class,	
									Community::class	=>	CommunityPolicy::class,	
				];	
				/**	
					*	Register	any	application	authentication	/	authorization	services.	
					*	
					*	@param		IlluminateContractsAuthAccessGate		$gate	
					*	@return	void	
					*/	
				public	function	boot(GateContract	$gate)	
				{	
								$this->registerPolicies($gate);	
				}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP
<?php	
namespace	AppProviders;	
use	AppPoliciesEntryPolicy;	
use	AppPoliciesCommunityPolicy;	
use	IlluminateContractsAuthAccessGate	as	GateContract;	
use	IlluminateFoundationSupportProvidersAuthServiceProvider	as	ServiceProvider;	
class	AuthServiceProvider	extends	ServiceProvider	
{	
				protected	$policies	=	[	
									Entry::class	=>	EntryPolicy::class,	
									Community::class	=>	CommunityPolicy::class,	
				];	
				/**	
					*	Register	any	application	authentication	/	authorization	services.	
					*	
					*	@param		IlluminateContractsAuthAccessGate		$gate	
					*	@return	void	
					*/	
				public	function	boot(GateContract	$gate)	
				{	
								$this->registerPolicies($gate);	
				}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
CHECKING POLICIES
▸ Via Gate facade







▸ Via User Model



if	(Gate::denies('update',	$entry))	{				
			//	
}
if	($user->can('update',	$entry))	{	
			//	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
CHECKING POLICIES
▸ Via Blade shortcut:





▸ Via Policy Helper:

@can('update',	$entry)	
@endcan
if	(policy($entry)->update($user,	$entry))	{	
			//	
}
LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES
CONCLUSION: THE AUTHSERVICEPROVIDER + POLICIES LETS YOU
▸ Use existing model methods to determine authorization
▸ Group related authorization rules together for
maintainability
▸ Use nifty shortcuts in your blades

THANK YOU!
@SNIPEYHEAD

Weitere ähnliche Inhalte

Was ist angesagt?

Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
Ignacio Martín
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
Jonathan Wage
 

Was ist angesagt? (20)

The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
Love and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayLove and Loss: A Symfony Security Play
Love and Loss: A Symfony Security Play
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 Application
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
 

Ähnlich wie Laravel 5.2 Gates, AuthServiceProvider and Policies

Drupal 7 module development
Drupal 7 module developmentDrupal 7 module development
Drupal 7 module development
Adam Kalsey
 

Ähnlich wie Laravel 5.2 Gates, AuthServiceProvider and Policies (20)

Using and reusing CakePHP plugins
Using and reusing CakePHP pluginsUsing and reusing CakePHP plugins
Using and reusing CakePHP plugins
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
Zend/Expressive 3 – The Next Generation
Zend/Expressive 3 – The Next GenerationZend/Expressive 3 – The Next Generation
Zend/Expressive 3 – The Next Generation
 
TYPO3 Flow 2.0 (T3CON13 San Francisco)
TYPO3 Flow 2.0 (T3CON13 San Francisco)TYPO3 Flow 2.0 (T3CON13 San Francisco)
TYPO3 Flow 2.0 (T3CON13 San Francisco)
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019
 
SEA Open Hack - YAP
SEA Open Hack - YAPSEA Open Hack - YAP
SEA Open Hack - YAP
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
YAP / Open Mail Overview
YAP / Open Mail OverviewYAP / Open Mail Overview
YAP / Open Mail Overview
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Zendcon 09
Zendcon 09Zendcon 09
Zendcon 09
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Testing TYPO3 Applications
Testing TYPO3 ApplicationsTesting TYPO3 Applications
Testing TYPO3 Applications
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
 
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
 
The hidden gems of Spring Security
The hidden gems of Spring SecurityThe hidden gems of Spring Security
The hidden gems of Spring Security
 
Drupal 7 module development
Drupal 7 module developmentDrupal 7 module development
Drupal 7 module development
 
How To Structure Go Applications - Paul Bellamy - Codemotion Milan 2016
How To Structure Go Applications - Paul Bellamy - Codemotion Milan 2016How To Structure Go Applications - Paul Bellamy - Codemotion Milan 2016
How To Structure Go Applications - Paul Bellamy - Codemotion Milan 2016
 

Mehr von Alison Gianotto

Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses
Alison Gianotto
 
Getting users to care about security
Getting users to care about securityGetting users to care about security
Getting users to care about security
Alison Gianotto
 

Mehr von Alison Gianotto (10)

Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses
 
dotScale 2014
dotScale 2014dotScale 2014
dotScale 2014
 
LonestarPHP 2014 Security Keynote
LonestarPHP 2014 Security KeynoteLonestarPHP 2014 Security Keynote
LonestarPHP 2014 Security Keynote
 
MacIT 2014 - Essential Security & Risk Fundamentals
MacIT 2014 - Essential Security & Risk FundamentalsMacIT 2014 - Essential Security & Risk Fundamentals
MacIT 2014 - Essential Security & Risk Fundamentals
 
Failing well: Managing Risk in High Performance Applications
Failing well: Managing Risk in High Performance ApplicationsFailing well: Managing Risk in High Performance Applications
Failing well: Managing Risk in High Performance Applications
 
DNS 101 for Non-Techs
DNS 101 for Non-TechsDNS 101 for Non-Techs
DNS 101 for Non-Techs
 
Security Primer
Security PrimerSecurity Primer
Security Primer
 
Facebook Timeline for Pages
Facebook Timeline for PagesFacebook Timeline for Pages
Facebook Timeline for Pages
 
Getting users to care about security
Getting users to care about securityGetting users to care about security
Getting users to care about security
 
Twitter 101: 140 characters. Don't be a douche.
Twitter 101: 140 characters. Don't be a douche.Twitter 101: 140 characters. Don't be a douche.
Twitter 101: 140 characters. Don't be a douche.
 

Kürzlich hochgeladen

₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
Diya Sharma
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
 
Al Barsha Night Partner +0567686026 Call Girls Dubai
Al Barsha Night Partner +0567686026 Call Girls  DubaiAl Barsha Night Partner +0567686026 Call Girls  Dubai
Al Barsha Night Partner +0567686026 Call Girls Dubai
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 

Laravel 5.2 Gates, AuthServiceProvider and Policies

  • 1. OH MY! LARAVEL 5.2 GATES, AUTHSERVICEPROVIDERS AND POLICIES
  • 2. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES WHOAMI ▸ Alison Gianotto (aka “snipe”, aka @snipeyhead) ▸ One of the original members of SDPHP ;) ▸ Working with PHP for 15+ years ▸ CTO/Co-Founder of AnySha.re ▸ Founder of Grokability, Inc. ▸ Creator of Snipe-IT and other internet things
  • 3. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES PROBLEMS THE AUTHSERVICEPROVIDER SOLVES ▸ Much cleaner syntax in blades (@can and @cannot) ▸ One unified place to keep authorization rules ▸ Assumes a user instance. If no user available, it fails to false ▸ Can handle basic authorization (“does the user own this thing?”) or much more sophisticated rules based off your model methods.
  • 4. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP public function boot(GateContract $gate) { $this->registerPolicies($gate); // -------------------------------- // BEFORE ANYTHING ELSE // -------------------------------- $gate->before(function ($user, $ability) { if ($user->superadmin=='1') { return true; } });
  • 5. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES SCENARIO: USER COMMUNITY WEBSITE ▸ users table ▸ communities table with user_id for creator ▸ communities_users pivot table ▸ boolean is_admin ▸ entries table with created_by for creator
  • 6. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES SCENARIO: USER COMMUNITY WEBSITE: USERS ▸ Users CAN update their own posts ▸ Users CAN delete their own posts ▸ Users CANNOT update other users’ posts ▸ Uses CAN see other posts in a community ▸ … (etc) ▸ Users CAN message other users if they are not blocked ▸ Users CANNOT messages other users if they are blocked
  • 7. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP // Check if the user can update an entry $gate->define('update-entry', function ($user, $entry) { return $user->id === $entry->created_by; });
  • 8. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/USER.PHP (USER MODEL) /** * Checks if a user is a member of a community * * @param Community $community * @return boolean */ public function isMemberOfCommunity($community) { return $this->communities()
 ->where('community_id', '=', $community->id) ->count() > 0; }
  • 9. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/HTTP/ENTRIESCONTROLLER.PHP (VIA GATE FACADE) public function getEdit(Request $request, $id) { if ($entry = Entry::find($id)) { if (Gate::denies('update-entry', $entry)) { // You can return a 403 or whatever you want here abort(403); } return view('entries.edit'); } return redirect()->back()->with('error', 'Invalid entry.'); }
  • 10. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/HTTP/ENTRIESCONTROLLER.PHP (VIA USER MODEL) public function getEdit(Request $request, $id) { if ($entry = Entry::find($id)) { if ($request->user()->cannot('update-entry', $entry)) { // You could return a 403 response here, etc. abort(403); } return view('entries.edit'); } return redirect()->back()->with('error', 'Invalid entry.'); }
  • 11. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES RESOURCES/VIEWS/ENTRIES/VIEW.BLADE.PHP @can('update-entry', $entry) <a href="{{ route('entry.edit.form', $entry->id) }}">Edit</a> @endcan
  • 12. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/HTTP/ENTRIESCONTROLLER.PHP (VIA FORM REQUEST) /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $entryId = $this->route('entry'); return Gate::allows('update', Entry::findOrFail($entryId)); }
  • 13. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES SCENARIO: USER COMMUNITY WEBSITE: COMMUNITY ADMINS ▸ Community admins CAN edit their own community settings ▸ … (etc) ▸ Community admins CAN update user posts ▸ Community admins CAN add/remove users from community
  • 14. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/USER.PHP (USER MODEL) /** * Returns whether or not the user is an admin of a community * * @param object $community * @return boolean */ public function isAdminOfCommunity($community) { return $this->communities() ->where('community_id', '=', $community->id) ->where('is_admin', '=', '1') ->count() > 0; }
  • 15. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP // Check if the user can join a community // (they are not already a member) $gate->define('join-community', function ($user, $community) { if (!$user->isMemberOfCommunity($community)) { return true; } }); // Check if the user can update the community settings // (they are an admin) $gate->define('update-community', function ($user, $community) { if ($user->isAdminOfCommunity($community) ) { return true; } });
  • 16. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES THIS COULD GET OUT OF HAND QUICKLY. ENTER POLICIES.
  • 17. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES CREATING A POLICY > php artisan make:policy EntryPolicy Policy created successfully. > php artisan make:policy CommunityPolicy Policy created successfully.
  • 18. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/POLICIES/ENTRYPOLICY.PHP <?php namespace AppPolicies; use AppUser; use AppEntry; use IlluminateAuthAccessHandlesAuthorization; class EntryPolicy { use HandlesAuthorization; public function update(User $user, Entry $entry) { return $user->id === $entry->created_by; } public function delete(User $user, Entry $entry) { // etc } }
  • 19. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/POLICIES/COMMUNITYPOLICY.PHP <?php namespace AppPolicies; use AppUser; use AppCommunity; use IlluminateAuthAccessHandlesAuthorization; class CommunityPolicy { use HandlesAuthorization; public function update(User $user, Community $community) { return $user->id === $community->created_by; } public function delete(User $user, Community $community) { // etc } }
  • 20. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP <?php namespace AppProviders; use AppPoliciesEntryPolicy; use AppPoliciesCommunityPolicy; use IlluminateContractsAuthAccessGate as GateContract; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { protected $policies = [ Entry::class => EntryPolicy::class, Community::class => CommunityPolicy::class, ]; /** * Register any application authentication / authorization services. * * @param IlluminateContractsAuthAccessGate $gate * @return void */ public function boot(GateContract $gate) { $this->registerPolicies($gate); }
  • 21. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES APP/PROVIDERS/AUTHSERVICEPROVIDER.PHP <?php namespace AppProviders; use AppPoliciesEntryPolicy; use AppPoliciesCommunityPolicy; use IlluminateContractsAuthAccessGate as GateContract; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { protected $policies = [ Entry::class => EntryPolicy::class, Community::class => CommunityPolicy::class, ]; /** * Register any application authentication / authorization services. * * @param IlluminateContractsAuthAccessGate $gate * @return void */ public function boot(GateContract $gate) { $this->registerPolicies($gate); }
  • 22. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES CHECKING POLICIES ▸ Via Gate facade
 
 
 
 ▸ Via User Model
 
 if (Gate::denies('update', $entry)) { // } if ($user->can('update', $entry)) { // }
  • 23. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES CHECKING POLICIES ▸ Via Blade shortcut:
 
 
 ▸ Via Policy Helper:
 @can('update', $entry) @endcan if (policy($entry)->update($user, $entry)) { // }
  • 24. LARAVEL 5.2 GATES, AUTHSERVICEPROVIDER AND POLICIES CONCLUSION: THE AUTHSERVICEPROVIDER + POLICIES LETS YOU ▸ Use existing model methods to determine authorization ▸ Group related authorization rules together for maintainability ▸ Use nifty shortcuts in your blades