How to setup two route groups using middleware in Laravel 5.4 - laravel

I'm setting up a web application in which I would like to distinguish two route groups. Both groups work as expected on their own, but when combined one of them fails. I've checked documentation on L5.4 website and followed instructions. After a whole day of digging decided to ask you.
Here is my routes/web.php file:
Route::group(['middleware' => ['auth']], function () {
Route::group(['middleware' => ['medewerker']], function () {
Route::get('/urencorrectie','UrenRegelsController#urencorrectie');
});
Route::group(['middleware' => ['officemanager']], function () {
Route::get('/', 'DashboardController#index');
Route::post('/', 'DashboardController#index');
Route::get('/profile', function(){
return view('profile');});
});
});
Auth::routes();
Route::get('/home', 'HomeController#index');
In order to enable roles I addes a column Rolid to the user model. Rol 1 is officemanager and role 3 is employee.
Then in the subsequent middleware we find employee.php:
namespace App\Http\Middleware;
use Closure;
use Auth;
class Employee
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->Rolid=='3')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
The Middleware officemanager.php file contains:
namespace App\Http\Middleware;
use Closure;
use Auth;
class Officemanager
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user=Auth::user();
if(Auth::user()->Rolid=='1')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
The code as is produces the following result:
- When an Officemanager logs in, he/she is redirected to the proper routes. Everything works fine.
- When an Employee logs in, he/she gets redirected to the /home redirect (bottom of routing/web.php file).
Any clues or help is very welcome. Kinda stuck on something probably basic.
[UPDATE]
In kernel.php both classes are mapped:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'officemanager' => \App\Http\Middleware\Officemanager::class,
'employee' => \App\Http\Middleware\Employee::class,
];

The only thing that I can think of is that the Rolid of employee is not 3 - so try to debug it.
In general, it is not recommended to rely on DB ids in your code, because they can change between environments. I would add a relation for the user model and check the rol name:
User model:
public function role()
{
return $this->belongsTo('App\Role', 'Rolid');
}
Employee middlaware
class Employee
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->role->name == 'employee')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}
Office manger middleware:
class Officemanager
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->role->name == 'officemanager')
{
return $next($request);
}
else
{
return redirect('/home');
}
}
}

Related

Laravel Socialite google login transfers to login page again

I am try to integrate Google login with my application. Its working fine but it send your user back to login screen after google authentication. But when I click on the google login again it behaves like the user is already logged in. I dont want want the user to fall back to login when we comeback from google. Following are my files for controller and routes.
LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
/*
* Remove the socialite session variable if exists
*/
\Session::forget(config('access.socialite_session_name'));
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => __('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
*
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$errors = [];
if (config('auth.users.confirm_email') && !$user->confirmed) {
$errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
}
if (!$user->active) {
$errors = [$this->username() => __('auth.active')];
}
if ($errors) {
auth()->logout(); //logout
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
return redirect()->intended($this->redirectPath());
}
}
SocialLoginController
namespace App\Http\Controllers\Auth;
use App\Models\Auth\User\User;
use App\Services\RoleService;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Socialite;
class SocialLoginController extends LoginController
{
use AuthenticatesUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/admin';
public function redirect($provider)
{
return Socialite::driver($provider)->stateless()->redirect();
}
public function googleCallback($provider)
{
$userSocial = Socialite::driver($provider)->stateless()->user();
$user = User::where(['email' => $userSocial->getEmail()])->first();
if($user){
Auth::login($user,true);
return redirect('admin/partners');
} else {
$user = User::create([
'name' => $userSocial->getEmail(),
'email' => $userSocial->getEmail(),
]);
$user->roles()->attach([RoleService::ROLE_AUTHENTICATED]);
return redirect('/admin');
}
}
}
routes/auth.php
Route::group(['namespace' => 'Auth', 'middleware' => ['force.ssl']], function () {
// Authentication Routes...
Route::get('login', 'LoginController#showLoginForm')->name('login');
Route::post('login', 'LoginController#login');
Route::get('logout', 'LoginController#logout')->name('logout');
// Social Authentication Routes...
Route::post('login', 'SocialController#login');
Route::get('login/{provider}', 'SocialLoginController#redirect');
Route::get('login/{provider}/callback', 'SocialLoginController#googleCallback');
});
Middleware/RedirectIfAuthenicated.php
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
*
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/admin');
}
return $next($request);
}
}
return Socialite::driver($provider)->with(["prompt" => "select_account"])->redirect();
this is worked for me

The custom middleware is not working in the controller (Laravel)

I did a custom middleware to handle the auth api token and I call this middleware in the controller, but it's not working I added dd('') inside the middleware to see if it displays anything and it did not worked.
My middleware is:
<?php
namespace App\Http\Middleware;
use Closure;
use App\ApiUser;
class ApiAuth
{
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $var)
{
dd('If I put this dd it does not display anything');
$api_user_count = ApiAuth::where('api_token', $var)->count();
if($api_user_count == 0)
{
abort(403, "Auth failed")
}
return $next($request)
}
}
My controller is, how you can see I am sending a parameter to the middleware:
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->middleware('apiauth:'.$request->api_token);
$transaction = new Transaction;
$transaction->folio = $request->folio;
$transaction->dte_code = $request->dte_code;
$transaction->cashier = $request->cashier;
$transaction->amount = $request->amount;
if($transaction->save())
{
return response()->json('Ok', 201);
}
else
{
return response()->json('Error', 400);
}
}
I put the middleware in the path App\Http\Middleware\ApiAuth.php
I put the middleware in the kernel.php like this:
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'apiauth' => \App\Http\Middleware\ApiAuth::class, // THIS IS THE MINE
];
The weird thing is that it does not display any error, it's like it does not exist so I wonder what it's wrong with this?
Thanks!
instead of calling the middleware manually from your controller method you can register the middleware to apply only for that one method
public function __construct()
{
$this->middleware('apiauth')->only(['store']);
}
then you can extract the api_token from $request
$api_user_count = ApiAuth::where('api_token', $request-> api_token)->get()->count();

Pass parameter to Laravel Middleware

How can I passed a parameter in my middleware? I'm always getting this error
Here are the structure of my middlware
<?php
namespace App\Http\Middleware;
use Closure;
class SubDomainAccess
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $subdomain)
{
dd($subdomain); // Just trying to output the result here
return $next($request);
}
}
And on the Kernel.php under the $routeMiddleware I added this
'subdomain.access' => \App\Http\Middleware\SubDomainAccess::class,
Now on my web.php route file I added this
Route::group(['domain' => '{subdomain}.' . config('site.domain')], function () {
Route::get('/', ['as' => 'site.home', 'uses' => 'Site\Listing\ListingController#showListing'])->middleware('subdomain.access');
});
Also I tried this
Route::group(['domain' => '{subdomain}.' . config('site.domain')], function () {
Route::group(['middleware' => 'subdomain.access'], function () {
Route::get('/', ['as' => 'site.home', 'uses' => 'Site\Listing\ListingController#showListing']);
});
});
I tried this but nothings working. The only thing I haven't tried is placing the middleware in my controller constructor. But I don't wan't it that way as I think this is messy and it's more elegant if its within the route file.
Hope you can help me on this. Thanks
Ok so I managed to find a way to get the parameters without passing a third parameter on the middleware handle function thanks to this link
So what I did to retrieve the subdomain parameter is this
$request->route()->parameter('subdomain')
or if all parameter
$request->route()->parameters()
['middleware' => 'subdomain.access'] is wrong, try to use ['middleware' => 'subdomain:access'] with a : instead.
https://mattstauffer.co/blog/passing-parameters-to-middleware-in-laravel-5.1
Get URI from $request object and then return domain. No need to pass subdomain as params to middleware.
namespace App\Http\Middleware;
use Closure;
class SubDomainAccess
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $subdomain)
{
$sudomain = $this->getSubDomain($_SERVER['HTTP_HOST']);
return $next($request);
}
/**
* Get Subdomain name
* #param $uri
* #return bool
*/
private function getSubDomain($uri)
{
if(!empty($uri))
{
$host = explode('.', $uri);
if(sizeof($host) > 2)
return $host[0];
}
return false;
}
}

Session in middleware don't working

I'm storing a value in session in my middleware:
but when I refresh or go to new page the sessions is null.
what I do wrong?
class WorkflowContextMiddleware
{
/**
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
*/
public function handle(Request $request, Closure $next)
{
$types = $request->input('types', []);
foreach ($types as $type => $context) {
$request->session()->put("somekey.contexts.{$type}", $context);
$request->session()->save();
}
return $next($request);
}
}
route:
Route::group([
'prefix' => LaravelLocalisation::setLocale(),
'middleware' => ['web','localise','localeSessionRedirect']
], function () {
Route::get('/', function() {
(new \Illuminate\Support\Debug\Dumper)->dump(\Session::get('somekey'));
});
});
route provider:
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* #var string
*/
protected $namespace = 'Arcanine\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #param \Illuminate\Routing\Router $router
* #return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* #param \Illuminate\Routing\Router $router
* #return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Workflow\Http\Middleware\WorkflowContextMiddleware::class,
],
In order for your session to work, wrap all your routes within:
Route::group(['middleware' => 'web'], function () {
...
});
Remove web middleware from route group if you're using 5.2.27 and higher.
The thing is all routes in web.php are already using web middleware and adding it manually will cause problems with sessions.

Laravel 5 Middleware Doesn't work

I have problem with my custom middleware. It doesn't work. I have registered it in Kernel.php, only in $routeMiddleware. Here is my code:
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'test' => \App\Http\Middleware\TestMiddleware::class
];
}
Here is my Controller Code:
/**
* Middleware Activated
*/
public function __constructor()
{
$this->middleware('test');
}
and here is my custom middleware code:
protected $auth;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$this->auth->check())
{
return redirect('/');
}
return $next($request);
}
When I'm logout and type in url
profile/21
it shows me the profile of user with id 21. I want to prevent that with middleware but it won't work for me.
Does anyone have an idea how to do that or where is the mistake?
To make sure if the middleware gets triggered put something like die('middleware triggerd'); inside the handle function of the middleware.
I noticed you have function __constructor() instead of function __construct().
That might be the problem.
If it does trigger the middleware but you still have the same problem try replacing:
if (!$this->auth->check()) with if (!\Auth::check())

Resources