Created
May 22, 2015 11:05
-
-
Save luceos/180fe5846df81f8b4b8e to your computer and use it in GitHub Desktop.
Route Authentication Middleware laravel 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait AuthenticatedTrait | |
{ | |
/** | |
* The check to see whether access is allowed to some route | |
* @return bool | |
*/ | |
public function allowedToAccessRoute() | |
{ | |
// your own check that should be used by default | |
return \Auth::check() && \Auth::user()->id == $this->id; | |
} | |
/** | |
* The redirect or action to undertake when disallowed to access route | |
* @return \RedirectResponse | |
*/ | |
public function disallowedRedirectResponse() | |
{ | |
return \Redirect::route('home'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http\Middleware; | |
use Closure; | |
use Eloquent; | |
class ModelAuthenticationMiddleware { | |
public function handle($request, Closure $next) | |
{ | |
foreach($request->route()->parameters() as $parameter) | |
{ | |
// chech whether parameter is an eloquent model | |
if($parameter instanceof Eloquent | |
// check whether eloquent model implements the AuthenticatedTrait or its own implementation | |
&& method_exists($parameter, 'allowedToAccessRoute') | |
// check whether eloquent model implements the AuthenticatedTrait or its own implementation | |
&& method_exists($parameter, 'disallowedRedirectResponse') | |
// check whether the user can access the route | |
&& !$parameter->allowedToAccessRoute()) | |
{ | |
return $parameter->disallowedRedirectResponse(); | |
} | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment