Middleware overriding other middleware in Laravel - php

I’m currently building my first larval app.
I’ve got two user types: buyers and sellers. However, they both have access to the same routes, but they need to be served up different templates and data. For example, both would have access to /home, but see something completely different.
I know I can use an if statement within the route, but that’s getting messy. To try and fix this, I’ve made two separate middlewares using two different route groups. Each middleware checks the user for permission, and logs them out if they don't have it, like so:
if ( Auth::user()->role !== 'buyer' ) {
return redirect( 'login' );
}
My goal:
If the user 'isBuyer', it only reads that middleware route group.
If the user 'isSeller', it only reads that middleware group.
I was hoping to use both in tandem:
// this will be triggered if they have the role 'buyer'
Route::group(['middleware' => 'isBuyer'], function () {
Route::get( '/', function ( ) {
return view( '/home-seller' );
});
});
//this will be triggered if they have the role 'seller'
Route::group(['middleware' => 'isSeller'], function () {
Route::get( '/', function ( ) {
return view( '/home-buyer' );
});
});
But it never reads the second group. It logs me out as a result of failing the auth test on the first group.
I assume this is because it's applying the middleware filter before it finishes reading the routes.php file. What's the best to deal with using the same routes for different user types?

You can use something like this:-
$middleware = '';
if ( Auth::user()->role == 'buyer' ) {
$middleware = 'isBuyer';
}
elseif(Auth::user()->role == 'seller') {
$middleware = 'isSeller';
}
else{
return redirect( 'login' );
}
Route::group(['middleware' => $middleware], function () {
Route::get( '/', function ( ) {
return view( '/home-seller' );
});
});

How about use a single route and render from the controller (returning a view) depending the role using "if blocks" for each role. Can you try that.

For this requirement, I think you should check the user role in your app controller/parent controller and depending on that role, redirect the user to their respective actions.

Related

Implement authorization in Laravel using external model

I want to protect my routes with authorization levels in laravel - client users have access to one group while admin gets access to a separate group. However, the laravel API I'm creating runs concurrent to the existing legacy app which uses its own Users class, rather than the pre rolled eloquent Users model that all the docs use.
So far I haven't been able to determine how best to create this custom authorization middleware.
Basically I'd like to do something like this:
Route::group(['middleware' => 'custom_auth', function() {
Route::get('/' function() {
return "Hello World";
}
}];
//where 'custom_auth' points to something like
function isAdmin() {
if (Core\User->check_is_admin()) {
return true;
} else {
return false;
}
}
Kind of an open-ended question, I know, so any links to blogs/docs/videos would be appreciated. Thanks!
Solved:
I added custom middleware to App\Http\Middleware that copied the structure of the prebuilt Middleware\Authenticate.php file and uses the custom isAdmin() method.
Make sure to include in HTTP\Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth_admin' => \App\Http\Middleware\AuthenticateAdmin::class, // <- New Middleware
...]
Then in my Routes\admin_api
Route::group(['middleware' => 'auth_admin'], function () {
Route::get('/', function () {
return "Hello World";
});
This all works!

Laravel, same URI, different route name, different middleware causes over loop

In laravel I've simply done this:
Route::group(["middleware" => "admin"], function() {
Route::get("/", "UserController#index")->name("user_index");
});
Route::group(["middleware" => "user", "as" => "User::"], function() {
Route::get("/", "DocumentController#index")->name("user_index");
});
The problem is when I am logged in as my Admin auth middleware, when going to "/" my browser returns too many redirects and stops. I'm guessing because the second route is removing this as when I print out php artisan route:list there is only one result for "/" and that's with the user middle's parameters so it's defo overriding the previous route.
What I don't understand is why would it do this is both have a separate middleware?
Both middlewares are extremely simple. Below is my admin
public function handle($request, Closure $next)
{
if ( Auth::check() && Auth::user()->hasRole("customer_service") )
{
return $next($request);
}
return redirect("/");
}
And my user's middleware is exactly alike except the role is different
This is probably wrong but this is what I did to fix this particular issue with the above.
public function index() {
return \Auth::user()->hasRole("trainer") ? \App::call("App\Http\Controllers\Trainer\UserController#index")
: \App::call("App\Http\Controllers\User\UserController#index");
}

Laravel 5 : Restrict access to controllers by User group

I've started learning Laravel 5.1 and so far I'm liking it! But there is one thing I don't get yet..
In my previous project I had 2 specific controllers (eg: "normal", "extended") which , after a successfull login, were called based on the Users user_group from the database.
If "Foo.Bar" enters his valid credentials and has the group normal he is redirected to NormalControler. Since I wasn't using any framework I restricted access to the other group by setting a $_SESSION with the group and checking it. So if another group tried to access that controller he got redirected.
How would this be achievable in Laravel 5? So far I have a controller which is callable without an Authentication and one restricted by this code in routes.php :
// All routes in the group are protected, only authed user are allowed to access them
Route::group(array('before' => 'auth'), function() {
// TO-DO : Seperate Controller access
});
And the login looks like this :
public function performLogin()
{
$logindata = array(
'username' => Input::get('user_name'),
'password' => Input::get('user_pass')
);
if( Auth::attempt( $logindata ) ){
// return \Redirect::to( check group and access this controller based on it);
}
else {
// TO-DO : Redirect back and show error message
dd('Login failed!');
}
}
----- EDIT -----
I've run the artisan command and made this middleware as you suggested :
namespace App\Http\Middleware;
use Closure;
use Request;
class GroupPermissions
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $group)
{
// Check User Group Permissions
if( $request->user()->group === $group ){
// Continue the request
return $next($request);
}
// Redirect
return redirect('restricted');
}
}
and edited this line into Kernel.php into $routeMiddleware :
'group.perm' => \App\Http\Middleware\GroupPermissions::class
I think this is done right so far, correct me if I'm wrong! Could I then do something like this to restrict the controllers?
Route::group(array('before' => 'auth'), function() {
Route::group( ['middleware' => 'group.perm', 'group' => 'normal'], function(){
Route::get('/normal/index', 'DummyNormalController#index');
});
Route::group( ['middleware' => 'group.perm', 'group' => 'extended'], function(){
Route::get('/extended/index', 'DummyExtendedController#index');
});
});
Ok, here is what you might do. Once user is logged in, you would check his credentials, get his user_group and decide what controller he should be redirected to.
if( Auth::attempt( $logindata ) ){
$user = Auth::user();
if ($user->inGroup('normal')) {
return redirect()->route('normal_controllers_named_route');
}
return redirect()->route('extended_controllers_named_route');
}
return redirect()->back()->withFlashMessage('don\'t get me wrong');
This will handle right routing after logging in.
The next portion where you need to protect you routes from unwanted user groups may be achieved with middlewares.
do an artisan command php artisan make:middleware ShouldBeInGroup
go to app/http/Kernel.php and add your new middleware to the routeMiddleware array. Key of the item might be anything you like. Let's call in inGroup. So: 'inGroup' => 'App\Http\Middleware\ShouldBeInGroup'
Now, in your controller, in constructor, you are able to call this middleware
$this->middleware('inGroup:extended'); //we also passing the name of the group
at lastly, work on the our middleware. Open newly created ShouldBeInGroup class and edit the handle method.
public function handle($request, Closure $next, $groupName)
{
if (Auth::check() && Auth::user()->inGroup($groupName)) {
return $next($request);
}
return redirect('/');
}
And finally you should work on inGroup method, that should return true of false. I assume that you have user_group field your users table. Then in your User eloquent model add the method
public function inGroup($groupName) {
return $this->user_group == $groupName;
}
Edit
if you want to use this middleware in your routes, you can do the following
Route::group(array('before' => 'auth'), function() {
Route::get('/normal/index', ['middleware' => 'group.perm:normal', 'uses' =>'DummyNormalController#index']);
}
But generally it's better to put all your middlewares into your Controller's constructor
public function __construct(){
$this->middleware('group.perm:normal'); // you can also pass in second argument to limit the methods this middleware is applied to : ['only' => ['store', 'update']];
}
And also on this note, Laravel provides built in auth middleware that you can use
public function __construct(){
$this->middleware('auth');
$this->middleware('group.perm:normal');
}
so then your routes would become much cleaner, just:
Route::get('normal/index', 'DummyNormalController#index');
I think the best way to do that is using middlewares. See the doc here
You can easily create a middleware using the following artisan command:
php artisan make:middleware ExtendedMiddleware
If you can't or don't want to use artisan, you need to create a class in The App/Http/Middleware folder.
In this class you'll need the following method to handle the request. In the method you can check for the user group.
public function handle($request, Closure $next)
{
// check user group
if( user_group_ok )
return $next($request); // Continue the request
return redirect('restricted'); // Redidrect
}
You can then use this middleware in your route.php file:
Route::group(['middleware' => 'auth'], function()
{
// Logged-in user with the extended group
Route::group(['middleware' => 'extended'], function()
{
// Restricted routes here
});
// Normal routes here
});
You can create a Middleware called : PermissionFilter
In PermissionFilter, you check if requesting user is in the group or not.
I can't provide a demo for now, but if you want I can make a demo later.
L5 middleware: http://laravel.com/docs/5.1/middleware

laravel how to create page restriction

Please tell me how to restrict the page using laravel,
i have 3 users.
1. admin, 2. client, 3. partner
i want if admin is logged in then open only- admin.index page
and if client logged in then open only- client.index page
i used in route.php following code-
Route::group(array('before' => 'role'), function(){
Route::resource('admin','AdminController#index');
Route::resource('client','clientController#index');
Route::resource('partner','partnerController#index');
});
using above code this if no any user login then it's coming properly,
and suppose if admin logged in, then page redirect to AdminController but,
if i hard coded (url) hit clientController or partnerController like http://localhost/laravel-login/public/client then client page is coming.
so please tell me how to avoid these
sorry for my english..
thanks
You may use different route filters for each route and create individual filters, for example:
Route::group(array('before' => 'auth'), function() {
Route::resource('admin','AdminController#index');
Route::resource('client','clientController#index');
Route::resource('partner','partnerController#index');
});
In each controller create a __construct method and add filter like:
public function __construct()
{
// In your AdminController
$this->beforeFilter(function() {
if(Auth::user()->role->name != 'admin') return redirect::to('/'); // home
});
}
Same way declare other filters in other controllers:
public function __construct()
{
// In your clientController
$this->beforeFilter(function() {
if(Auth::user()->role->name != 'client') return redirect::to('/'); // home
});
}
And so on. Check more on Laravel website about controller filtering.
The best way to restrict controllers to make new middleware , where you can define rules before the request. example :
I have a admin controller only register users with admin role can access it .
to do so when you define the route include the middleware .
// namespace = indicate where my controller is (sub folder )
// middleware = indicate what restriction i want for my controller you can pass one middleware or array of midlewares
Route::group([ 'namespace' => 'Admin','middleware' => ['auth' , 'IsAdmin'] ], function()
{
Route::resource('admin/posts', 'PostsController');
});
to create the middle ware and register it follow the documentation
look this is my middleware after
<?php
namespace App\Http\Middleware;
use Closure;
class IsAdmin
{
public function handle($request, Closure $next)
{
if($request->user()->is_admin == false ){
return redirect('/');
}
return $next($request);
}
}

Laravel auth check for all pages

I have created the Authentication, and its working perfectly. But there is some problem in checking the inner pages. For example,
Route::get('/', array('before' => 'auth' , 'do'=> function(){
return View::make('home.index');
}));
The index page is only visible for logged in users. But whenever I have go to the inner pages, for example example.com/products. The products page can be visible without log in.
Here is my solution.
/**
* Groups of routes that needs authentication to access.
*/
Route::group(array('before' => 'auth'), function()
{
Route::get('user/logout', array(
'uses' => 'UserController#doLogout',
));
Route::get('/', function() {
return Redirect::to('dashboard');
});
Route::get('dashboard', array(
'uses' => 'DashboardController#showIndex',
));
// More Routes
});
// Here Routes that don't need Auth.
There are several ways of applying filters for many routes.
Putting rotues into Route::group() or if you using controllers add the filter there, add it in the Base_Controller so it will be applied to all. You can also use filter patterns and use a regex which applies the filter to all except a few you don't want to.
Documentation
Route filters: http://laravel.com/docs/routing#route-filters
Example to the pattern filter, as the others are basicly in the docs. This one could be the fastest but also the most problematic because of the problematic way of registering a regex in this function (the * is actually converted into (.*)).
Route::filter('pattern: ^(?!login)*', 'auth');
This will apply auth to any route except example.com/login.
Route::group(['middleware' => ['auth']], function()
{
Route::get('list', 'EventsController#index');
});
Read more on the documentation page:
https://laravel.com/docs/5.2/routing#route-groups
There may be a better way but I take a whitelist approach. Everything is blocked from public except for what the pages I put in this array.
// config/application.php
return array(
'safe' => array(
'/',
'card/form_confirm',
'record/form_create',
'card/form_viewer',
'user/login',
'user/quick_login',
'user/register',
'info/how_it_works',
'info/pricing',
'info/faq',
'info/our_story',
'invite/accept',
'user/terms',
'user/privacy',
'email/send_email_queue',
'user/manual_login',
'checkin/',
'checkin/activate',
'system/list',
),
// routes.php
Route::filter('before', function()
{
// Maintenance mode
if(0) return Response::error( '503' );
/*
Secures parts of the application
from public viewing.
*/
$location = URI::segment(1) . '/' . URI::segment(2);
if(Auth::guest() && !in_array( $location, Config::get('application.safe')))
return Redirect::to( 'user/login' );
});
this code working fine with me
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
// Authentication Routes...
Route::get('/', 'HomeController#index')->name('home');
});
The same problem can be solved using a BaseController to extends all Controller have must logged user.
Example:
class SomeController extends BaseController
{
public function index() { return view('some.index');}
}
just add a __construct() method to BaseController
class BaseController extends Controller
{
protected $redirectTo = '/myIndex'; // Redirect after successfull login
public function __construct()
{
$this->middleware('auth'); // force all controllers extending this to pass auth
}
}
More info here
Just check if user is logged in in your views.
Or restrict all controller (if you use it)
Or check Route Groups, and give a filter to whole group of routes: http://laravel.com/docs/routing#groups
Route::filter('pattern: /*', array('name' => 'auth', function()
{
return View::make('home.index');
}));
It worked for me . take a look at it.
Route::when('*', 'auth.basic');
Route::get('api/getactorinfo/{actorname}', array('uses' =>'ActorController#getActorInfo'));
Route::get('api/getmovieinfo/{moviename}', array('uses' =>'MovieController#getMovieInfo'));
Route::put('api/addactor/{actorname}', array('uses' =>'ActorController#putActor'));
Route::put('api/addmovie/{moviename}/{movieyear}', array('uses' =>'MovieController#putMovie'));
Route::delete('api/deleteactor/{id}', array('uses' =>'ActorController#deleteActor'));
Route::delete('api/deletemovie/{id}', array('uses' =>'MovieController#deleteMovie'));

Categories