Laravel which route group does current route belong to - php

I am working with Laravel 5.5 and want to find out if the current route belongs to the auth:web middleware group. Is there a way to get this?
My routes:
/***********************************************************************************************************************
* Guest routes
**********************************************************************************************************************/
Route::group([
'middleware' => ['guest']
], function () {
Route::get("login", "Auth\LoginController#showLoginForm")->name("user.login");
Route::post("login", "Auth\LoginController#login")->name("user.do-login");
..................
});
/***********************************************************************************************************************
* All routes that require AUTH
**********************************************************************************************************************/
Route::group([
'middleware' => ['auth:user']
], function () {
..............
});
Something like below. Note I want the route group not the auth for the user:
$request()->currentRoute()->isGuest();
Is this possible? I cannot seem to find this in the Laravel docs.
I am trying to achieve executing a popup modal on all guest route pages without having to check and maintain a list of routes to test against. Thanks.

You can modify the handle method in the guest middleware class \App\Http\Middleware\RedirectIfAuthenticated, something like:
public function handle($request, Closure $next, $guard = null)
{
// share a token to all views for this middleware:
View::share('is_guest_route', true); // <-- this line is added
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
Make sure to also add:
use Illuminate\Support\Facades\View;
in the use-section of the file.
Now, in every view (blade file), you can do:
#if (isset($is_guest_route))
// do whatever is needed for guest routes
#endif

Fixed it with workaround. Added web. or app. prefix to all route names and now I search for this.
#if(substr(\Request::route()->getName(), 0, 4) !== 'web.')
#include('org.popupmsg.modal-pop')
#endif
with now the routes having changed to: web.user.login

Related

Test that middleware was used in Laravel

I have a post route inside a middleware that checks whether a user performing a request belongs to a specific role. I have 4 roles in total. And I have found it silly to write tests like :
testRole2CanNotDoAction
testRole3CanNotDoAction
testRole4CanNotDoAction
every time I want to test some action. So it would be really nice if I can just write 1 test
testMiddlewareWasCalled
to assure that route is placed in right place. How can I do it? To give you the context lets assume I have the following middleware:
class MustBeRole1
{
public function handle($request, Closure $next)
{
$user = $request->user();
if ($user && $user->isRole1()) {
return $next($request);
}
abort(403, 'You are not an role1!');
}
}
and following routes:
Route::group(['middleware' => ['isRole1']], function () {
Route::post('/testAction', ['as' => 'testAction', 'uses' => 'testActionController#test']);
}
How should my test look like?

Laravel multiple midleware for some route

I am developing web application with laravel 5.2.
What i need is i have some off account that distinguished by role. and i have to role that can access 1 route but other role cannot access. i have browsing and i have done everything that i found like
Route::group(['prefix' => '/', 'middleware' => ['role:user_a','role:user_b']], function(){someroute}
Route::group(['prefix' => '/', 'middleware' => ['role:user_a|role:user_b']], function(){someroute}
Route::group(['prefix' => '/', 'middleware' => ['role:user_a,role:user_b']], function(){someroute}
no one work. i dont know how to make my single route can be accessed by 2 role but disable for other role
You can create a middleware named role, read more about middleware in docs here
The handle method of middleware will be as:
public function handle($request, Closure $next)
{
if (auth()->user()->role('b')) {
return redirect('home');
}
// else users of other roles can visit the page
return $next($request);
}
Then you can use it in your route file as:
Route::group(['middleware' => 'role'], function () {
// someroute
});
i think you cant do this, but you can use this way.
Route::group(['prefix'=>'/', 'middleware' =>['role:user_a','role:user_b']],function(){
Route::group(['prefix'=>'userAorB', 'middleware' =>['role:user_a|role:user_b']],function(){ Routes });
Route::group(['prefix'=>'userAANDB', 'middleware' =>['role:user_a,role:user_b']],function(){ Routes });
})

more than one guard in route

I use laravel framework I want to use more than one guard in my route like :
Route::group([ 'middleware' => 'jwt.auth', 'guard' => ['biker','customer','operator']], function () {}
I have a script in AuthServiceProvider.php like below in boot section:
$this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $event) {
$route = $event->route;
if (!array_has($route->getAction(), 'guard')) {
return;
}
$routeGuard = array_get($route->getAction(), 'guard');
$this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) {
return $this->app['auth']->guard($routeGuard)->user();
});
$this->app['auth']->setDefaultDriver($routeGuard);
});
That work with just one guard in route like 'guard'=>'biker'
So how change that code in AuthServiceProvider.php to work with more than one gaurd in route
I know this is an old question but I just went through this issue and figured out how to solve it by myself. This might be useful for someone else. The solution is very simple, you just have to specify each guard after the name of your middleware separated by commas like this:
Route::group(['middleware' => ['auth:biker,customer,operator'], function() {
// ...
});
The guards are then sent to \Illuminate\Auth\Middleware\Authenticate function authenticate(array $guards) which checks every guard provided in the array.
This works for Laravel 5.4.
Also works for Laravel 6.0.

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);
}
}

Categories